context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (CharacterController))] [RequireComponent(typeof (AudioSource))] public class 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, Physics.AllLayers, QueryTriggerInteraction.Ignore); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x*speed; m_MoveDir.z = desiredMove.z*speed; if (m_CharacterController.isGrounded) { m_MoveDir.y = -m_StickToGroundForce; if (m_Jump) { m_MoveDir.y = m_JumpSpeed; //PlayJumpSound(); m_Jump = false; m_Jumping = true; } } else { m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; } m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); m_MouseLook.UpdateCursorLock(); } private void PlayJumpSound() { m_AudioSource.clip = m_JumpSound; m_AudioSource.Play(); } private void ProgressStepCycle(float speed) { if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) { m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) { return; } m_NextStep = m_StepCycle + m_StepInterval; //PlayFootStepAudio(); } private void PlayFootStepAudio() { if (!m_CharacterController.isGrounded) { return; } // pick & play a random footstep sound from the array, // excluding sound at index 0 int n = Random.Range(1, m_FootstepSounds.Length); m_AudioSource.clip = m_FootstepSounds[n]; m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time m_FootstepSounds[n] = m_FootstepSounds[0]; m_FootstepSounds[0] = m_AudioSource.clip; } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } else { newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset(); } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); bool waswalking = m_IsWalking; #if !MOBILE_INPUT // On standalone builds, walk/run speed is modified by a key press. // keep track of whether or not the character is walking or running m_IsWalking = !Input.GetKey(KeyCode.LeftShift); #endif // set the desired speed to be walking or running speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed; m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } private void RotateView() { m_MouseLook.LookRotation (transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Generators\EnvQueryGenerator_Composite.h:16 namespace UnrealEngine { [ManageType("ManageEnvQueryGenerator_Composite")] public partial class ManageEnvQueryGenerator_Composite : UEnvQueryGenerator_Composite, IManageWrapper { public ManageEnvQueryGenerator_Composite(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_UpdateNodeVersion(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_Composite_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods public override void UpdateNodeVersion() => E__Supper__UEnvQueryGenerator_Composite_UpdateNodeVersion(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UEnvQueryGenerator_Composite_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UEnvQueryGenerator_Composite_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UEnvQueryGenerator_Composite_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UEnvQueryGenerator_Composite_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UEnvQueryGenerator_Composite_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UEnvQueryGenerator_Composite_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UEnvQueryGenerator_Composite_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UEnvQueryGenerator_Composite_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UEnvQueryGenerator_Composite_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UEnvQueryGenerator_Composite_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UEnvQueryGenerator_Composite_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UEnvQueryGenerator_Composite_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UEnvQueryGenerator_Composite_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UEnvQueryGenerator_Composite_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UEnvQueryGenerator_Composite_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageEnvQueryGenerator_Composite self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageEnvQueryGenerator_Composite(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageEnvQueryGenerator_Composite>(PtrDesc); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Search { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Client that can be used to manage and query indexes and documents, as /// well as manage other resources, on an Azure Search service. /// </summary> public partial class SearchServiceClient : ServiceClient<SearchServiceClient>, ISearchServiceClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IDataSourcesOperations. /// </summary> public virtual IDataSourcesOperations DataSources { get; private set; } /// <summary> /// Gets the IIndexersOperations. /// </summary> public virtual IIndexersOperations Indexers { get; private set; } /// <summary> /// Gets the IIndexesOperations. /// </summary> public virtual IIndexesOperations Indexes { get; private set; } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchServiceClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchServiceClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchServiceClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SearchServiceClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SearchServiceClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SearchServiceClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SearchServiceClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.DataSources = new DataSourcesOperations(this); this.Indexers = new IndexersOperations(this); this.Indexes = new IndexesOperations(this); this.BaseUri = new Uri("http://localhost"); this.ApiVersion = "2015-02-28-Preview"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DataChangeDetectionPolicy>("@odata.type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DataChangeDetectionPolicy>("@odata.type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<DataDeletionDetectionPolicy>("@odata.type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<DataDeletionDetectionPolicy>("@odata.type")); SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<ScoringFunction>("type")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<ScoringFunction>("type")); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ using System.Collections; using System.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { internal sealed class SqlConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class DEFAULT { internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const string AttachDBFilename = ""; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const string Current_Language = ""; internal const string Data_Source = ""; internal const bool Encrypt = false; internal const string FailoverPartner = ""; internal const string Initial_Catalog = ""; internal const bool Integrated_Security = false; internal const int Load_Balance_Timeout = 0; // default of 0 means don't use internal const bool MARS = false; internal const int Max_Pool_Size = 100; internal const int Min_Pool_Size = 0; internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; internal const int Packet_Size = 8000; internal const string Password = ""; internal const bool Persist_Security_Info = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string Type_System_Version = ""; internal const string User_ID = ""; internal const bool User_Instance = false; internal const bool Replication = false; internal const int Connect_Retry_Count = 1; internal const int Connect_Retry_Interval = 10; } // SqlConnection ConnectionString Options // keys must be lowercase! internal static class KEY { internal const string ApplicationIntent = "applicationintent"; internal const string Application_Name = "application name"; internal const string AsynchronousProcessing = "asynchronous processing"; internal const string AttachDBFilename = "attachdbfilename"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; internal const string Data_Source = "data source"; internal const string Encrypt = "encrypt"; internal const string Enlist = "enlist"; internal const string FailoverPartner = "failover partner"; internal const string Initial_Catalog = "initial catalog"; internal const string Integrated_Security = "integrated security"; internal const string Load_Balance_Timeout = "load balance timeout"; internal const string MARS = "multipleactiveresultsets"; internal const string Max_Pool_Size = "max pool size"; internal const string Min_Pool_Size = "min pool size"; internal const string MultiSubnetFailover = "multisubnetfailover"; internal const string Network_Library = "network library"; internal const string Packet_Size = "packet size"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Pooling = "pooling"; internal const string TransactionBinding = "transaction binding"; internal const string TrustServerCertificate = "trustservercertificate"; internal const string Type_System_Version = "type system version"; internal const string User_ID = "user id"; internal const string User_Instance = "user instance"; internal const string Workstation_Id = "workstation id"; internal const string Replication = "replication"; internal const string Connect_Retry_Count = "connectretrycount"; internal const string Connect_Retry_Interval = "connectretryinterval"; } // Constant for the number of duplicate options in the connnection string private static class SYNONYM { // application name internal const string APP = "app"; internal const string Async = "async"; // attachDBFilename internal const string EXTENDED_PROPERTIES = "extended properties"; internal const string INITIAL_FILE_NAME = "initial file name"; // connect timeout internal const string CONNECTION_TIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; // current language internal const string LANGUAGE = "language"; // data source internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORK_ADDRESS = "network address"; // initial catalog internal const string DATABASE = "database"; // integrated security internal const string TRUSTED_CONNECTION = "trusted_connection"; // load balance timeout internal const string Connection_Lifetime = "connection lifetime"; // network library internal const string NET = "net"; internal const string NETWORK = "network"; // password internal const string Pwd = "pwd"; // persist security info internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; // user id internal const string UID = "uid"; internal const string User = "user"; // workstation id internal const string WSID = "wsid"; // make sure to update SynonymCount value below when adding or removing synonyms } internal const int SynonymCount = 18; internal const int DeprecatedSynonymCount = 3; internal enum TypeSystem { Latest = 2008, SQLServer2000 = 2000, SQLServer2005 = 2005, SQLServer2008 = 2008, SQLServer2012 = 2012, } internal static class TYPESYSTEMVERSION { internal const string Latest = "Latest"; internal const string SQL_Server_2000 = "SQL Server 2000"; internal const string SQL_Server_2005 = "SQL Server 2005"; internal const string SQL_Server_2008 = "SQL Server 2008"; internal const string SQL_Server_2012 = "SQL Server 2012"; } static private Hashtable s_sqlClientSynonyms; private readonly bool _integratedSecurity; private readonly bool _encrypt; private readonly bool _trustServerCertificate; private readonly bool _mars; private readonly bool _persistSecurityInfo; private readonly bool _pooling; private readonly bool _replication; private readonly bool _userInstance; private readonly bool _multiSubnetFailover; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; private readonly int _minPoolSize; private readonly int _packetSize; private readonly int _connectRetryCount; private readonly int _connectRetryInterval; private readonly ApplicationIntent _applicationIntent; private readonly string _applicationName; private readonly string _attachDBFileName; private readonly string _currentLanguage; private readonly string _dataSource; private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB private readonly string _failoverPartner; private readonly string _initialCatalog; private readonly string _password; private readonly string _userID; private readonly string _workstationId; private readonly TypeSystem _typeSystemVersion; internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms()) { ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing); ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset); ThrowUnsupportedIfKeywordSet(KEY.Context_Connection); ThrowUnsupportedIfKeywordSet(KEY.Enlist); ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding); // Network Library has its own special error message if (ContainsKey(KEY.Network_Library)) { throw SQL.NetworkLibraryKeywordNotSupported(); } _integratedSecurity = ConvertValueToIntegratedSecurity(); _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } if (true == _userInstance && !ADP.IsEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (ADP.IsEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount < 0) || (_connectRetryCount > 255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } } // This c-tor is used to create SSE and user instance connection strings when user instance is set to true // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _encrypt = connectionOptions._encrypt; _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _workstationId = connectionOptions._workstationId; _typeSystemVersion = connectionOptions._typeSystemVersion; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); } internal bool IntegratedSecurity { get { return _integratedSecurity; } } // We always initialize in Async mode so that both synchronous and asynchronous methods // will work. In the future we can deprecate the keyword entirely. internal bool Asynchronous { get { return true; } } // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security internal bool ConnectionReset { get { return true; } } // internal bool EnableUdtDownload { get { return _enableUdtDownload;} } internal bool Encrypt { get { return _encrypt; } } internal bool TrustServerCertificate { get { return _trustServerCertificate; } } internal bool MARS { get { return _mars; } } internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } } internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } } internal bool Pooling { get { return _pooling; } } internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } internal int MinPoolSize { get { return _minPoolSize; } } internal int PacketSize { get { return _packetSize; } } internal int ConnectRetryCount { get { return _connectRetryCount; } } internal int ConnectRetryInterval { get { return _connectRetryInterval; } } internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } } internal string ApplicationName { get { return _applicationName; } } internal string AttachDBFilename { get { return _attachDBFileName; } } internal string CurrentLanguage { get { return _currentLanguage; } } internal string DataSource { get { return _dataSource; } } internal string LocalDBInstance { get { return _localDBInstance; } } internal string FailoverPartner { get { return _failoverPartner; } } internal string InitialCatalog { get { return _initialCatalog; } } internal string Password { get { return _password; } } internal string UserID { get { return _userID; } } internal string WorkstationId { get { return _workstationId; } } internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } } // this hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string internal static Hashtable GetParseSynonyms() { Hashtable hash = s_sqlClientSynonyms; if (null == hash) { hash = new Hashtable(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount); hash.Add(KEY.ApplicationIntent, KEY.ApplicationIntent); hash.Add(KEY.Application_Name, KEY.Application_Name); hash.Add(KEY.AsynchronousProcessing, KEY.AsynchronousProcessing); hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename); hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout); hash.Add(KEY.Connection_Reset, KEY.Connection_Reset); hash.Add(KEY.Context_Connection, KEY.Context_Connection); hash.Add(KEY.Current_Language, KEY.Current_Language); hash.Add(KEY.Data_Source, KEY.Data_Source); hash.Add(KEY.Encrypt, KEY.Encrypt); hash.Add(KEY.Enlist, KEY.Enlist); hash.Add(KEY.FailoverPartner, KEY.FailoverPartner); hash.Add(KEY.Initial_Catalog, KEY.Initial_Catalog); hash.Add(KEY.Integrated_Security, KEY.Integrated_Security); hash.Add(KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout); hash.Add(KEY.MARS, KEY.MARS); hash.Add(KEY.Max_Pool_Size, KEY.Max_Pool_Size); hash.Add(KEY.Min_Pool_Size, KEY.Min_Pool_Size); hash.Add(KEY.MultiSubnetFailover, KEY.MultiSubnetFailover); hash.Add(KEY.Network_Library, KEY.Network_Library); hash.Add(KEY.Packet_Size, KEY.Packet_Size); hash.Add(KEY.Password, KEY.Password); hash.Add(KEY.Persist_Security_Info, KEY.Persist_Security_Info); hash.Add(KEY.Pooling, KEY.Pooling); hash.Add(KEY.Replication, KEY.Replication); hash.Add(KEY.TrustServerCertificate, KEY.TrustServerCertificate); hash.Add(KEY.TransactionBinding, KEY.TransactionBinding); hash.Add(KEY.Type_System_Version, KEY.Type_System_Version); hash.Add(KEY.User_ID, KEY.User_ID); hash.Add(KEY.User_Instance, KEY.User_Instance); hash.Add(KEY.Workstation_Id, KEY.Workstation_Id); hash.Add(KEY.Connect_Retry_Count, KEY.Connect_Retry_Count); hash.Add(KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval); hash.Add(SYNONYM.APP, KEY.Application_Name); hash.Add(SYNONYM.Async, KEY.AsynchronousProcessing); hash.Add(SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename); hash.Add(SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename); hash.Add(SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.LANGUAGE, KEY.Current_Language); hash.Add(SYNONYM.ADDR, KEY.Data_Source); hash.Add(SYNONYM.ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.NETWORK_ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.SERVER, KEY.Data_Source); hash.Add(SYNONYM.DATABASE, KEY.Initial_Catalog); hash.Add(SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security); hash.Add(SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout); hash.Add(SYNONYM.NET, KEY.Network_Library); hash.Add(SYNONYM.NETWORK, KEY.Network_Library); hash.Add(SYNONYM.Pwd, KEY.Password); hash.Add(SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info); hash.Add(SYNONYM.UID, KEY.User_ID); hash.Add(SYNONYM.User, KEY.User_ID); hash.Add(SYNONYM.WSID, KEY.Workstation_Id); Debug.Assert(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount == hash.Count, "incorrect initial ParseSynonyms size"); s_sqlClientSynonyms = hash; } return hash; } internal string ObtainWorkstationId() { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; if (null == result) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted // the information is shared with the server, but not directly with the user result = string.Empty; } return result; } private void ValidateValueLength(string value, int limit, string key) { if (limit < value.Length) { throw ADP.InvalidConnectionOptionValueLength(key, limit); } } internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent() { object value = base.Parsetable[KEY.ApplicationIntent]; if (value == null) { return DEFAULT.ApplicationIntent; } // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor, // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool) try { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } // ArgumentException and other types are raised as is (no wrapping) } internal void ThrowUnsupportedIfKeywordSet(string keyword) { if (ContainsKey(keyword)) { throw SQL.UnsupportedKeyword(keyword); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Script.Services; using System.Web.Services; using System.Web.UI; using System.Xml; using System.Xml.Xsl; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Web.WebServices; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.macro; using umbraco.cms.businesslogic.template; using umbraco.cms.businesslogic.web; using System.Net; using System.Collections; using umbraco.NodeFactory; namespace umbraco.presentation.webservices { /// <summary> /// Summary description for codeEditorSave /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] [ScriptService] public class codeEditorSave : UmbracoAuthorizedWebService { [WebMethod] public string SaveCss(string fileName, string oldName, string fileContents, int fileID) { if (AuthorizeRequest(DefaultApps.settings.ToString())) { var stylesheet = Services.FileService.GetStylesheetByName(oldName.EnsureEndsWith(".css")); if (stylesheet == null) throw new InvalidOperationException("No stylesheet found with name " + oldName); stylesheet.Content = fileContents; if (fileName.InvariantEquals(oldName) == false) { //it's changed which means we need to change the path stylesheet.Path = stylesheet.Path.TrimEnd(oldName.EnsureEndsWith(".css")) + fileName.EnsureEndsWith(".css"); } Services.FileService.SaveStylesheet(stylesheet, Security.CurrentUser.Id); return "true"; } return "false"; } [WebMethod] public string SaveXslt(string fileName, string oldName, string fileContents, bool ignoreDebugging) { if (AuthorizeRequest(DefaultApps.developer.ToString())) { IOHelper.EnsurePathExists(SystemDirectories.Xslt); // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), SystemDirectories.Xslt); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), new List<string>() { "xsl", "xslt" }); StreamWriter SW; string tempFileName = IOHelper.MapPath(SystemDirectories.Xslt + "/" + DateTime.Now.Ticks + "_temp.xslt"); SW = File.CreateText(tempFileName); SW.Write(fileContents); SW.Close(); // Test the xslt string errorMessage = ""; if (!ignoreDebugging) { try { // Check if there's any documents yet string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*"; if (content.Instance.XmlContent.SelectNodes(xpath).Count > 0) { var macroXML = new XmlDocument(); macroXML.LoadXml("<macro/>"); var macroXSLT = new XslCompiledTransform(); var umbPage = new page(content.Instance.XmlContent.SelectSingleNode("//* [@parentID = -1]")); var xslArgs = macro.AddMacroXsltExtensions(); var lib = new library(umbPage); xslArgs.AddExtensionObject("urn:umbraco.library", lib); HttpContext.Current.Trace.Write("umbracoMacro", "After adding extensions"); // Add the current node xslArgs.AddParam("currentPage", "", library.GetXmlNodeById(umbPage.PageID.ToString())); HttpContext.Current.Trace.Write("umbracoMacro", "Before performing transformation"); // Create reader and load XSL file // We need to allow custom DTD's, useful for defining an ENTITY var readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; using (var xmlReader = XmlReader.Create(tempFileName, readerSettings)) { var xslResolver = new XmlUrlResolver(); xslResolver.Credentials = CredentialCache.DefaultCredentials; macroXSLT.Load(xmlReader, XsltSettings.TrustedXslt, xslResolver); xmlReader.Close(); // Try to execute the transformation var macroResult = new HtmlTextWriter(new StringWriter()); macroXSLT.Transform(macroXML, xslArgs, macroResult); macroResult.Close(); File.Delete(tempFileName); } } else { //errorMessage = ui.Text("developer", "xsltErrorNoNodesPublished"); File.Delete(tempFileName); //base.speechBubble(speechBubbleIcon.info, ui.Text("errors", "xsltErrorHeader", base.getUser()), "Unable to validate xslt as no published content nodes exist."); } } catch (Exception errorXslt) { File.Delete(tempFileName); errorMessage = (errorXslt.InnerException ?? errorXslt).ToString(); // Full error message errorMessage = errorMessage.Replace("\n", "<br/>\n"); //closeErrorMessage.Visible = true; // Find error var m = Regex.Matches(errorMessage, @"\d*[^,],\d[^\)]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match mm in m) { string[] errorLine = mm.Value.Split(','); if (errorLine.Length > 0) { var theErrorLine = int.Parse(errorLine[0]); var theErrorChar = int.Parse(errorLine[1]); errorMessage = "Error in XSLT at line " + errorLine[0] + ", char " + errorLine[1] + "<br/>"; errorMessage += "<span style=\"font-family: courier; font-size: 11px;\">"; var xsltText = fileContents.Split("\n".ToCharArray()); for (var i = 0; i < xsltText.Length; i++) { if (i >= theErrorLine - 3 && i <= theErrorLine + 1) if (i + 1 == theErrorLine) { errorMessage += "<b>" + (i + 1) + ": &gt;&gt;&gt;&nbsp;&nbsp;" + Server.HtmlEncode(xsltText[i].Substring(0, theErrorChar)); errorMessage += "<span style=\"text-decoration: underline; border-bottom: 1px solid red\">" + Server.HtmlEncode( xsltText[i].Substring(theErrorChar, xsltText[i].Length - theErrorChar)). Trim() + "</span>"; errorMessage += " &lt;&lt;&lt;</b><br/>"; } else errorMessage += (i + 1) + ": &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + Server.HtmlEncode(xsltText[i]) + "<br/>"; } errorMessage += "</span>"; } } } } if (errorMessage == "" && fileName.ToLower().EndsWith(".xslt")) { //Hardcoded security-check... only allow saving files in xslt directory... var savePath = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName); if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Xslt + "/"))) { //deletes the old xslt file if (fileName != oldName) { var p = IOHelper.MapPath(SystemDirectories.Xslt + "/" + oldName); if (File.Exists(p)) File.Delete(p); } SW = File.CreateText(savePath); SW.Write(fileContents); SW.Close(); errorMessage = "true"; } else { errorMessage = "Illegal path"; } } File.Delete(tempFileName); return errorMessage; } return "false"; } [WebMethod] public string SaveDLRScript(string fileName, string oldName, string fileContents, bool ignoreDebugging) { if (AuthorizeRequest(DefaultApps.developer.ToString())) { if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName"); var allowedExtensions = new List<string>(); foreach (var lang in MacroEngineFactory.GetSupportedUILanguages()) { if (!allowedExtensions.Contains(lang.Extension)) allowedExtensions.Add(lang.Extension); } // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName), SystemDirectories.MacroScripts); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName), allowedExtensions); //As Files Can Be Stored In Sub Directories, So We Need To Get The Exeuction Directory Correct var lastOccurance = fileName.LastIndexOf('/') + 1; var directory = fileName.Substring(0, lastOccurance); var fileNameWithExt = fileName.Substring(lastOccurance); var tempFileName = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + directory + DateTime.Now.Ticks + "_" + fileNameWithExt); using (var sw = new StreamWriter(tempFileName, false, Encoding.UTF8)) { sw.Write(fileContents); sw.Close(); } var errorMessage = ""; if (!ignoreDebugging) { var root = Document.GetRootDocuments().FirstOrDefault(); if (root != null) { var args = new Hashtable(); var n = new Node(root.Id); args.Add("currentPage", n); try { var engine = MacroEngineFactory.GetByFilename(tempFileName); var tempErrorMessage = ""; var xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*"; if ( !engine.Validate(fileContents, tempFileName, Node.GetNodeByXpath(xpath), out tempErrorMessage)) errorMessage = tempErrorMessage; } catch (Exception err) { errorMessage = err.ToString(); } } } if (errorMessage == "") { var savePath = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + fileName); //deletes the file if (fileName != oldName) { var p = IOHelper.MapPath(SystemDirectories.MacroScripts + "/" + oldName); if (File.Exists(p)) File.Delete(p); } using (var sw = new StreamWriter(savePath, false, Encoding.UTF8)) { sw.Write(fileContents); sw.Close(); } errorMessage = "true"; } File.Delete(tempFileName); return errorMessage.Replace("\n", "<br/>\n"); } return "false"; } //[WebMethod] //public string SavePartialView(string filename, string oldName, string contents) //{ // if (BasePage.ValidateUserContextID(BasePage.umbracoUserContextID)) // { // var folderPath = SystemDirectories.MvcViews + "/Partials/"; // // validate file // IOHelper.ValidateEditPath(IOHelper.MapPath(folderPath + filename), folderPath); // // validate extension // IOHelper.ValidateFileExtension(IOHelper.MapPath(folderPath + filename), new[] {"cshtml"}.ToList()); // var val = contents; // string returnValue; // var saveOldPath = oldName.StartsWith("~/") ? IOHelper.MapPath(oldName) : IOHelper.MapPath(folderPath + oldName); // var savePath = filename.StartsWith("~/") ? IOHelper.MapPath(filename) : IOHelper.MapPath(folderPath + filename); // //Directory check.. only allow files in script dir and below to be edited // if (savePath.StartsWith(IOHelper.MapPath(folderPath))) // { // //deletes the old file // if (savePath != saveOldPath) // { // if (File.Exists(saveOldPath)) // File.Delete(saveOldPath); // } // using (var sw = File.CreateText(savePath)) // { // sw.Write(val); // } // returnValue = "true"; // } // else // { // returnValue = "illegalPath"; // } // return returnValue; // } // return "false"; //} [Obsolete("This method has been superceded by the REST service /Umbraco/RestServices/SaveFile/SaveScript which is powered by the SaveFileController.")] [WebMethod] public string SaveScript(string filename, string oldName, string contents) { if (AuthorizeRequest(DefaultApps.settings.ToString())) { // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename), SystemDirectories.Scripts); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename), UmbracoConfig.For.UmbracoSettings().Content.ScriptFileTypes.ToList()); var val = contents; string returnValue; try { var saveOldPath = ""; saveOldPath = oldName.StartsWith("~/") ? IOHelper.MapPath(oldName) : IOHelper.MapPath(SystemDirectories.Scripts + "/" + oldName); var savePath = ""; savePath = filename.StartsWith("~/") ? IOHelper.MapPath(filename) : IOHelper.MapPath(SystemDirectories.Scripts + "/" + filename); //Directory check.. only allow files in script dir and below to be edited if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Scripts + "/")) || savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Masterpages + "/"))) { //deletes the old file if (savePath != saveOldPath) { if (File.Exists(saveOldPath)) File.Delete(saveOldPath); } //ensure the folder exists before saving Directory.CreateDirectory(Path.GetDirectoryName(savePath)); using (var sw = File.CreateText(savePath)) { sw.Write(val); sw.Close(); } returnValue = "true"; } else { returnValue = "illegalPath"; } } catch { returnValue = "false"; } return returnValue; } return "false"; } [Obsolete("This method has been superceded by the REST service /Umbraco/RestServices/SaveFile/SaveTemplate which is powered by the SaveFileController.")] [WebMethod] public string SaveTemplate(string templateName, string templateAlias, string templateContents, int templateID, int masterTemplateID) { if (AuthorizeRequest(DefaultApps.settings.ToString())) { var _template = new Template(templateID); string retVal = "false"; if (_template != null) { _template.Text = templateName; _template.Alias = templateAlias; _template.MasterTemplate = masterTemplateID; _template.Design = templateContents; _template.Save(); retVal = "true"; } return retVal; } return "false"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128Int16Byte() { var test = new SimpleUnaryOpTest__ConvertToVector128Int16Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using the pointer overload test.RunBasicScenario_Ptr(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using the pointer overload test.RunReflectionScenario_Ptr(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128Int16Byte { private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Byte[] _data = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar; private Vector128<Byte> _fld; private SimpleUnaryOpTest__DataTable<Int16, Byte> _dataTable; static SimpleUnaryOpTest__ConvertToVector128Int16Byte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleUnaryOpTest__ConvertToVector128Int16Byte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int16, Byte>(_data, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.ConvertToVector128Int16( Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Ptr() { var result = Sse41.ConvertToVector128Int16( (Byte*)_dataTable.inArrayPtr ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.ConvertToVector128Int16( Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.ConvertToVector128Int16( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int16), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Ptr() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int16), new Type[] { typeof(Byte*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(Byte*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int16), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int16), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.ConvertToVector128Int16( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr); var result = Sse41.ConvertToVector128Int16(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int16(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int16(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector128Int16Byte(); var result = Sse41.ConvertToVector128Int16(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.ConvertToVector128Int16(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Int16[] result, [CallerMemberName] string method = "") { if (result[0] != firstOp[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int16)}<Int16>(Vector128<Byte>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using EasyLOB.Library; using System; using System.Configuration; using System.Data; using System.Data.Common; namespace EasyLOB.Persistence { /// <summary> /// AdoNet Helper /// </summary> public static partial class AdoNetHelper { #region Methods Properties /// <summary> /// Sequence prefix. /// </summary> public static string SequencePrefix { get { return LibraryHelper.AppSettings<string>("AdoNet.SequencePrefix"); } } /// <summary> /// Records by Search. /// </summary> public static int RecordsBySearch { get { return LibraryHelper.AppSettings<int>("AdoNet.RecordsBySearch"); } } #endregion Methods Properties #region Methods Connection /// <summary> /// Get connection. /// </summary> /// <param name="connectionName">Connection name</param> /// <returns></returns> public static DbConnection GetConnection(string connectionName) { DbProviderFactory provider = GetProvider(connectionName); DbConnection connection = provider.CreateConnection(); connection.ConnectionString = GetConnectionString(connectionName); return connection; } /// <summary> /// Get connection string by connection name. /// </summary> /// <param name="connectionName">Connection name</param> /// <returns></returns> public static string GetConnectionString(string connectionName) { string connectionString = LibraryHelper.ConnectionStrings(connectionName); return connectionString; } /// <summary> /// Get connection user and password. /// </summary> /// <param name="connectionName">Connection name</param> /// <returns></returns> public static string[] GetUserPassword(string connectionName) { string[] result = new string[] { "", "" }; string cs = LibraryHelper.ConnectionStrings(connectionName); string[] tokens = cs.Split(';'); for (var i = 0; i < tokens.Length; i++) { var token = tokens[i]; if (token.StartsWith("User ID")) { result[0] = token.Substring(token.IndexOf("=") + 1); } if (token.StartsWith("Password")) { result[1] = token.Substring(token.IndexOf("=") + 1); } } // using System.Linq; //string connectionString = LibraryHelper.ConnectionStrings(connectionName); //var tokens = connectionString.Split(';').Select(x => x.Split('=')); //string userId = tokens.First(n => n[0].Equals("User ID").Select(x => x[1]); //string password = tokens.First(n => n[0].Equals("Password")).Select(x => x[1]); return result; } #endregion Methods Connection #region Methods DBMS /// <summary> /// Get ZDBMS /// </summary> /// <param name="provider">Provider</param> /// <returns></returns> public static ZDBMS GetDBMS(DbProviderFactory provider) { string providerType = provider.GetType().FullName; switch (providerType) { case "FirebirdSql.Data.FirebirdClient.FirebirdClientFactory": return ZDBMS.Firebird; case "MySql.Data.MySqlClient.MySqlClientFactory": return ZDBMS.MySQL; case "Oracle.DataAccess.Client.OracleClientFactory": case "System.Data.OracleClient.OracleClientFactory": return ZDBMS.Oracle; case "Npgsql.NpgsqlFactory": return ZDBMS.PostgreSQL; case "System.Data.SQLite.SQLiteFactory": return ZDBMS.SQLite; case "System.Data.SqlClient.SqlClientFactory": return ZDBMS.SQLServer; default: return ZDBMS.Unknown; } } /// <summary> /// Get ZDBMS /// </summary> /// <param name="connection">Connection name | Connection string | Connection provider</param> /// <returns></returns> public static ZDBMS GetDBMS(string connection) { if (connection.Contains("FirebirdSql")) { return ZDBMS.Firebird; } else if (connection.Contains("MySql")) { return ZDBMS.MySQL; } else if (connection.Contains("Oracle")) { return ZDBMS.Oracle; } else if (connection.Contains("Npgsql")) { return ZDBMS.PostgreSQL; } else if (connection.Contains("SQLite")) { return ZDBMS.SQLite; } else if (connection.Contains("SqlClient")) { return ZDBMS.SQLServer; } else { return ZDBMS.Unknown; } //DbProviderFactory provider = GetProvider(connection); // Connection Name //if (provider != null) //{ // return GetDBMS(provider); //} //else //{ // return ZDBMS.Unknown; //} } #endregion Methods DBMS #region Methods DbType /// <summary> /// Get database type. /// </summary> /// <param name="type">Type</param> /// <returns></returns> public static DbType GetDbType(Type type) { return GetDbType(type.Name); } /// <summary> /// Get database type. /// </summary> /// <param name="type">Type</param> /// <returns></returns> public static DbType GetDbType(string type) { switch (type) { case "System.DateTime": return DbType.DateTime; case "System.Decimal": return DbType.Decimal; case "System.Double": return DbType.Double; case "System.Guid": return DbType.Guid; case "System.Int16": return DbType.Int16; case "System.Int32": return DbType.Int32; case "System.Int64": return DbType.Int64; case "System.String": return DbType.String; default: return DbType.String; } } #endregion Methods DbType #region Methods Id & Sequence /// <summary> /// Get Id generated by DBMS SQL /// </summary> /// <param name="dbms"></param> /// <returns></returns> public static string GetIdSql(ZDBMS dbms) { switch (dbms) { case ZDBMS.MySQL: return ";SELECT LAST_INSERT_ID();"; case ZDBMS.PostgreSQL: return ";LASTVAL();"; case ZDBMS.SQLServer: return ";SELECT SCOPE_IDENTITY();"; default: return ""; } } /// <summary> /// Get Sequence SQL /// </summary> /// <param name="dbms"></param> /// <param name="entity"></param> /// <returns></returns> public static string GetSequenceSql(ZDBMS dbms, string entity) { switch (dbms) { case ZDBMS.Firebird: // Firebird Generators: CREATE GENERATOR Generator return "SELECT GEN_ID(" + SequencePrefix + entity + ", 1) FROM RDB$DATABASE"; case ZDBMS.Oracle: // Oracle Sequences: CREATE SEQUENCE Sequence return "SELECT " + SequencePrefix + entity + ".NEXTVAL FROM DUAL"; case ZDBMS.PostgreSQL: // PostgreSQL Sequences: CREATE SEQUENCE Sequence return "SELECT NEXTVAL('" + SequencePrefix + entity + "')"; default: return ""; } } /// <summary> /// Get Sequence generated by DBMS. /// </summary> /// <param name="entity"></param> /// <param name="connectionName"></param> /// <returns></returns> public static object GetSequence(string entity, string connectionName) { object value = null; DbConnection connection = null; try { DbProviderFactory provider = AdoNetHelper.GetProvider(connectionName); connection = provider.CreateConnection(); connection.ConnectionString = AdoNetHelper.GetConnectionString(connectionName); connection.Open(); DbCommand command = connection.CreateCommand(); command.CommandType = System.Data.CommandType.Text; command.CommandText = GetSequenceSql(GetDBMS(provider), entity); if (command.CommandText != "") { if (connection.State == ConnectionState.Closed) connection.Open(); try { value = LibraryHelper.ObjectToInt32(command.ExecuteScalar()); } finally { connection.Close(); } } } catch (Exception exception) { throw new Exception("GetId", exception); } finally { if (connection != null) { connection.Close(); } } return value; } #endregion Methods Id & Sequence #region Methods Provider /// <summary> /// Get provider. /// </summary> /// <param name="connectionName"></param> /// <returns></returns> public static DbProviderFactory GetProvider(string connectionName) { string providerName = GetProviderName(connectionName); DbProviderFactory provider = DbProviderFactories.GetFactory(providerName); return provider; } /// <summary> /// Get provider name. /// </summary> /// <param name="connectionName"></param> /// <returns></returns> public static string GetProviderName(string connectionName) { return ConfigurationManager.ConnectionStrings[connectionName].ProviderName; } public static DateTime GetDateTime(DbProviderFactory provider) { DateTime now = DateTime.Now; ZDBMS db = GetDBMS(provider); switch (db) { case ZDBMS.Firebird: return now; case ZDBMS.MySQL: return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second); case ZDBMS.Oracle: return now; case ZDBMS.PostgreSQL: return now; case ZDBMS.SQLite: return now; case ZDBMS.SQLServer: return now; default: return now; } } #endregion Methods Provider #region Methods SQL /// <summary> /// Convert "#" parameter token to database specific parameter token /// </summary> /// <param name="command">Database command</param> /// <param name="provider">Database provider</param> public static void SqlParameters(DbCommand command, DbProviderFactory provider) { ZDBMS db = GetDBMS(provider); switch (db) { case ZDBMS.Firebird: command.CommandText = command.CommandText.Replace("#", "@"); command.CommandText = command.CommandText.Replace("@Value IS NULL", "CAST(@Value AS VARCHAR(10)) IS NULL"); foreach (DbParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("#", "@"); } break; case ZDBMS.MySQL: command.CommandText = command.CommandText.Replace("#", "@"); foreach (DbParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("#", "@"); } break; case ZDBMS.Oracle: command.CommandText = command.CommandText.Replace("#", ":"); foreach (DbParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("#", ":"); } if (provider.GetType().FullName == "Oracle.DataAccess.Client.OracleClientFactory") { //((OracleCommand)command).BindByName = true; command.GetType().GetProperty("BindByName").SetValue(command, true, null); } break; case ZDBMS.PostgreSQL: command.CommandText = command.CommandText.Replace("#", ":"); foreach (DbParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("#", ":"); } break; case ZDBMS.SQLite: command.CommandText = command.CommandText.Replace("#", "@"); foreach (DbParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("#", "@"); } break; case ZDBMS.SQLServer: command.CommandText = command.CommandText.Replace("#", "@"); foreach (DbParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("#", "@"); } break; } } /// <summary> /// Get SQL parameter token /// </summary> /// <param name="provider"></param> /// <returns></returns> public static string SqlParameterToken(DbProviderFactory provider) { string parameter; ZDBMS db = GetDBMS(provider); switch (db) { case ZDBMS.Firebird: parameter = "@"; break; case ZDBMS.MySQL: parameter = "@"; break; case ZDBMS.Oracle: parameter = ":"; break; case ZDBMS.PostgreSQL: parameter = ":"; break; case ZDBMS.SQLite: parameter = "@"; break; case ZDBMS.SQLServer: parameter = "@"; break; default: parameter = ""; break; } return parameter; } /// <summary> /// Get SQL limited by N records /// </summary> /// <param name="command"></param> /// <param name="provider"></param> public static void SqlRecords(DbCommand command, DbProviderFactory provider) { SqlRecords(command, provider, RecordsBySearch); } /// <summary> /// Get SQL limited by N records /// </summary> /// <param name="command"></param> /// <param name="provider"></param> /// <param name="records"></param> public static void SqlRecords(DbCommand command, DbProviderFactory provider, int? records) { if (records == null || records <= 0) { records = RecordsBySearch; } if (records != Int32.MaxValue) { ZDBMS db = GetDBMS(provider); switch (db) { case ZDBMS.Firebird: if (!command.CommandText.Contains(" FIRST ")) { command.CommandText = command.CommandText.StringReplaceFirst("SELECT ", "SELECT FIRST " + records.ToString() + " "); } break; case ZDBMS.MySQL: if (!command.CommandText.Contains(" LIMIT ")) { command.CommandText = command.CommandText + " LIMIT " + records.ToString(); } break; case ZDBMS.Oracle: if (!command.CommandText.Contains(" ROWNUM <")) { command.CommandText = "SELECT * FROM (" + command.CommandText + ") WHERE ROWNUM <= " + records.ToString(); } break; case ZDBMS.PostgreSQL: if (!command.CommandText.Contains(" LIMIT ")) { command.CommandText = command.CommandText + " LIMIT " + records.ToString(); } break; case ZDBMS.SQLite: if (!command.CommandText.Contains(" LIMIT ")) { command.CommandText = "SELECT * FROM (" + command.CommandText + ") ORDER BY ROWID ASC LIMIT " + records.ToString(); } break; case ZDBMS.SQLServer: if (!command.CommandText.Contains(" TOP ")) { command.CommandText = command.CommandText.StringReplaceFirst("SELECT ", "SELECT TOP " + records.ToString() + " "); } break; } } } #endregion Methods SQL } }
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Design; using System.Windows.Forms; using System.Reflection; using System.Windows.Forms.Design; using gView.Framework.Symbology; using gView.Framework.system; using gView.Framework.Carto; using gView.Framework.Carto.UI; using gView.Framework.Symbology.UI.Controls; namespace gView.Framework.Symbology.UI { internal class ColorTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService wfes=provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if (wfes != null) { gView.Framework.Symbology.UI.Controls.OfficeColorPicker picker = new gView.Framework.Symbology.UI.Controls.OfficeColorPicker(wfes, (Color)value); picker.AllowNoColor = true; picker.Height = picker.PreferredHeight; wfes.DropDownControl(picker); return picker.Color; } return value; } public override void PaintValue(PaintValueEventArgs e) { using(SolidBrush brush=new SolidBrush((Color)e.Value)) { e.Graphics.FillRectangle(brush,e.Bounds); } } public override bool GetPaintValueSupported(ITypeDescriptorContext context) { return true; } } internal class DashStyleTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService wfes=provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if(wfes!=null) { Form_UITypeEditor_DashStyle dlg=new Form_UITypeEditor_DashStyle(wfes,(DashStyle)value); dlg.TopLevel=false; wfes.DropDownControl(dlg); value=dlg.DashStyle; } return value; } public override bool GetPaintValueSupported(ITypeDescriptorContext context) { return true; } public override void PaintValue(PaintValueEventArgs e) { using(Pen pen=new Pen(Color.Black,1)) { pen.DashStyle=(DashStyle)e.Value; e.Graphics.DrawLine(pen,e.Bounds.Left+2,e.Bounds.Height/2,e.Bounds.Right-4,e.Bounds.Height/2); } } } internal class PenWidthTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService wfes = provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if (wfes != null) { gView.Framework.Symbology.UI.Controls.OfficeLineWidthPicker picker = new gView.Framework.Symbology.UI.Controls.OfficeLineWidthPicker(wfes); picker.Height = picker.PreferredHeight; wfes.DropDownControl(picker); return picker.PenWidth != -1 ? picker.PenWidth : value; } return value; } public override bool GetPaintValueSupported(ITypeDescriptorContext context) { return true; } public override void PaintValue(PaintValueEventArgs e) { using (Pen pen = new Pen(Color.Black, Math.Min(e.Bounds.Height,(float)e.Value))) { e.Graphics.DrawLine(pen, e.Bounds.Left + 1, e.Bounds.Height / 2, e.Bounds.Right - 1, e.Bounds.Height / 2); } } } internal class HatchStyleTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService wfes=provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if(wfes!=null) { Form_UITypeEditor_DashStyle dlg=new Form_UITypeEditor_DashStyle(wfes,(HatchStyle)value); dlg.TopLevel=false; wfes.DropDownControl(dlg); value=dlg.HatchStyle; } return value; } } internal class LineSymbolTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService wfes=provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if(wfes!=null) { ISymbol symbol=(ISymbol)value; if(symbol==null) { symbol=new SimpleLineSymbol(); } Form_UITypeEditor_Color dlg=new Form_UITypeEditor_Color(wfes,symbol); wfes.DropDownControl(dlg.panelSymbol); return dlg.Symbol; } return value; } public override bool GetPaintValueSupported(ITypeDescriptorContext context) { return true; } public override void PaintValue(PaintValueEventArgs e) { if(!(e.Value is ISymbol)) return; SymbolPreview.Draw(e.Graphics,e.Bounds,(ISymbol)e.Value); } } internal class CharacterTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.DropDown; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { Font font=null; if(context.Instance is TrueTypeMarkerSymbol) { font=((TrueTypeMarkerSymbol)context.Instance).Font; } if (context.Instance is CustomClass && ((CustomClass)context.Instance).ObjectInstance is TrueTypeMarkerSymbol) { font = ((TrueTypeMarkerSymbol)((CustomClass)context.Instance).ObjectInstance).Font; } if(font==null) return value; IWindowsFormsEditorService wfes=provider.GetService( typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService; if(wfes!=null) { Form_UITypeEditor_Character dlg=new Form_UITypeEditor_Character(wfes,font,(byte)value); wfes.DropDownControl(dlg.panelChars); return dlg.Charakter; } return value; } } internal class FileTypeEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { string filename = String.Empty; if (context.Instance is RasterMarkerSymbol) { filename = ((RasterMarkerSymbol)context.Instance).Filename; } if (context.Instance is CustomClass && ((CustomClass)context.Instance).ObjectInstance is RasterMarkerSymbol) { filename = ((RasterMarkerSymbol)((CustomClass)context.Instance).ObjectInstance).Filename; } OpenFileDialog dlg = new OpenFileDialog(); dlg.FileName = filename; if (dlg.ShowDialog() == DialogResult.OK) { return dlg.FileName; } return filename; } } internal class ColorGradientEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { FormColorGradient dlg = new FormColorGradient(); ColorGradient gradient = new ColorGradient(Color.Red, Color.Blue); if (context.Instance is GradientFillSymbol) { gradient = dlg.ColorGradient = ((GradientFillSymbol)context.Instance).ColorGradient; } if (context.Instance is CustomClass && ((CustomClass)context.Instance).ObjectInstance is GradientFillSymbol) { gradient = dlg.ColorGradient = ((GradientFillSymbol)((CustomClass)context.Instance).ObjectInstance).ColorGradient; } if (dlg.ShowDialog() == DialogResult.OK) { return dlg.ColorGradient; } return gradient; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; namespace FluentRest { /// <summary> /// Extension method for <see cref="HttpRequestMessage"/> /// </summary> public static class HttpMessageExtensions { /// <summary> /// Gets the <see cref="UrlBuilder"/> from the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <returns> /// The <see cref="UrlBuilder"/> to modify the request message URI. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static UrlBuilder GetUrlBuilder(this HttpRequestMessage requestMessage) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); var propertyValue = requestMessage.Properties.GetOrAdd(FluentProperties.RequestUrlBuilder, k => requestMessage.RequestUri == null ? new UrlBuilder() : new UrlBuilder(requestMessage.RequestUri) ); return propertyValue as UrlBuilder; } /// <summary> /// Sets the <see cref="UrlBuilder" /> on the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <param name="urlBuilder">The URL bulder to set on the properties dictionary.</param> /// <exception cref="ArgumentNullException"><paramref name="requestMessage" /> is <see langword="null" /></exception> public static void SetUrlBuilder(this HttpRequestMessage requestMessage, UrlBuilder urlBuilder) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties[FluentProperties.RequestUrlBuilder] = urlBuilder; } /// <summary> /// Gets the content data from the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <returns> /// The content data to send for the request message. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static object GetContentData(this HttpRequestMessage requestMessage) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties.TryGetValue(FluentProperties.RequestContentData, out var propertyValue); return propertyValue; } /// <summary> /// Sets the content data on the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <param name="contentData">The content data to send for the request message..</param> /// <exception cref="ArgumentNullException"><paramref name="requestMessage" /> is <see langword="null" /></exception> public static void SetContentData(this HttpRequestMessage requestMessage, object contentData) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties[FluentProperties.RequestContentData] = contentData; } /// <summary> /// Gets the form data property from the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <returns> /// The dictionary of for data to send in the request message. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static Dictionary<string, ICollection<string>> GetFormData(this HttpRequestMessage requestMessage) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); var propertyValue = requestMessage.Properties.GetOrAdd(FluentProperties.RequestFormData, k => new Dictionary<string, ICollection<string>>()); return propertyValue as Dictionary<string, ICollection<string>>; } /// <summary> /// Gets the completion option property from the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <returns> /// The <see cref="HttpCompletionOption"/> to use when sending the request message. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static HttpCompletionOption GetCompletionOption(this HttpRequestMessage requestMessage) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties.TryGetValue(FluentProperties.HttpCompletionOption, out var propertyValue); return (HttpCompletionOption)(propertyValue ?? HttpCompletionOption.ResponseContentRead); } /// <summary> /// Sets the completion option property on the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to use when sending the request message.</param> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static void SetCompletionOption(this HttpRequestMessage requestMessage, HttpCompletionOption completionOption) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties[FluentProperties.HttpCompletionOption] = completionOption; } /// <summary> /// Gets the cancellation token property from the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <returns> /// The <see cref="CancellationToken"/> to use when sending the request message. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static CancellationToken GetCancellationToken(this HttpRequestMessage requestMessage) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties.TryGetValue(FluentProperties.CancellationToken, out var propertyValue); return (CancellationToken)(propertyValue ?? CancellationToken.None); } /// <summary> /// Sets the cancellation token property on the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use when sending the request message.</param> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static void SetCancellationToken(this HttpRequestMessage requestMessage, CancellationToken cancellationToken) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties[FluentProperties.CancellationToken] = cancellationToken; } /// <summary> /// Gets the content serializer property from the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <returns> /// The <see cref="IContentSerializer"/> to use when serializing content to send in the request message. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static IContentSerializer GetContentSerializer(this HttpRequestMessage requestMessage) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); var propertyValue = requestMessage.Properties.GetOrAdd(FluentProperties.ContentSerializer, k => ContentSerializer.Current); return propertyValue as IContentSerializer; } /// <summary> /// Sets the content serializer property on the specified <paramref name="requestMessage" /> properties dictionary. /// </summary> /// <param name="requestMessage">The request message containing the property.</param> /// <param name="contentSerializer">The <see cref="IContentSerializer"/> to use when serializing content to send in the request message.</param> /// <exception cref="ArgumentNullException"><paramref name="requestMessage"/> is <see langword="null"/></exception> public static void SetContentSerializer(this HttpRequestMessage requestMessage, IContentSerializer contentSerializer) { if (requestMessage == null) throw new ArgumentNullException(nameof(requestMessage)); requestMessage.Properties[FluentProperties.ContentSerializer] = contentSerializer ?? ContentSerializer.Current; } /// <summary> /// Synchronizes the specified request message with the fluent properties. /// </summary> /// <param name="requestMessage">The request message.</param> public static void Synchronize(this HttpRequestMessage requestMessage) { var urlBuilder = requestMessage.GetUrlBuilder(); requestMessage.RequestUri = urlBuilder.ToUri(); } /// <summary> /// Deserialize the HTTP response message asynchronously. /// </summary> /// <typeparam name="TData">The type of the data.</typeparam> /// <param name="responseMessage">The response message to deserialize.</param> /// <param name="ensureSuccess">Throw an exception if the HTTP response was unsuccessful.</param> /// <returns> /// The data object deserialized from the HTTP response message. /// </returns> /// <exception cref="HttpRequestException">Response status code does not indicate success.</exception> /// <exception cref="ArgumentNullException"><paramref name="responseMessage"/> is <see langword="null"/></exception> public static async Task<TData> DeserializeAsync<TData>(this HttpResponseMessage responseMessage, bool ensureSuccess = true) { if (responseMessage == null) throw new ArgumentNullException(nameof(responseMessage)); if (ensureSuccess) await responseMessage.EnsureSuccessStatusCode(true); var serializer = responseMessage.RequestMessage.GetContentSerializer(); var data = await serializer .DeserializeAsync<TData>(responseMessage.Content) .ConfigureAwait(false); return data; } /// <summary> /// Throws an exception if the IsSuccessStatusCode property for the HTTP response is false. /// </summary> /// <param name="responseMessage">The response message.</param> /// <param name="includeContent">if set to <c>true</c> the response content is included in the exception.</param> /// <returns></returns> /// <exception cref="HttpRequestException">The HTTP response is unsuccessful.</exception> public static async Task EnsureSuccessStatusCode(this HttpResponseMessage responseMessage, bool includeContent) { if (responseMessage.IsSuccessStatusCode) return; // will throw if respose is a problem json await CheckResponseForProblem(responseMessage).ConfigureAwait(false); var message = $"Response status code does not indicate success: {responseMessage.StatusCode} ({responseMessage.ReasonPhrase});"; if (!includeContent) throw new HttpRequestException(message); var contentString = await responseMessage.Content.ReadAsStringAsync(); if (string.IsNullOrEmpty(contentString)) throw new HttpRequestException(message); // add response content body to message for easier debugging message += Environment.NewLine + contentString; var exception = new HttpRequestException(message); exception.Data.Add("Response", contentString); throw exception; } private static async Task CheckResponseForProblem(HttpResponseMessage responseMessage) { string mediaType = responseMessage.Content?.Headers?.ContentType?.MediaType; if (!string.Equals(mediaType, ProblemDetails.ContentType, StringComparison.OrdinalIgnoreCase)) return; var serializer = responseMessage.RequestMessage.GetContentSerializer(); var problem = await serializer .DeserializeAsync<ProblemDetails>(responseMessage.Content) .ConfigureAwait(false); throw new ProblemException(problem); } } }
//--------------------------------------------------------------------- // <copyright file="SqlSelectStatement.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Data.Common.CommandTrees; namespace System.Data.SqlClient.SqlGen { /// <summary> /// A SqlSelectStatement represents a canonical SQL SELECT statement. /// It has fields for the 5 main clauses /// <list type="number"> /// <item>SELECT</item> /// <item>FROM</item> /// <item>WHERE</item> /// <item>GROUP BY</item> /// <item>ORDER BY</item> /// </list> /// We do not have HAVING, since the CQT does not have such a node. /// Each of the fields is a SqlBuilder, so we can keep appending SQL strings /// or other fragments to build up the clause. /// /// The FromExtents contains the list of inputs in use for the select statement. /// There is usually just one element in this - Select statements for joins may /// temporarily have more than one. /// /// If the select statement is created by a Join node, we maintain a list of /// all the extents that have been flattened in the join in AllJoinExtents /// <example> /// in J(j1= J(a,b), c) /// FromExtents has 2 nodes JoinSymbol(name=j1, ...) and Symbol(name=c) /// AllJoinExtents has 3 nodes Symbol(name=a), Symbol(name=b), Symbol(name=c) /// </example> /// /// If any expression in the non-FROM clause refers to an extent in a higher scope, /// we add that extent to the OuterExtents list. This list denotes the list /// of extent aliases that may collide with the aliases used in this select statement. /// It is set by <see cref="SqlGenerator.Visit(DbVariableReferenceExpression)"/>. /// An extent is an outer extent if it is not one of the FromExtents. /// /// /// </summary> internal sealed class SqlSelectStatement : ISqlFragment { /// <summary> /// Whether the columns ouput by this sql statement were renamed from what given in the command tree. /// </summary> internal bool OutputColumnsRenamed { get; set; } /// <summary> /// A dictionary of output columns /// </summary> internal Dictionary<string, Symbol> OutputColumns { get; set; } internal List<Symbol> AllJoinExtents { get; // We have a setter as well, even though this is a list, // since we use this field only in special cases. set; } private List<Symbol> fromExtents; internal List<Symbol> FromExtents { get { if (null == fromExtents) { fromExtents = new List<Symbol>(); } return fromExtents; } } private Dictionary<Symbol, bool> outerExtents; internal Dictionary<Symbol, bool> OuterExtents { get { if (null == outerExtents) { outerExtents = new Dictionary<Symbol, bool>(); } return outerExtents; } } private readonly SqlSelectClauseBuilder select; internal SqlSelectClauseBuilder Select { get { return select; } } private readonly SqlBuilder from = new SqlBuilder(); internal SqlBuilder From { get { return from; } } private SqlBuilder where; internal SqlBuilder Where { get { if (null == where) { where = new SqlBuilder(); } return where; } } private SqlBuilder groupBy; internal SqlBuilder GroupBy { get { if (null == groupBy) { groupBy = new SqlBuilder(); } return groupBy; } } private SqlBuilder orderBy; public SqlBuilder OrderBy { get { if (null == orderBy) { orderBy = new SqlBuilder(); } return orderBy; } } //indicates whether it is the top most select statement, // if not Order By should be omitted unless there is a corresponding TOP internal bool IsTopMost { get; set; } #region Internal Constructor internal SqlSelectStatement() { this.select = new SqlSelectClauseBuilder(delegate() { return this.IsTopMost; }); } #endregion #region ISqlFragment Members /// <summary> /// Write out a SQL select statement as a string. /// We have to /// <list type="number"> /// <item>Check whether the aliases extents we use in this statement have /// to be renamed. /// We first create a list of all the aliases used by the outer extents. /// For each of the FromExtents( or AllJoinExtents if it is non-null), /// rename it if it collides with the previous list. /// </item> /// <item>Write each of the clauses (if it exists) as a string</item> /// </list> /// </summary> /// <param name="writer"></param> /// <param name="sqlGenerator"></param> public void WriteSql(SqlWriter writer, SqlGenerator sqlGenerator) { #region Check if FROM aliases need to be renamed // Create a list of the aliases used by the outer extents // JoinSymbols have to be treated specially. List<string> outerExtentAliases = null; if ((null != outerExtents) && (0 < outerExtents.Count)) { foreach (Symbol outerExtent in outerExtents.Keys) { JoinSymbol joinSymbol = outerExtent as JoinSymbol; if (joinSymbol != null) { foreach (Symbol symbol in joinSymbol.FlattenedExtentList) { if (null == outerExtentAliases) { outerExtentAliases = new List<string>(); } outerExtentAliases.Add(symbol.NewName); } } else { if (null == outerExtentAliases) { outerExtentAliases = new List<string>(); } outerExtentAliases.Add(outerExtent.NewName); } } } // An then rename each of the FromExtents we have // If AllJoinExtents is non-null - it has precedence. // The new name is derived from the old name - we append an increasing int. List<Symbol> extentList = this.AllJoinExtents ?? this.fromExtents; if (null != extentList) { foreach (Symbol fromAlias in extentList) { if ((null != outerExtentAliases) && outerExtentAliases.Contains(fromAlias.Name)) { int i = sqlGenerator.AllExtentNames[fromAlias.Name]; string newName; do { ++i; newName = fromAlias.Name + i.ToString(System.Globalization.CultureInfo.InvariantCulture); } while (sqlGenerator.AllExtentNames.ContainsKey(newName)); sqlGenerator.AllExtentNames[fromAlias.Name] = i; fromAlias.NewName = newName; // Add extent to list of known names (although i is always incrementing, "prefix11" can // eventually collide with "prefix1" when it is extended) sqlGenerator.AllExtentNames[newName] = 0; } // Add the current alias to the list, so that the extents // that follow do not collide with me. if (null == outerExtentAliases) { outerExtentAliases = new List<string>(); } outerExtentAliases.Add(fromAlias.NewName); } } #endregion // Increase the indent, so that the Sql statement is nested by one tab. writer.Indent += 1; // ++ can be confusing in this context this.select.WriteSql(writer, sqlGenerator); writer.WriteLine(); writer.Write("FROM "); this.From.WriteSql(writer, sqlGenerator); if ((null != this.where) && !this.Where.IsEmpty) { writer.WriteLine(); writer.Write("WHERE "); this.Where.WriteSql(writer, sqlGenerator); } if ((null != this.groupBy) && !this.GroupBy.IsEmpty) { writer.WriteLine(); writer.Write("GROUP BY "); this.GroupBy.WriteSql(writer, sqlGenerator); } if ((null != this.orderBy) && !this.OrderBy.IsEmpty && (this.IsTopMost || this.Select.Top != null)) { writer.WriteLine(); writer.Write("ORDER BY "); this.OrderBy.WriteSql(writer, sqlGenerator); } --writer.Indent; } #endregion } }
using System; using SquishIt.Framework.CSS; using SquishIt.Framework.Files; using SquishIt.Framework.Invalidation; using SquishIt.Framework.JavaScript; using SquishIt.Framework.Minifiers; using SquishIt.Framework.Minifiers.JavaScript; using SquishIt.Framework.Renderers; using SquishIt.Framework.Utilities; using MsMinifier = SquishIt.Framework.Minifiers.CSS.MsMinifier; using NullMinifier = SquishIt.Framework.Minifiers.CSS.NullMinifier; using YuiMinifier = SquishIt.Framework.Minifiers.CSS.YuiMinifier; namespace SquishIt.Framework { public class Configuration { private static Configuration instance; private ICacheInvalidationStrategy _defaultCacheInvalidationStrategy = new DefaultCacheInvalidationStrategy(); private IMinifier<CSSBundle> _defaultCssMinifier = new MsMinifier(); private Func<bool> _defaultDebugPredicate; private string _defaultHashKeyName = "r"; private IHasher _defaultHasher = new Hasher(new RetryableFileOpener()); private IMinifier<JavaScriptBundle> _defaultJsMinifier = new Minifiers.JavaScript.MsMinifier(); private string _defaultOutputBaseHref; private IPathTranslator _defaultPathTranslator = new PathTranslator(); private IRenderer _defaultReleaseRenderer; private ITempPathProvider _defaultTempPathProvider = new TempPathProvider(); public Configuration() { JavascriptMimeType = "application/javascript"; CssMimeType = "text/css"; } public static Configuration Instance { get { return (instance = instance ?? new Configuration()); } internal set { instance = value; } } /// <summary> /// Mime-type used to serve Javascript content. Defaults to "application/javascript". /// To enable gzip compression in IIS change this to "application/x-javascript". /// </summary> public string JavascriptMimeType { get; set; } /// <summary> /// Mime-type used to serve CSS content. Defaults to "text/css". /// </summary> public string CssMimeType { get; set; } public Configuration UseMinifierForCss<TMinifier>() where TMinifier : IMinifier<CSSBundle> { return UseMinifierForCss(typeof (TMinifier)); } public Configuration UseMinifierForCss(Type minifierType) { if (!typeof (IMinifier<CSSBundle>).IsAssignableFrom(minifierType)) throw new InvalidCastException( String.Format("Type '{0}' must implement '{1}' to be used for Css minification.", minifierType, typeof (IMinifier<CSSBundle>))); return UseMinifierForCss((IMinifier<CSSBundle>) Activator.CreateInstance(minifierType, true)); } public Configuration UseMinifierForCss(IMinifier<CSSBundle> minifier) { _defaultCssMinifier = minifier; return this; } public Configuration UseMinifierForJs<TMinifier>() where TMinifier : IMinifier<JavaScriptBundle> { return UseMinifierForJs(typeof (TMinifier)); } public Configuration UseMinifierForJs(Type minifierType) { if (!typeof (IMinifier<JavaScriptBundle>).IsAssignableFrom(minifierType)) throw new InvalidCastException( String.Format("Type '{0}' must implement '{1}' to be used for Javascript minification.", minifierType, typeof (IMinifier<JavaScriptBundle>))); return UseMinifierForJs((IMinifier<JavaScriptBundle>) Activator.CreateInstance(minifierType, true)); } public Configuration UseMinifierForJs(IMinifier<JavaScriptBundle> minifier) { _defaultJsMinifier = minifier; return this; } /// <summary> /// Use Yahoo YUI Compressor for CSS minification by default. /// </summary> public Configuration UseYuiForCssMinification() { return UseMinifierForCss<YuiMinifier>(); } /// <summary> /// Use Microsoft Ajax Minifier for CSS minification by default. /// </summary> public Configuration UseMsAjaxForCssMinification() { return UseMinifierForCss<MsMinifier>(); } /// <summary> /// By default, perform no minification of CSS. /// </summary> public Configuration UseNoCssMinification() { return UseMinifierForCss<NullMinifier>(); } /// <summary> /// Use Microsoft Ajax Minifier for Javascript minification by default. /// </summary> public Configuration UseMsAjaxForJsMinification() { return UseMinifierForJs<Minifiers.JavaScript.MsMinifier>(); } /// <summary> /// Use Yahoo YUI Compressor for Javascript minification by default. /// </summary> public Configuration UseYuiForJsMinification() { return UseMinifierForJs<Minifiers.JavaScript.YuiMinifier>(); } /// <summary> /// Use Google Closure for Javascript minification by default. /// </summary> public Configuration UseClosureForMinification() { return UseMinifierForJs<ClosureMinifier>(); } /// <summary> /// By default, perform no minification of Javascript. /// </summary> public Configuration UseNoJsMinification() { return UseMinifierForJs<Minifiers.JavaScript.NullMinifier>(); } /// <summary> /// Use Douglas Crockford's JsMin for Javascript minification by default. /// </summary> public Configuration UseJsMinForJsMinification() { return UseMinifierForJs<JsMinMinifier>(); } internal IMinifier<CSSBundle> DefaultCssMinifier() { return _defaultCssMinifier; } internal IMinifier<JavaScriptBundle> DefaultJsMinifier() { return _defaultJsMinifier; } public Configuration UseReleaseRenderer(IRenderer releaseRenderer) { _defaultReleaseRenderer = releaseRenderer; return this; } internal IRenderer DefaultReleaseRenderer() { return _defaultReleaseRenderer; } public Configuration UseDefaultOutputBaseHref(string url) { _defaultOutputBaseHref = url; return this; } internal string DefaultOutputBaseHref() { return _defaultOutputBaseHref; } public Configuration UseConditionToForceDebugging(Func<bool> condition) { _defaultDebugPredicate = condition; return this; } internal Func<bool> DefaultDebugPredicate() { return _defaultDebugPredicate; } public Configuration UseHasher(IHasher hasher) { _defaultHasher = hasher; return this; } public Configuration UseSHA1Hasher() { return UseHasher(new SHA1Hasher(new RetryableFileOpener())); } internal IHasher DefaultHasher() { return _defaultHasher; } public Configuration UseHashAsVirtualDirectoryInvalidationStrategy() { return UseCacheInvalidationStrategy(new HashAsVirtualDirectoryCacheInvalidationStrategy()); } public Configuration UseCacheInvalidationStrategy(ICacheInvalidationStrategy strategy) { _defaultCacheInvalidationStrategy = strategy; return this; } public ICacheInvalidationStrategy DefaultCacheInvalidationStrategy() { return _defaultCacheInvalidationStrategy; } public Configuration UseHashKeyName(string hashKeyName) { _defaultHashKeyName = hashKeyName; return this; } public string DefaultHashKeyName() { return _defaultHashKeyName; } public Configuration UsePathTranslator(IPathTranslator translator) { _defaultPathTranslator = translator; return this; } public IPathTranslator DefaultPathTranslator() { return _defaultPathTranslator; } public Configuration UseTempPathProvider(ITempPathProvider provider) { _defaultTempPathProvider = provider; return this; } public ITempPathProvider DefaultTempPathProvider() { return _defaultTempPathProvider; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #elif DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; using System.IO; using System.Collections; #if !(NETFX_CORE || DNXCORE50) #if !UNITY3D using System.Web.UI; #endif #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JObjectTests : TestFixtureBase { #if !(NET35 || NET20 || PORTABLE40) [Test] public void EmbedJValueStringInNewJObject() { string s = null; var v = new JValue(s); dynamic o = JObject.FromObject(new { title = v }); string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); Assert.AreEqual(null, v.Value); Assert.IsNull((string)o.title); } #endif [Test] public void ReadWithSupportMultipleContent() { string json = @"{ 'name': 'Admin' }{ 'name': 'Publisher' }"; IList<JObject> roles = new List<JObject>(); JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.SupportMultipleContent = true; while (true) { JObject role = (JObject)JToken.ReadFrom(reader); roles.Add(role); if (!reader.Read()) { break; } } Assert.AreEqual(2, roles.Count); Assert.AreEqual("Admin", (string)roles[0]["name"]); Assert.AreEqual("Publisher", (string)roles[1]["name"]); } [Test] public void JObjectWithComments() { string json = @"{ /*comment2*/ ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/ ""ExpiryDate"": ""\/Date(1230422400000)\/"", ""Price"": 3.99, ""Sizes"": /*comment6*/ [ /*comment7*/ ""Small"", /*comment8*/ ""Medium"" /*comment9*/, /*comment10*/ ""Large"" /*comment11*/ ] /*comment12*/ } /*comment13*/"; JToken o = JToken.Parse(json); Assert.AreEqual("Apple", (string)o["Name"]); } [Test] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.AreEqual(@"{ ""novalue"": null }", o.ToString()); } [Test] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.AreEqual(0, d.Keys.Count); o["value"] = true; Assert.AreEqual(1, d.Keys.Count); } [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] public void DuplicatePropertyNameShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] public void GenericCollectionCopyToNullArrayShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }, #if UNITY3D @"Argument cannot be null. Parameter name: array", #endif @"Value cannot be null. Parameter name: array"); } [Test] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }, @"arrayIndex is less than 0. Parameter name: arrayIndex"); } [Test] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }, @"arrayIndex is equal to or greater than the length of array."); } [Test] public void GenericCollectionCopyToInsufficientArrayCapacity() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] public void Parse_ShouldThrowOnUnexpectedToken() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"[""prop""]"; JObject.Parse(json); }, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] public void Blog() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 4."); } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); StringAssert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Assert.AreEqual("Apple", name); Assert.AreEqual("Small", smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>"); StringAssert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); StringAssert.AreEqual(@"{ ""FirstName"": ""Maurice"", ""LastName"": ""Moss"", ""BirthDate"": ""1977-12-30T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Support"" }", moss.ToString()); JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; StringAssert.AreEqual(@"{ ""FirstName"": ""Jen"", ""LastName"": ""Barber"", ""BirthDate"": ""1978-03-15T00:00:00"", ""Department"": ""IT"", ""JobTitle"": ""Manager"" }", jen.ToString()); } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !(NET20 || PORTABLE || PORTABLE40 || UNITY3D) [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void IListAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }, "Argument is not a JToken."); } [Test] public void IListAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void IListSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListSetItemInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void GenericListJTokenAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void GenericListJTokenSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40 || UNITY3D) [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] public void IBindingListApplySort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveSort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.RemoveSort(); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] public void IBindingListFind() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.Find(null, null); }, "Specified method is not supported."); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] public void IBindingListAddNew() { ExceptionAssert.Throws<JsonException>(() => { IBindingList l = new JObject(); l.AddNew(); }, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'."); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty)newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if !(NET20 || NET35 || PORTABLE40) [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o._collectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] public void SetValueWithInvalidPropertyName() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o[0] = new JValue(3); }, "Set JObject values with invalid key value: 0. Object property name expected."); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40) [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } #endif [Test] public void InvalidValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }, "Can not convert Object to String."); } [Test] public void InvalidPropertyValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }, "Can not convert Object to String."); } [Test] public void ParseIncomplete() { ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6."); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); StringAssert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] public void LoadFromNestedObjectIncomplete() { ExceptionAssert.Throws<JsonReaderException>(() => { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 14."); } #if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40 || UNITY3D) [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(object), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(object), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(object), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif [Test] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.AreEqual(0, o.Count); } [Test] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.AreEqual(v.Value, TimeSpan.FromDays(1)); Assert.AreEqual("1.00:00:00", v.ToString()); } [Test] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz")); Assert.AreEqual("http://www.stuff.co.nz/", v.ToString()); } [Test] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 1."); } [Test] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.IsFalse(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.IsFalse(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.IsFalse(o1.DeepEquals(o5)); Assert.IsFalse(o1.DeepEquals(null)); } [Test] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.AreEqual(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.AreEqual(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(1, l2.Count); } [Test] public void EmptyObjectDeepEquals() { Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.IsTrue(JToken.DeepEquals(a, b)); Assert.IsTrue(JToken.DeepEquals(b, a)); } [Test] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.AreEqual("Upper", exactMatch); Assert.AreEqual("Lower", ignoreCase); } [Test] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue("NAME")); Assert.AreEqual(null, a.GetValue("TITLE")); Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null)); JToken v; Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.AreEqual(null, v); Assert.IsFalse(a.TryGetValue("NAME", out v)); Assert.IsFalse(a.TryGetValue("TITLE", out v)); Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.AreEqual("Name!", (string)v); Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.AreEqual("name!", (string)v); Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else { token.WriteTo(writer); } } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Test] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } [Test] public void Parse_NoComments() { string json = "{'prop':[1,2/*comment*/,3]}"; JObject o = JObject.Parse(json, new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }); Assert.AreEqual(3, o["prop"].Count()); Assert.AreEqual(1, (int)o["prop"][0]); Assert.AreEqual(2, (int)o["prop"][1]); Assert.AreEqual(3, (int)o["prop"][2]); } } }
// <copyright file="Histogram.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2015 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using MathNet.Numerics.Properties; namespace MathNet.Numerics.Statistics { /// <summary> /// A <see cref="Histogram"/> consists of a series of <see cref="Bucket"/>s, /// each representing a region limited by a lower bound (exclusive) and an upper bound (inclusive). /// </summary> /// <remarks> /// This type declares a DataContract for out of the box ephemeral serialization /// with engines like DataContractSerializer, Protocol Buffers and FsPickler, /// but does not guarantee any compatibility between versions. /// It is not recommended to rely on this mechanism for durable persistance. /// </remarks> [Serializable] [DataContract(Namespace = "urn:MathNet/Numerics")] public class Bucket : #if PORTABLE IComparable<Bucket> #else IComparable<Bucket>, ICloneable #endif { /// <summary> /// This <c>IComparer</c> performs comparisons between a point and a bucket. /// </summary> private sealed class PointComparer : IComparer<Bucket> { /// <summary> /// Compares a point and a bucket. The point will be encapsulated in a bucket with width 0. /// </summary> /// <param name="bkt1">The first bucket to compare.</param> /// <param name="bkt2">The second bucket to compare.</param> /// <returns>-1 when the point is less than this bucket, 0 when it is in this bucket and 1 otherwise.</returns> public int Compare(Bucket bkt1, Bucket bkt2) { return bkt2.IsSinglePoint ? -bkt1.Contains(bkt2.UpperBound) : -bkt2.Contains(bkt1.UpperBound); } } private static readonly PointComparer Comparer = new PointComparer(); /// <summary> /// Lower Bound of the Bucket. /// </summary> [DataMember(Order = 1)] public double LowerBound { get; set; } /// <summary> /// Upper Bound of the Bucket. /// </summary> [DataMember(Order = 2)] public double UpperBound { get; set; } /// <summary> /// The number of datapoints in the bucket. /// </summary> /// <remarks> /// Value may be NaN if this was constructed as a <see cref="IComparer{Bucket}"/> argument. /// </remarks> [DataMember(Order = 3)] public double Count { get; set; } /// <summary> /// Initializes a new instance of the Bucket class. /// </summary> public Bucket(double lowerBound, double upperBound, double count = 0.0) { if (lowerBound > upperBound) { throw new ArgumentException(Resources.ArgumentUpperBoundMustBeLargerThanOrEqualToLowerBound); } if (count < 0.0) { throw new ArgumentOutOfRangeException("count", Resources.ArgumentMustBePositive); } LowerBound = lowerBound; UpperBound = upperBound; Count = count; } /// <summary> /// Constructs a Bucket that can be used as an argument for a <see cref="IComparer{Bucket}"/> /// like <see cref="DefaultPointComparer"/> when performing a Binary search. /// </summary> /// <param name="targetValue">Value to look for</param> public Bucket(double targetValue) { LowerBound = targetValue; UpperBound = targetValue; Count = double.NaN; } /// <summary> /// Creates a copy of the Bucket with the lowerbound, upperbound and counts exactly equal. /// </summary> /// <returns>A cloned Bucket object.</returns> public object Clone() { return new Bucket(LowerBound, UpperBound, Count); } /// <summary> /// Width of the Bucket. /// </summary> public double Width { get { return UpperBound - LowerBound; } } /// <summary> /// True if this is a single point argument for <see cref="IComparer{Bucket}"/> /// when performing a Binary search. /// </summary> private bool IsSinglePoint { get { return double.IsNaN(Count); } } /// <summary> /// Default comparer. /// </summary> public static IComparer<Bucket> DefaultPointComparer { get { return Comparer; } } /// <summary> /// This method check whether a point is contained within this bucket. /// </summary> /// <param name="x">The point to check.</param> /// <returns> /// 0 if the point falls within the bucket boundaries; /// -1 if the point is smaller than the bucket, /// +1 if the point is larger than the bucket.</returns> public int Contains(double x) { if (LowerBound < x) { if (UpperBound >= x) { return 0; } return 1; } return -1; } /// <summary> /// Comparison of two disjoint buckets. The buckets cannot be overlapping. /// </summary> /// <returns> /// 0 if <c>UpperBound</c> and <c>LowerBound</c> are bit-for-bit equal /// 1 if This bucket is lower that the compared bucket /// -1 otherwise /// </returns> public int CompareTo(Bucket bucket) { if (UpperBound > bucket.LowerBound && LowerBound < bucket.LowerBound) { throw new ArgumentException(Resources.PartialOrderException); } if (UpperBound.Equals(bucket.UpperBound) && LowerBound.Equals(bucket.LowerBound)) { return 0; } if (bucket.UpperBound <= LowerBound) { return 1; } return -1; } /// <summary> /// Checks whether two Buckets are equal. /// </summary> /// <remarks> /// <c>UpperBound</c> and <c>LowerBound</c> are compared bit-for-bit, but This method tolerates a /// difference in <c>Count</c> given by <seealso cref="Precision.AlmostEqual(double,double)"/>. /// </remarks> public override bool Equals(object obj) { if (!(obj is Bucket)) { return false; } var bucket = (Bucket) obj; return LowerBound.Equals(bucket.LowerBound) && UpperBound.Equals(bucket.UpperBound) && Count.AlmostEqual(bucket.Count); } /// <summary> /// Provides a hash code for this bucket. /// </summary> public override int GetHashCode() { return LowerBound.GetHashCode() ^ UpperBound.GetHashCode() ^ Count.GetHashCode(); } /// <summary> /// Formats a human-readable string for this bucket. /// </summary> public override string ToString() { return "(" + LowerBound + ";" + UpperBound + "] = " + Count; } } /// <summary> /// A class which computes histograms of data. /// </summary> [Serializable] [DataContract(Namespace = "urn:MathNet/Numerics")] public class Histogram { /// <summary> /// Contains all the <c>Bucket</c>s of the <c>Histogram</c>. /// </summary> [DataMember(Order = 1)] private readonly List<Bucket> _buckets; /// <summary> /// Indicates whether the elements of <c>buckets</c> are currently sorted. /// </summary> [DataMember(Order = 2)] private bool _areBucketsSorted; /// <summary> /// Initializes a new instance of the Histogram class. /// </summary> public Histogram() { _buckets = new List<Bucket>(); _areBucketsSorted = true; } /// <summary> /// Constructs a Histogram with a specific number of equally sized buckets. The upper and lower bound of the histogram /// will be set to the smallest and largest datapoint. /// </summary> /// <param name="data">The datasequence to build a histogram on.</param> /// <param name="nbuckets">The number of buckets to use.</param> public Histogram(IEnumerable<double> data, int nbuckets) : this() { if (nbuckets < 1) { throw new ArgumentOutOfRangeException("data", "The number of bins in a histogram should be at least 1."); } double lower = data.Minimum(); double upper = data.Maximum(); double width = (upper - lower)/nbuckets; if (double.IsNaN(width)) { throw new ArgumentException("Data must contain at least one entry.", "data"); } // Add buckets for each bin; the smallest bucket's lowerbound must be slightly smaller // than the minimal element. double fNextLowerBound = lower + width; AddBucket(new Bucket(lower.Decrement(), fNextLowerBound)); for (int n = 1; n < nbuckets; n++) { AddBucket(new Bucket( fNextLowerBound, fNextLowerBound = (lower + (n + 1) * width))); } AddData(data); } /// <summary> /// Constructs a Histogram with a specific number of equally sized buckets. /// </summary> /// <param name="data">The datasequence to build a histogram on.</param> /// <param name="nbuckets">The number of buckets to use.</param> /// <param name="lower">The histogram lower bound.</param> /// <param name="upper">The histogram upper bound.</param> public Histogram(IEnumerable<double> data, int nbuckets, double lower, double upper) : this() { if (lower > upper) { throw new ArgumentOutOfRangeException("upper", "The histogram lower bound must be smaller than the upper bound."); } if (nbuckets < 1) { throw new ArgumentOutOfRangeException("nbuckets", "The number of bins in a histogram should be at least 1."); } double width = (upper - lower) / nbuckets; // Add buckets for each bin. for (int n = 0; n < nbuckets; n++) { AddBucket(new Bucket(lower + n * width, lower + (n + 1) * width)); } AddData(data); } /// <summary> /// Add one data point to the histogram. If the datapoint falls outside the range of the histogram, /// the lowerbound or upperbound will automatically adapt. /// </summary> /// <param name="d">The datapoint which we want to add.</param> public void AddData(double d) { // Sort if needed. LazySort(); if (d <= LowerBound) { // Make the lower bound just slightly smaller than the datapoint so it is contained in this bucket. _buckets[0].LowerBound = d.Decrement(); _buckets[0].Count++; } else if (d > UpperBound) { _buckets[BucketCount - 1].UpperBound = d; _buckets[BucketCount - 1].Count++; } else { _buckets[GetBucketIndexOf(d)].Count++; } } /// <summary> /// Add a sequence of data point to the histogram. If the datapoint falls outside the range of the histogram, /// the lowerbound or upperbound will automatically adapt. /// </summary> /// <param name="data">The sequence of datapoints which we want to add.</param> public void AddData(IEnumerable<double> data) { foreach (double d in data) { AddData(d); } } /// <summary> /// Adds a <c>Bucket</c> to the <c>Histogram</c>. /// </summary> public void AddBucket(Bucket bucket) { _buckets.Add(bucket); _areBucketsSorted = false; } /// <summary> /// Sort the buckets if needed. /// </summary> private void LazySort() { if (!_areBucketsSorted) { _buckets.Sort(); _areBucketsSorted = true; } } /// <summary> /// Returns the <c>Bucket</c> that contains the value <c>v</c>. /// </summary> /// <param name="v">The point to search the bucket for.</param> /// <returns>A copy of the bucket containing point <paramref name="v"/>.</returns> public Bucket GetBucketOf(double v) { return (Bucket) _buckets[GetBucketIndexOf(v)].Clone(); } /// <summary> /// Returns the index in the <c>Histogram</c> of the <c>Bucket</c> /// that contains the value <c>v</c>. /// </summary> /// <param name="v">The point to search the bucket index for.</param> /// <returns>The index of the bucket containing the point.</returns> public int GetBucketIndexOf(double v) { // Sort if needed. LazySort(); // Binary search for the bucket index. int index = _buckets.BinarySearch(new Bucket(v), Bucket.DefaultPointComparer); if (index < 0) { throw new ArgumentException(Resources.ArgumentHistogramContainsNot); } return index; } /// <summary> /// Returns the lower bound of the histogram. /// </summary> public double LowerBound { get { LazySort(); return _buckets[0].LowerBound; } } /// <summary> /// Returns the upper bound of the histogram. /// </summary> public double UpperBound { get { LazySort(); return _buckets[_buckets.Count - 1].UpperBound; } } /// <summary> /// Gets the <c>n</c>'th bucket. /// </summary> /// <param name="n">The index of the bucket to be returned.</param> /// <returns>A copy of the <c>n</c>'th bucket.</returns> public Bucket this[int n] { get { LazySort(); return (Bucket) _buckets[n].Clone(); } } /// <summary> /// Gets the number of buckets. /// </summary> public int BucketCount { get { return _buckets.Count; } } /// <summary> /// Gets the total number of datapoints in the histogram. /// </summary> public double DataCount { get { double totalCount = 0; for (int i = 0; i < BucketCount; i++) { totalCount += this[i].Count; } return totalCount; } } /// <summary> /// Prints the buckets contained in the <see cref="Histogram"/>. /// </summary> public override string ToString() { var sb = new StringBuilder(); foreach (Bucket b in _buckets) { sb.Append(b); } return sb.ToString(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using NodaTime; using ProtoBuf; using System.IO; using Newtonsoft.Json; using QuantConnect.Securities; using System.Collections.Generic; using QuantConnect.Securities.Positions; namespace QuantConnect.Data.Custom.AlphaStreams { /// <summary> /// Snapshot of an algorithms portfolio state /// </summary> [ProtoContract(SkipConstructor = true)] public class AlphaStreamsPortfolioState : BaseData { /// <summary> /// The deployed alpha id. This is the id generated upon submission to the alpha marketplace /// </summary> [JsonProperty("alphaId", DefaultValueHandling = DefaultValueHandling.Ignore)] [ProtoMember(10)] public string AlphaId { get; set; } /// <summary> /// The algorithm's unique deploy identifier /// </summary> [JsonProperty("algorithmId", DefaultValueHandling = DefaultValueHandling.Ignore)] [ProtoMember(11)] public string AlgorithmId { get; set; } /// <summary> /// The source of this data point, 'live trading' or in sample /// </summary> [ProtoMember(12)] public string Source { get; set; } /// <summary> /// Portfolio state id /// </summary> [ProtoMember(13)] public int Id { get; set; } /// <summary> /// Algorithms account currency /// </summary> [ProtoMember(14)] public string AccountCurrency { get; set; } /// <summary> /// The current total portfolio value /// </summary> [ProtoMember(15)] public decimal TotalPortfolioValue { get; set; } /// <summary> /// The margin used /// </summary> [ProtoMember(16)] public decimal TotalMarginUsed { get; set; } /// <summary> /// The different positions groups /// </summary> [JsonProperty("positionGroups", DefaultValueHandling = DefaultValueHandling.Ignore)] [ProtoMember(17)] public List<PositionGroupState> PositionGroups { get; set; } /// <summary> /// Gets the cash book that keeps track of all currency holdings (only settled cash) /// </summary> [JsonProperty("cashBook", DefaultValueHandling = DefaultValueHandling.Ignore)] [ProtoMember(18)] public Dictionary<string, Cash> CashBook { get; set; } /// <summary> /// Gets the cash book that keeps track of all currency holdings (only unsettled cash) /// </summary> [JsonProperty("unsettledCashBook", DefaultValueHandling = DefaultValueHandling.Ignore)] [ProtoMember(19)] public Dictionary<string, Cash> UnsettledCashBook { get; set; } /// <summary> /// Return the Subscription Data Source /// </summary> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source file</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Subscription Data Source.</returns> public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { var source = Path.Combine( Globals.DataFolder, "alternative", "alphastreams", "portfoliostate", config.Symbol.Value.ToLowerInvariant(), $"{date:yyyyMMdd}.json" ); return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv); } /// <summary> /// Reader converts each line of the data source into BaseData objects. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Content of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>New data point object</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { var dataPoint = JsonConvert.DeserializeObject<AlphaStreamsPortfolioState>(line); dataPoint.Symbol = config.Symbol; return dataPoint; } /// <summary> /// Specifies the data time zone for this data type /// </summary> /// <remarks>Will throw <see cref="InvalidOperationException"/> for security types /// other than <see cref="SecurityType.Base"/></remarks> /// <returns>The <see cref="DateTimeZone"/> of this data type</returns> public override DateTimeZone DataTimeZone() { return DateTimeZone.Utc; } /// <summary> /// Return a new instance clone of this object, used in fill forward /// </summary> public override BaseData Clone() { return new AlphaStreamsPortfolioState { Id = Id, Time = Time, Source = Source, Symbol = Symbol, AlphaId = AlphaId, DataType = DataType, CashBook = CashBook, AlgorithmId = AlgorithmId, PositionGroups = PositionGroups, TotalMarginUsed = TotalMarginUsed, AccountCurrency = AccountCurrency, UnsettledCashBook = UnsettledCashBook, TotalPortfolioValue = TotalPortfolioValue, }; } /// <summary> /// Indicates that the data set is expected to be sparse /// </summary> public override bool IsSparseData() { return true; } } /// <summary> /// Snapshot of a position group state /// </summary> [ProtoContract(SkipConstructor = true)] public class PositionGroupState { /// <summary> /// Currently margin used /// </summary> [ProtoMember(1)] public decimal MarginUsed { get; set; } /// <summary> /// The margin used by this position in relation to the total portfolio value /// </summary> [ProtoMember(2)] public decimal PortfolioValuePercentage { get; set; } /// <summary> /// THe positions which compose this group /// </summary> [ProtoMember(3)] public List<PositionState> Positions { get; set; } } /// <summary> /// Snapshot of a position state /// </summary> [ProtoContract(SkipConstructor = true)] public class PositionState : IPosition { /// <summary> /// The symbol /// </summary> [ProtoMember(1)] public Symbol Symbol { get; set; } /// <summary> /// The quantity /// </summary> [ProtoMember(2)] public decimal Quantity { get; set; } /// <summary> /// The unit quantity. The unit quantities of a group define the group. For example, a covered /// call has 100 units of stock and -1 units of call contracts. /// </summary> [ProtoMember(3)] public decimal UnitQuantity { get; set; } /// <summary> /// Creates a new instance /// </summary> public static PositionState Create(IPosition position) { return new PositionState { Symbol = position.Symbol, Quantity = position.Quantity, UnitQuantity = position.UnitQuantity }; } } }
using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.Compilation.Parser; using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DotVVM.Framework.Tests.Parser.Dothtml { [TestClass] public class DothtmlTokenizerBindingTests : DothtmlTokenizerTestsBase { [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_SelfClosing_BindingAttribute() { var input = @" tr <input value=""{binding: FirstName}"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Slash, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_BindingInPlainText() { var input = @"tr {{binding: FirstName}}"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding() { var input = @"<input value=""{"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_CloseBinding() { var input = @"<input value=""{}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Text_CloseBinding() { var input = @"<input value=""{value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Text_WhiteSpace_Text_CloseBinding() { var input = @"<input value=""{value value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Colon_Text_CloseBinding() { var input = @"<input value=""{:value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Colon_CloseBinding() { var input = @"<input value=""{:value}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Incomplete_OpenBinding_Text_Colon_CloseBinding() { var input = @"<input value=""{name:}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.IsFalse(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Invalid_BindingInPlainText_NotClosed() { var input = @"tr {{binding: FirstName"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Invalid_BindingInPlainText_ClosedWithOneBrace() { var input = @"tr {{binding: FirstName}test"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual("FirstName", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(1, tokenizer.Tokens[i].Length); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_CurlyBraceInStringInBinding() { var input = @"tr {{binding: ""{"" + FirstName + ""}""}}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"""{"" + FirstName + ""}""", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_CurlyBraceInStringInBinding_EscapedQuotes() { var input = @"tr {{binding: ""\""{"" + FirstName + '\'""{'}}"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"""\""{"" + FirstName + '\'""{'", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_Tag_CurlyBraceInStringInBinding() { var input = @"<a href=""{binding: ""{"" + FirstName + ""}""}"">"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"""{"" + FirstName + ""}""", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Valid_Tag_CurlyBraceInStringInBinding_EscapedQuotes() { var input = @"<a href=""{binding: ""\""{"" + FirstName + '\'""{'}"">"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Equals, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.Colon, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"""\""{"" + FirstName + '\'""{'", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.DoubleQuote, tokenizer.Tokens[i++].Type); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_BindingParsing_Invalid_BindingInPlainText_SingleBraces_TreatedAsText() { var input = @"tr {binding: FirstName}test"" />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); var i = 0; Assert.AreEqual(1, tokenizer.Tokens.Count); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Valid_OneBrace() { var input = @"{binding: FirstName}"; // parse var tokenizer = new DothtmlTokenizer(); var result = tokenizer.TokenizeBinding(input, false); Assert.IsTrue(result); CheckForErrors(tokenizer, input.Length); Assert.AreEqual(6, tokenizer.Tokens.Count); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[0].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[1].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[4].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[5].Type); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Valid_DoubleBrace_NotStated() { var input = @"{{binding: FirstName}}"; // parse var tokenizer = new DothtmlTokenizer(); var result =tokenizer.TokenizeBinding(input, false); Assert.IsTrue(result); CheckForErrors(tokenizer, input.Length); Assert.AreEqual(6, tokenizer.Tokens.Count); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[0].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[1].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[4].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[5].Type); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Valid_InvalidTextAround() { var input = @"dfds dsfsffds {binding: FirstName}fdsdsf"; // parse var tokenizer = new DothtmlTokenizer(); var result = tokenizer.TokenizeBinding(input, false); Assert.IsFalse(result); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Invalid_InvalidTextEnd() { var input = @"{binding: FirstName}fdsdsf"; // parse var tokenizer = new DothtmlTokenizer(); var result = tokenizer.TokenizeBinding(input, false); Assert.IsFalse(result); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Invalid_UnfinishedText() { var input = @"{binding: ""FirstName}fdsdsf"; // parse var tokenizer = new DothtmlTokenizer(); var result = tokenizer.TokenizeBinding(input, false); Assert.IsFalse(result); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Invalid_Unclosed() { var input = @"{binding: FirstName"; // parse var tokenizer = new DothtmlTokenizer(); var result = tokenizer.TokenizeBinding(input, false); Assert.IsFalse(result); } [TestMethod] public void DothtmlTokenizer_TokenizeBinding_Valid_StringInside() { var input = @"{binding: FirstName + ""{not: Binding}""}"; // parse var tokenizer = new DothtmlTokenizer(); var result = tokenizer.TokenizeBinding(input, false); Assert.IsTrue(result); CheckForErrors(tokenizer, input.Length); Assert.AreEqual(6, tokenizer.Tokens.Count); Assert.AreEqual(DothtmlTokenType.OpenBinding, tokenizer.Tokens[0].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[1].Type); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[4].Type); Assert.AreEqual(DothtmlTokenType.CloseBinding, tokenizer.Tokens[5].Type); } } }
/* * 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.Linq.Impl { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; /// <summary> /// MethodCall expression visitor. /// </summary> internal static class MethodVisitor { /// <summary> The string length method. </summary> public static readonly MemberInfo StringLength = typeof (string).GetProperty("Length"); /// <summary> Method visit delegate. </summary> private delegate void VisitMethodDelegate(MethodCallExpression expression, CacheQueryExpressionVisitor visitor); /// <summary> /// Delegates dictionary. /// </summary> private static readonly Dictionary<MethodInfo, VisitMethodDelegate> Delegates = new List <KeyValuePair<MethodInfo, VisitMethodDelegate>> { GetStringMethod("ToLower", new Type[0], GetFunc("lower")), GetStringMethod("ToUpper", new Type[0], GetFunc("upper")), GetStringMethod("Contains", del: (e, v) => VisitSqlLike(e, v, "'%' || ? || '%'")), GetStringMethod("StartsWith", new[] {typeof (string)}, (e, v) => VisitSqlLike(e, v, "? || '%'")), GetStringMethod("EndsWith", new[] {typeof (string)}, (e, v) => VisitSqlLike(e, v, "'%' || ?")), GetStringMethod("IndexOf", new[] {typeof (string)}, GetFunc("instr", -1)), GetStringMethod("IndexOf", new[] {typeof (string), typeof (int)}, GetFunc("instr", -1)), GetStringMethod("Substring", new[] {typeof (int)}, GetFunc("substring", 0, 1)), GetStringMethod("Substring", new[] {typeof (int), typeof (int)}, GetFunc("substring", 0, 1)), GetStringMethod("Trim", "trim"), GetStringMethod("Trim", "trim", typeof(char[])), GetStringMethod("TrimStart", "ltrim", typeof(char[])), GetStringMethod("TrimEnd", "rtrim", typeof(char[])), GetStringMethod("Replace", "replace", typeof(string), typeof(string)), GetMethod(typeof (Regex), "Replace", new[] {typeof (string), typeof (string), typeof (string)}, GetFunc("regexp_replace")), GetMethod(typeof (DateTime), "ToString", new[] {typeof (string)}, (e, v) => VisitFunc(e, v, "formatdatetime", ", 'en', 'UTC'")), GetMathMethod("Abs", typeof (int)), GetMathMethod("Abs", typeof (long)), GetMathMethod("Abs", typeof (float)), GetMathMethod("Abs", typeof (double)), GetMathMethod("Abs", typeof (decimal)), GetMathMethod("Abs", typeof (sbyte)), GetMathMethod("Abs", typeof (short)), GetMathMethod("Acos", typeof (double)), GetMathMethod("Asin", typeof (double)), GetMathMethod("Atan", typeof (double)), GetMathMethod("Atan2", typeof (double), typeof (double)), GetMathMethod("Ceiling", typeof (double)), GetMathMethod("Ceiling", typeof (decimal)), GetMathMethod("Cos", typeof (double)), GetMathMethod("Cosh", typeof (double)), GetMathMethod("Exp", typeof (double)), GetMathMethod("Floor", typeof (double)), GetMathMethod("Floor", typeof (decimal)), GetMathMethod("Log", typeof (double)), GetMathMethod("Log10", typeof (double)), GetMathMethod("Pow", "Power", typeof (double), typeof (double)), GetMathMethod("Round", typeof (double)), GetMathMethod("Round", typeof (double), typeof (int)), GetMathMethod("Round", typeof (decimal)), GetMathMethod("Round", typeof (decimal), typeof (int)), GetMathMethod("Sign", typeof (double)), GetMathMethod("Sign", typeof (decimal)), GetMathMethod("Sign", typeof (float)), GetMathMethod("Sign", typeof (int)), GetMathMethod("Sign", typeof (long)), GetMathMethod("Sign", typeof (short)), GetMathMethod("Sign", typeof (sbyte)), GetMathMethod("Sin", typeof (double)), GetMathMethod("Sinh", typeof (double)), GetMathMethod("Sqrt", typeof (double)), GetMathMethod("Tan", typeof (double)), GetMathMethod("Tanh", typeof (double)), GetMathMethod("Truncate", typeof (double)), GetMathMethod("Truncate", typeof (decimal)), }.ToDictionary(x => x.Key, x => x.Value); /// <summary> /// Visits the method call expression. /// </summary> public static void VisitMethodCall(MethodCallExpression expression, CacheQueryExpressionVisitor visitor) { var mtd = expression.Method; VisitMethodDelegate del; if (!Delegates.TryGetValue(mtd, out del)) throw new NotSupportedException(string.Format("Method not supported: {0}.({1})", mtd.DeclaringType == null ? "static" : mtd.DeclaringType.FullName, mtd)); del(expression, visitor); } /// <summary> /// Gets the function. /// </summary> private static VisitMethodDelegate GetFunc(string func, params int[] adjust) { return (e, v) => VisitFunc(e, v, func, null, adjust); } /// <summary> /// Visits the instance function. /// </summary> private static void VisitFunc(MethodCallExpression expression, CacheQueryExpressionVisitor visitor, string func, string suffix, params int[] adjust) { visitor.ResultBuilder.Append(func).Append("("); var isInstanceMethod = expression.Object != null; if (isInstanceMethod) visitor.Visit(expression.Object); for (int i= 0; i < expression.Arguments.Count; i++) { var arg = expression.Arguments[i]; if (isInstanceMethod || (i > 0)) visitor.ResultBuilder.Append(", "); if (arg.NodeType == ExpressionType.NewArrayInit) { // Only trim methods use params[], only one param is supported var args = ((NewArrayExpression) arg).Expressions; if (args.Count != 1) throw new NotSupportedException("Method call only supports a single parameter: "+ expression); visitor.Visit(args[0]); } else visitor.Visit(arg); AppendAdjustment(visitor, adjust, i + 1); } visitor.ResultBuilder.Append(suffix).Append(")"); AppendAdjustment(visitor, adjust, 0); } /// <summary> /// Appends the adjustment. /// </summary> private static void AppendAdjustment(CacheQueryExpressionVisitor visitor, int[] adjust, int idx) { if (idx < adjust.Length) { var delta = adjust[idx]; if (delta > 0) visitor.ResultBuilder.AppendFormat(" + {0}", delta); else if (delta < 0) visitor.ResultBuilder.AppendFormat(" {0}", delta); } } /// <summary> /// Visits the SQL like expression. /// </summary> private static void VisitSqlLike(MethodCallExpression expression, CacheQueryExpressionVisitor visitor, string likeFormat) { visitor.ResultBuilder.Append("("); visitor.Visit(expression.Object); visitor.ResultBuilder.AppendFormat(" like {0}) ", likeFormat); var arg = expression.Arguments[0] as ConstantExpression; var paramValue = arg != null ? arg.Value : visitor.RegisterEvaluatedParameter(expression.Arguments[0]); visitor.Parameters.Add(paramValue); } /// <summary> /// Gets the method. /// </summary> private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetMethod(Type type, string name, Type[] argTypes = null, VisitMethodDelegate del = null) { var method = argTypes == null ? type.GetMethod(name) : type.GetMethod(name, argTypes); return new KeyValuePair<MethodInfo, VisitMethodDelegate>(method, del ?? GetFunc(name)); } /// <summary> /// Gets the string method. /// </summary> private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetStringMethod(string name, Type[] argTypes = null, VisitMethodDelegate del = null) { return GetMethod(typeof(string), name, argTypes, del); } /// <summary> /// Gets the string method. /// </summary> private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetStringMethod(string name, string sqlName, params Type[] argTypes) { return GetMethod(typeof(string), name, argTypes, GetFunc(sqlName)); } /// <summary> /// Gets the math method. /// </summary> private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetMathMethod(string name, string sqlName, params Type[] argTypes) { return GetMethod(typeof(Math), name, argTypes, GetFunc(sqlName)); } /// <summary> /// Gets the math method. /// </summary> private static KeyValuePair<MethodInfo, VisitMethodDelegate> GetMathMethod(string name, params Type[] argTypes) { return GetMathMethod(name, name, argTypes); } } }
// Copyright (c) 2014-2015 Robert Rouhani <[email protected]> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using System.Collections.Generic; #if MONOGAME using Vector3 = Microsoft.Xna.Framework.Vector3; #elif OPENTK using Vector3 = OpenTK.Vector3; #elif SHARPDX using Vector3 = SharpDX.Vector3; #endif namespace SharpNav.Geometry { //TODO array bounds checking to catch out of bounds exceptions early. //TODO index arrays of other integral types (byte, sbyte, short, ushort, uint) - possibly make generic? /// <summary> /// A static class that generates an <see cref="IEnumerable{T}"/> of <see cref="Triangle3"/> using iterator blocks. /// </summary> public static class TriangleEnumerable { /// <summary> /// Iterates over an array of <see cref="Triangle3"/> with a specified offset and length. /// </summary> /// <param name="triangles">An array of triangles.</param> /// <param name="triOffset">The index of the first triangle to be enumerated.</param> /// <param name="triCount">The number of triangles to enumerate.</param> /// <returns>An enumerable collection of triangles.</returns> public static IEnumerable<Triangle3> FromTriangle(Triangle3[] triangles, int triOffset, int triCount) { for (int i = 0; i < triCount; i++) yield return triangles[triOffset + i]; } /// <summary> /// Iterates over an array of <see cref="Vector3"/> with a specified offset, stride, and length. /// </summary> /// <param name="vertices">An array of vertices.</param> /// <param name="vertOffset">The index of the first vertex to be enumerated.</param> /// <param name="vertStride">The distance between the start of two triangles. A value of 0 means the data is tightly packed.</param> /// <param name="triCount">The number of triangles to enumerate.</param> /// <returns>An enumerable collection of triangles.</returns> public static IEnumerable<Triangle3> FromVector3(Vector3[] vertices, int vertOffset, int vertStride, int triCount) { Triangle3 tri; if (vertStride == 0) vertStride = 3; for (int i = 0; i < triCount; i++) { tri.A = vertices[i * vertStride + vertOffset]; tri.B = vertices[i * vertStride + vertOffset + 1]; tri.C = vertices[i * vertStride + vertOffset + 2]; yield return tri; } } /// <summary> /// Iterates over an array of <see cref="float"/> with a specified offset, stride, and length. /// </summary> /// <param name="vertices">An array of vertices.</param> /// <param name="floatOffset">The index of the first float to be enumerated.</param> /// <param name="floatStride">The distance between the start of two vertices. A value of 0 means the data is tightly packed.</param> /// <param name="triCount">The number of triangles to enumerate.</param> /// <returns>An enumerable collection of triangles.</returns> public static IEnumerable<Triangle3> FromFloat(float[] vertices, int floatOffset, int floatStride, int triCount) { Triangle3 tri; if (floatStride == 0) floatStride = 3; for (int i = 0; i < triCount; i++) { int indA = i * (floatStride * 3) + floatOffset; int indB = indA + floatStride; int indC = indB + floatStride; tri.A.X = vertices[indA]; tri.A.Y = vertices[indA + 1]; tri.A.Z = vertices[indA + 2]; tri.B.X = vertices[indB]; tri.B.Y = vertices[indB + 1]; tri.B.Z = vertices[indB + 2]; tri.C.X = vertices[indC]; tri.C.Y = vertices[indC + 1]; tri.C.Z = vertices[indC + 2]; yield return tri; } } /// <summary> /// Iterates over an array of <see cref="Vector3"/> indexed by an array of <see cref="int"/> with a specified offset, stride, and length. /// </summary> /// <param name="vertices">An array of vertices.</param> /// <param name="indices">An array of indices.</param> /// <param name="vertOffset">The index of the first vertex to be enumerated.</param> /// <param name="vertStride">The distance between the start of two triangles. A value of 0 means the data is tightly packed.</param> /// <param name="indexOffset">The index of the first index to be enumerated.</param> /// <param name="triCount">The number of triangles to enumerate.</param> /// <returns>An enumerable collection of triangles.</returns> public static IEnumerable<Triangle3> FromIndexedVector3(Vector3[] vertices, int[] indices, int vertOffset, int vertStride, int indexOffset, int triCount) { Triangle3 tri; for (int i = 0; i < triCount; i++) { int indA = vertOffset + indices[i * 3 + indexOffset] * vertStride; int indB = vertOffset + indices[i * 3 + indexOffset + 1] * vertStride; int indC = vertOffset + indices[i * 3 + indexOffset + 2] * vertStride; tri.A = vertices[indA]; tri.B = vertices[indB]; tri.C = vertices[indC]; yield return tri; } } /// <summary> /// Iterates over an array of <see cref="float"/> indexed by an array of <see cref="int"/> with a specified offset, stride, and length. /// </summary> /// <param name="vertices">An array of vertices.</param> /// <param name="indices">An array of indices.</param> /// <param name="floatOffset">The index of the first float to be enumerated.</param> /// <param name="floatStride">The distance between the start of two vertices. A value of 0 means the data is tightly packed.</param> /// <param name="indexOffset">The index of the first index to be enumerated.</param> /// <param name="triCount">The number of triangles to enumerate.</param> /// <returns>An enumerable collection of triangles.</returns> public static IEnumerable<Triangle3> FromIndexedFloat(float[] vertices, int[] indices, int floatOffset, int floatStride, int indexOffset, int triCount) { Triangle3 tri; for (int i = 0; i < triCount; i++) { int indA = floatOffset + indices[i * 3 + indexOffset] * floatStride; int indB = floatOffset + indices[i * 3 + indexOffset + 1] * floatStride; int indC = floatOffset + indices[i * 3 + indexOffset + 2] * floatStride; tri.A.X = vertices[indA]; tri.A.Y = vertices[indA + 1]; tri.A.Z = vertices[indA + 2]; tri.B.X = vertices[indB]; tri.B.Y = vertices[indB + 1]; tri.B.Z = vertices[indB + 2]; tri.C.X = vertices[indC]; tri.C.Y = vertices[indC + 1]; tri.C.Z = vertices[indC + 2]; yield return tri; } } /// <summary> /// Generates a bounding box for a collection of triangles. /// </summary> /// <param name="tris">The triangles to create a bounding box from.</param> /// <returns>A bounding box containing every triangle.</returns> public static BBox3 GetBoundingBox(this IEnumerable<Triangle3> tris) { return GetBoundingBox(tris, float.Epsilon * 2f); } /// <summary> /// Generates a bounding box for a collection of triangles. /// </summary> /// <param name="tris">The triangles to create a bounding box from.</param> /// <param name="padding">Padding to the bounding box</param> /// <returns>A bounding box containing every triangle.</returns> public static BBox3 GetBoundingBox(this IEnumerable<Triangle3> tris, float padding) { BBox3 bounds = new BBox3(); Vector3 va, vb, vc; foreach (Triangle3 tri in tris) { va = tri.A; vb = tri.B; vc = tri.C; ApplyVertexToBounds(ref va, ref bounds); ApplyVertexToBounds(ref vb, ref bounds); ApplyVertexToBounds(ref vc, ref bounds); } //pad the bounding box a bit to make sure outer triangles are fully contained. ApplyPaddingToBounds(padding, ref bounds); return bounds; } /// <summary> /// Generates a bounding box for a collection of vectors. /// </summary> /// <param name="vecs">The vectors to create a bounding box from.</param> /// <returns>A bounding box containing every vector.</returns> public static BBox3 GetBoundingBox(this IEnumerable<Vector3> vecs) { BBox3 bounds = new BBox3(); Vector3 v; foreach (Vector3 vec in vecs) { v = vec; ApplyVertexToBounds(ref v, ref bounds); } ApplyPaddingToBounds(1.0f, ref bounds); return bounds; } /// <summary> /// Adjusts a bounding box to include a vertex. /// </summary> /// <param name="v">The vertex to include.</param> /// <param name="b">The bounding box to adjust.</param> private static void ApplyVertexToBounds(ref Vector3 v, ref BBox3 b) { if (v.X < b.Min.X) b.Min.X = v.X; if (v.Y < b.Min.Y) b.Min.Y = v.Y; if (v.Z < b.Min.Z) b.Min.Z = v.Z; if (v.X > b.Max.X) b.Max.X = v.X; if (v.Y > b.Max.Y) b.Max.Y = v.Y; if (v.Z > b.Max.Z) b.Max.Z = v.Z; } /// <summary> /// Applies a padding to the bounding box. /// </summary> /// <param name="pad">The amount to pad the bounding box on all sides.</param> /// <param name="b">The bounding box to pad.</param> private static void ApplyPaddingToBounds(float pad, ref BBox3 b) { b.Min.X -= pad; b.Min.Y -= pad; b.Min.Z -= pad; b.Max.X += pad; b.Max.Y += pad; b.Max.Z += pad; } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Collections; using System.Runtime.InteropServices; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; using Ovr; /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { /// <summary> /// Contains information about the user's preferences and body dimensions. /// </summary> public struct Profile { public float ipd; public float eyeHeight; public float eyeDepth; public float neckHeight; } /// <summary> /// Contains the valid range of antialiasing levels usable with Unity render textures. /// </summary> public enum RenderTextureAntiAliasing { _1 = 1, _2 = 2, _4 = 4, _8 = 8, } /// <summary> /// Contains the valid range of texture depth values usable with Unity render textures. /// </summary> public enum RenderTextureDepth { _0 = 0, _16 = 16, _24 = 24, } /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } private static Hmd _capiHmd; /// <summary> /// Gets a reference to the low-level C API Hmd Wrapper /// </summary> public static Hmd capiHmd { get { #if !UNITY_ANDROID || UNITY_EDITOR if (_capiHmd == null) { IntPtr hmdPtr = IntPtr.Zero; OVR_GetHMD(ref hmdPtr); _capiHmd = (hmdPtr != IntPtr.Zero) ? new Hmd(hmdPtr) : null; } #else _capiHmd = null; #endif return _capiHmd; } } /// <summary> /// Gets a reference to the active OVRDisplay /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active OVRTracker /// </summary> public static OVRTracker tracker { get; private set; } private static bool _profileIsCached = false; private static Profile _profile; /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> public static Profile profile { get { if (!_profileIsCached) { #if !UNITY_ANDROID || UNITY_EDITOR float ipd = capiHmd.GetFloat(Hmd.OVR_KEY_IPD, Hmd.OVR_DEFAULT_IPD); float eyeHeight = capiHmd.GetFloat(Hmd.OVR_KEY_EYE_HEIGHT, Hmd.OVR_DEFAULT_EYE_HEIGHT); float[] defaultOffset = new float[] { Hmd.OVR_DEFAULT_NECK_TO_EYE_HORIZONTAL, Hmd.OVR_DEFAULT_NECK_TO_EYE_VERTICAL }; float[] neckToEyeOffset = capiHmd.GetFloatArray(Hmd.OVR_KEY_NECK_TO_EYE_DISTANCE, defaultOffset); float neckHeight = eyeHeight - neckToEyeOffset[1]; _profile = new Profile { ipd = ipd, eyeHeight = eyeHeight, eyeDepth = neckToEyeOffset[0], neckHeight = neckHeight, }; #else float ipd = 0.0f; OVR_GetInterpupillaryDistance(ref ipd); float eyeHeight = 0.0f; OVR_GetPlayerEyeHeight(ref eyeHeight); _profile = new Profile { ipd = ipd, eyeHeight = eyeHeight, eyeDepth = 0f, //TODO neckHeight = 0.0f, // TODO }; #endif _profileIsCached = true; } return _profile; } } /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when the tracker gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the tracker lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when HSW dismissed. /// </summary> public static event Action HSWDismissed; /// <summary> /// Occurs when the Native Texture Scale is modified. /// </summary> internal static event Action<float, float> NativeTextureScaleModified; /// <summary> /// Occurs when the Virtual Texture Scale is modified. /// </summary> internal static event Action<float, float> VirtualTextureScaleModified; /// <summary> /// Occurs when the Eye Texture AntiAliasing level is modified. /// </summary> internal static event Action<RenderTextureAntiAliasing, RenderTextureAntiAliasing> EyeTextureAntiAliasingModified; /// <summary> /// Occurs when the Eye Texture Depth is modified. /// </summary> internal static event Action<RenderTextureDepth, RenderTextureDepth> EyeTextureDepthModified; /// <summary> /// Occurs when the Eye Texture Format is modified. /// </summary> internal static event Action<RenderTextureFormat, RenderTextureFormat> EyeTextureFormatModified; /// <summary> /// Occurs when Monoscopic mode is modified. /// </summary> internal static event Action<bool, bool> MonoscopicModified; /// <summary> /// Occurs when HDR mode is modified. /// </summary> internal static event Action<bool, bool> HdrModified; /// <summary> /// If true, then the Oculus health and safety warning (HSW) is currently visible. /// </summary> public static bool isHSWDisplayed { get { #if !UNITY_ANDROID || UNITY_EDITOR return (capiHmd.GetHSWDisplayState().Displayed != 0); #else return false; #endif } } /// <summary> /// If the HSW has been visible for the necessary amount of time, this will make it disappear. /// </summary> public static void DismissHSWDisplay() { #if !UNITY_ANDROID || UNITY_EDITOR capiHmd.DismissHSWDisplay(); #endif } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { #if !UNITY_ANDROID || UNITY_EDITOR return 1.0f; #else return OVR_GetBatteryLevel(); #endif } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0.0f; #else return OVR_GetBatteryTemperature(); #endif } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0; #else return OVR_GetBatteryStatus(); #endif } } /// <summary> /// Gets the current volume level. /// </summary> /// <returns><c>volume level in the range [0,MaxVolume], or -1 for not initialized.</c> public static int volumeLevel { get { #if !UNITY_ANDROID || UNITY_EDITOR Debug.LogError( "GetVolume() is only supported on Android" ); return -1; #else return OVR_GetVolume(); #endif } } /// <summary> /// Gets the time since last volume change /// </summary> /// <returns><c>time since last volume change or -1 for not initialized.</c> public static double timeSinceLastVolumeChange { get { #if !UNITY_ANDROID || UNITY_EDITOR Debug.LogError( "GetTimeSinceLastVolumeChange() is only supported on Android" ); return -1; #else return OVR_GetTimeSinceLastVolumeChange(); #endif } } [Range(0.1f, 4.0f)] /// <summary> /// Controls the size of the eye textures. /// Values must be above 0. /// Values below 1 permit sub-sampling for improved performance. /// Values above 1 permit super-sampling for improved sharpness. /// </summary> public float nativeTextureScale = 1.0f; [Range(0.1f, 1.0f)] /// <summary> /// Controls the size of the rendering viewport. /// Values must be above 0 and less than or equal to 1. /// Values below 1 permit dynamic sub-sampling for improved performance. /// </summary> public float virtualTextureScale = 1.0f; /// <summary> /// The format of each eye texture. /// </summary> public RenderTextureFormat eyeTextureFormat = RenderTextureFormat.Default; /// <summary> /// The antialiasing level of each eye texture. /// </summary> public RenderTextureAntiAliasing eyeTextureAntiAliasing = RenderTextureAntiAliasing._2; /// <summary> /// The depth of each eye texture in bits. Valid Unity render texture depths are 0, 16, and 24. /// </summary> public RenderTextureDepth eyeTextureDepth = RenderTextureDepth._24; /// <summary> /// If true, head tracking will affect the orientation of each OVRCameraRig's cameras. /// </summary> public bool usePositionTracking = true; /// <summary> /// If true, TimeWarp will be used to correct the output of each OVRCameraRig for rotational latency. /// </summary> public bool timeWarp = true; /// <summary> /// If this is true and TimeWarp is true, each OVRCameraRig will stop tracking and only TimeWarp will respond to head motion. /// </summary> public bool freezeTimeWarp = false; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> public bool resetTrackerOnLoad = true; /// <summary> /// If true, the eyes see the same image, which is rendered only by the left camera. /// </summary> public bool monoscopic = false; /// <summary> /// If true, enable high dynamic range support. /// </summary> public bool hdr = false; /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } private static bool usingPositionTrackingCached = false; private static bool usingPositionTracking = false; private static bool wasHmdPresent = false; private static bool wasPositionTracked = false; private static float prevNativeTextureScale; private static float prevVirtualTextureScale; private static RenderTextureAntiAliasing prevEyeTextureAntiAliasing; private static RenderTextureDepth prevEyeTextureDepth; private static bool prevMonoscopic; private static bool prevHdr; private static RenderTextureFormat prevEyeTextureFormat; private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); #if UNITY_ANDROID && !UNITY_EDITOR // Get this from Unity on startup so we can call Activity java functions private static bool androidJavaInit = false; private static AndroidJavaObject activity; private static AndroidJavaClass javaVrActivityClass; internal static int timeWarpViewNumber = 0; [NonSerialized] private static OVRVolumeControl VolumeController = null; public static void EnterVRMode() { OVRPluginEvent.Issue(RenderEventType.Resume); } public static void LeaveVRMode() { OVRPluginEvent.Issue(RenderEventType.Pause); } #else private static bool ovrIsInitialized; private static bool isQuitting; #endif #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; #if !UNITY_ANDROID || UNITY_EDITOR if (!ovrIsInitialized) { OVR_Initialize(); OVRPluginEvent.Issue(RenderEventType.Initialize); ovrIsInitialized = true; } var netVersion = new System.Version(Ovr.Hmd.OVR_VERSION_STRING); System.Version ovrVersion = new System.Version("0.0.0"); var versionString = Ovr.Hmd.GetVersionString(); var success = false; try { ovrVersion = new System.Version(versionString); success = true; } catch (Exception e) { Debug.Log("Failed to parse Oculus version string \"" + versionString + "\" with message \"" + e.Message + "\"."); } if (!success || netVersion > ovrVersion) Debug.LogWarning("Version check failed. Please make sure you are using Oculus runtime " + Ovr.Hmd.OVR_VERSION_STRING + " or newer."); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR // don't allow the application to run if orientation is not landscape left. if (Screen.orientation != ScreenOrientation.LandscapeLeft) { Debug.LogError("********************************************************************************\n"); Debug.LogError("***** Default screen orientation must be set to landscape left for VR.\n" + "***** Stopping application.\n"); Debug.LogError("********************************************************************************\n"); Debug.Break(); Application.Quit(); } // don't enable gyro, it is not used and triggers expensive display calls if (Input.gyro.enabled) { Debug.LogError("*** Auto-disabling Gyroscope ***"); Input.gyro.enabled = false; } // don't enable antiAliasing on the main window display, it may cause // bad behavior with various tiling controls. if (QualitySettings.antiAliasing > 1) { Debug.LogError("*** Main Display should have 0 samples ***"); } // we sync in the TimeWarp, so we don't want unity // syncing elsewhere QualitySettings.vSyncCount = 0; // try to render at 60fps Application.targetFrameRate = 60; // don't allow the app to run in the background Application.runInBackground = false; // Disable screen dimming Screen.sleepTimeout = SleepTimeout.NeverSleep; if (!androidJavaInit) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); javaVrActivityClass = new AndroidJavaClass("com.oculusvr.vrlib.VrActivity"); // Prepare for the RenderThreadInit() SetInitVariables(activity.GetRawObject(), javaVrActivityClass.GetRawClass()); androidJavaInit = true; } // We want to set up our touchpad messaging system OVRTouchpad.Create(); InitVolumeController(); #else SetEditorPlay(Application.isEditor); #endif prevEyeTextureAntiAliasing = OVRManager.instance.eyeTextureAntiAliasing; prevEyeTextureDepth = OVRManager.instance.eyeTextureDepth; prevEyeTextureFormat = OVRManager.instance.eyeTextureFormat; prevNativeTextureScale = OVRManager.instance.nativeTextureScale; prevVirtualTextureScale = OVRManager.instance.virtualTextureScale; prevMonoscopic = OVRManager.instance.monoscopic; prevHdr = OVRManager.instance.hdr; if (display == null) display = new OVRDisplay(); if (tracker == null) tracker = new OVRTracker(); if (resetTrackerOnLoad) display.RecenterPose(); #if !UNITY_ANDROID || UNITY_EDITOR // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps(). if (timeWarp) { bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"); QualitySettings.vSyncCount = useUnityVSync ? 1 : 0; } #endif #if UNITY_STANDALONE_WIN if (!OVRUnityVersionChecker.hasD3D9ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9")) { MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } if (!OVRUnityVersionChecker.hasD3D11ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")) { MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } #endif } private void OnDestroy() { #if UNITY_ANDROID && !UNITY_EDITOR RenderTexture.active = null; #endif } private void OnApplicationQuit() { #if !UNITY_ANDROID || UNITY_EDITOR isQuitting = true; #else Debug.Log( "OnApplicationQuit" ); // This will trigger the shutdown on the render thread OVRPluginEvent.Issue( RenderEventType.ShutdownRenderThread ); #endif } private void OnEnable() { #if !UNITY_ANDROID || UNITY_EDITOR Camera cam = GetComponent<Camera>(); if (cam == null) { // Ensure there is a non-RT camera in the scene to force rendering of the left and right eyes. cam = gameObject.AddComponent<Camera>(); cam.cullingMask = 0; cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.0f, 0.0f, 0.0f); cam.renderingPath = RenderingPath.Forward; cam.orthographic = true; cam.useOcclusionCulling = false; } #endif bool isD3d = SystemInfo.graphicsDeviceVersion.Contains("Direct3D") || Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceVersion.Contains("emulated"); display.flipInput = isD3d; StartCoroutine(CallbackCoroutine()); #if UNITY_ANDROID && !UNITY_EDITOR if (VolumeController != null) { OVRPose pose = OVRManager.display.GetHeadPose(); VolumeController.UpdatePosition(pose.orientation, pose.position); } #endif } private void OnDisable() { #if !UNITY_ANDROID || UNITY_EDITOR if (!isQuitting) return; if (ovrIsInitialized) { OVR_Destroy(); OVRPluginEvent.Issue(RenderEventType.Destroy); _capiHmd = null; ovrIsInitialized = false; } #else StopAllCoroutines(); #endif } private void Start() { #if UNITY_ANDROID && !UNITY_EDITOR // NOTE: For Android, the resolution should be the same for both left and right eye OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); Vector2 resolution = leftEyeDesc.resolution; OVR_SetEyeParms((int)resolution.x,(int)resolution.y); // This will trigger the init on the render thread InitRenderThread(); #endif } private void Update() { if (!usingPositionTrackingCached || usingPositionTracking != usePositionTracking) { tracker.isEnabled = usePositionTracking; usingPositionTracking = usePositionTracking; usingPositionTrackingCached = true; } // Dispatch any events. if (HMDLost != null && wasHmdPresent && !display.isPresent) HMDLost(); if (HMDAcquired != null && !wasHmdPresent && display.isPresent) HMDAcquired(); wasHmdPresent = display.isPresent; if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked) TrackingLost(); if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked) TrackingAcquired(); wasPositionTracked = tracker.isPositionTracked; if (NativeTextureScaleModified != null && nativeTextureScale != prevNativeTextureScale) NativeTextureScaleModified(prevNativeTextureScale, nativeTextureScale); prevNativeTextureScale = nativeTextureScale; if (VirtualTextureScaleModified != null && virtualTextureScale != prevVirtualTextureScale) VirtualTextureScaleModified(prevVirtualTextureScale, virtualTextureScale); prevVirtualTextureScale = virtualTextureScale; if (EyeTextureAntiAliasingModified != null && eyeTextureAntiAliasing != prevEyeTextureAntiAliasing) EyeTextureAntiAliasingModified(prevEyeTextureAntiAliasing, eyeTextureAntiAliasing); prevEyeTextureAntiAliasing = eyeTextureAntiAliasing; if (EyeTextureDepthModified != null && eyeTextureDepth != prevEyeTextureDepth) EyeTextureDepthModified(prevEyeTextureDepth, eyeTextureDepth); prevEyeTextureDepth = eyeTextureDepth; if (EyeTextureFormatModified != null && eyeTextureFormat != prevEyeTextureFormat) EyeTextureFormatModified(prevEyeTextureFormat, eyeTextureFormat); prevEyeTextureFormat = eyeTextureFormat; if (MonoscopicModified != null && monoscopic != prevMonoscopic) MonoscopicModified(prevMonoscopic, monoscopic); prevMonoscopic = monoscopic; if (HdrModified != null && hdr != prevHdr) HdrModified(prevHdr, hdr); prevHdr = hdr; if (isHSWDisplayed && Input.anyKeyDown) { DismissHSWDisplay(); if (HSWDismissed != null) HSWDismissed(); } display.timeWarp = timeWarp; display.Update(); #if UNITY_ANDROID && !UNITY_EDITOR if (VolumeController != null) { OVRPose pose = OVRManager.display.GetHeadPose(); VolumeController.UpdatePosition(pose.orientation, pose.position); } #endif } #if (UNITY_EDITOR_OSX) private void OnPreCull() // TODO: Fix Mac Unity Editor memory corruption issue requiring OnPreCull workaround. #else private void LateUpdate() #endif { #if (!UNITY_ANDROID || UNITY_EDITOR) display.BeginFrame(); #endif } private IEnumerator CallbackCoroutine() { while (true) { yield return waitForEndOfFrame; #if UNITY_ANDROID && !UNITY_EDITOR OVRManager.DoTimeWarp(timeWarpViewNumber); #else display.EndFrame(); #endif } } #if UNITY_ANDROID && !UNITY_EDITOR private void OnPause() { LeaveVRMode(); } private IEnumerator OnResume() { yield return null; // delay 1 frame to allow Unity enough time to create the windowSurface EnterVRMode(); } private void OnApplicationPause(bool pause) { Debug.Log("OnApplicationPause() " + pause); if (pause) { OnPause(); } else { StartCoroutine(OnResume()); } } void OnApplicationFocus( bool focus ) { // OnApplicationFocus() does not appear to be called // consistently while OnApplicationPause is. Moved // functionality to OnApplicationPause(). Debug.Log( "OnApplicationFocus() " + focus ); } /// <summary> /// Creates a popup dialog that shows when volume changes. /// </summary> private static void InitVolumeController() { if (VolumeController == null) { Debug.Log("Creating volume controller..."); // Create the volume control popup GameObject go = GameObject.Instantiate(Resources.Load("OVRVolumeController")) as GameObject; if (go != null) { VolumeController = go.GetComponent<OVRVolumeControl>(); } else { Debug.LogError("Unable to instantiate volume controller"); } } } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } #endif #endregion public static void SetEditorPlay(bool isEditor) { #if !UNITY_ANDROID || UNITY_EDITOR OVR_SetEditorPlay(isEditor); #endif } public static void SetInitVariables(IntPtr activity, IntPtr vrActivityClass) { #if UNITY_ANDROID && !UNITY_EDITOR OVR_SetInitVariables(activity, vrActivityClass); #endif } public static void PlatformUIConfirmQuit() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUIConfirmQuit); #endif } public static void PlatformUIGlobalMenu() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUI); #endif } public static void DoTimeWarp(int timeWarpViewNumber) { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.IssueWithData(RenderEventType.TimeWarp, timeWarpViewNumber); #endif } public static void EndEye(OVREye eye) { #if UNITY_ANDROID && !UNITY_EDITOR RenderEventType eventType = (eye == OVREye.Left) ? RenderEventType.LeftEyeEndFrame : RenderEventType.RightEyeEndFrame; int eyeTextureId = display.GetEyeTextureId(eye); OVRPluginEvent.IssueWithData(eventType, eyeTextureId); #endif } public static void InitRenderThread() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.InitRenderThread); #endif } private const string LibOVR = "OculusPlugin"; #if !UNITY_ANDROID || UNITY_EDITOR [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_GetHMD(ref IntPtr hmdPtr); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_SetEditorPlay(bool isEditorPlay); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_Initialize(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] private static extern void OVR_Destroy(); #if UNITY_STANDALONE_WIN [DllImport("user32", EntryPoint = "MessageBoxA", CharSet = CharSet.Ansi)] public static extern bool MessageBox(int hWnd, [MarshalAs(UnmanagedType.LPStr)]string text, [MarshalAs(UnmanagedType.LPStr)]string caption, uint type); #endif #else [DllImport(LibOVR)] private static extern void OVR_SetInitVariables(IntPtr activity, IntPtr vrActivityClass); [DllImport(LibOVR)] private static extern void OVR_SetEyeParms( int fbWidth, int fbHeight ); [DllImport(LibOVR)] private static extern float OVR_GetBatteryLevel(); [DllImport(LibOVR)] private static extern int OVR_GetBatteryStatus(); [DllImport(LibOVR)] private static extern float OVR_GetBatteryTemperature(); [DllImport(LibOVR)] private static extern int OVR_GetVolume(); [DllImport(LibOVR)] private static extern double OVR_GetTimeSinceLastVolumeChange(); [DllImport(LibOVR)] private static extern bool OVR_GetPlayerEyeHeight(ref float eyeHeight); [DllImport(LibOVR)] private static extern bool OVR_GetInterpupillaryDistance(ref float interpupillaryDistance); #endif }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005DockPaneStrip : DockPaneStripBase { private class TabVS2005 : Tab { public TabVS2005(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 1; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 4; private const int _DocumentButtonGapBottom = 4; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 3; private const int _DocumentTabGapLeft = 3; private const int _DocumentTabGapRight = 3; private const int _DocumentIconGapBottom = 2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 3; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.GrayText; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2005DockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2005 tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; TabVS2005 tab = Tabs[index] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X + rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X + rectTabStrip.Height / 2; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); TabVS2005 tab = Tabs[index] as TabVS2005; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); if (DockPane.DockPanel.ShowDocumentIcon) return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2005 tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2005; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2005, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1, rectTabStrip.Right, rectTabStrip.Bottom - 1); g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { int curveSize = 6; GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); // Draws the full angle piece for active content (or first tab) if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } // Draws the partial angle for non-active content else { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } else { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top); GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90); } else { // Draws the top horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top); // Draws the rounded corner oppposite the angled side GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90); } } if (Tabs.IndexOf(tab) != EndDisplayingTab && (Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent) && !full) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom); } } } else { // Draw the vertical line opposite the angled side if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top); else GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom); } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top); else GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom); } } return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect) { Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); g.DrawPath(PenToolWindowTabBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) { Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop); Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom); g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2)); } Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect) { if (tab.TabWidth == 0) return; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); g.DrawPath(PenDocumentTabActiveBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; if (DockPane.IsActiveDocumentPane) TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat); else TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); g.DrawPath(PenDocumentTabInactiveBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2005 tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; m_closeButtonVisible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected internal override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(Control.MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); if (index != -1) { TabVS2005 tab = Tabs[index] as TabVS2005; if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; } if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security; using System.Text.RegularExpressions; using System.Web; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Configuration; using Microsoft.Xrm.Portal.Cms; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Runtime; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Microsoft.Xrm.Portal.Web { /// <summary> /// A <see cref="SiteMapProvider"/> for navigating portal <see cref="Entity"/> hierarchies. /// </summary> /// <remarks> /// Configuration format. /// <code> /// <![CDATA[ /// <configuration> /// /// <system.web> /// <siteMap enabled="true" defaultProvider="Xrm"> /// <providers> /// <add /// name="Xrm" /// type="Microsoft.Xrm.Portal.Web.CrmSiteMapProvider" /// securityTrimmingEnabled="true" /// portalName="Xrm" [Microsoft.Xrm.Portal.Configuration.PortalContextElement] /// /> /// </providers> /// </siteMap> /// </system.web> /// /// </configuration> /// ]]> /// </code> /// </remarks> /// <seealso cref="PortalContextElement"/> /// <seealso cref="PortalCrmConfigurationManager"/> /// <seealso cref="CrmConfigurationManager"/> public class CrmSiteMapProvider : CrmSiteMapProviderBase { public override SiteMapNode FindSiteMapNode(string rawUrl) { var clientUrl = ExtractClientUrlFromRawUrl(rawUrl); // For the case when we're relying on the redirect-404-to-dummy-Default.aspx trick for // URL routing, normalize this path to '/'. if (clientUrl.Path.Equals("/Default.aspx", StringComparison.OrdinalIgnoreCase)) { clientUrl.Path = "/"; } TraceInfo("FindSiteMapNode({0})", clientUrl.PathWithQueryString); var portal = PortalContext; var context = portal.ServiceContext; var website = portal.Website; // If the URL matches a web page, try to look up that page and return a node. var page = UrlMapping.LookupPageByUrlPath(context, website, clientUrl.Path); if (page != null) { return GetAccessibleNodeOrAccessDeniedNode(context, page); } // If the URL matches a web file, try to look up that file and return a node. var file = UrlMapping.LookupFileByUrlPath(context, website, clientUrl.Path); if (file != null) { return GetAccessibleNodeOrAccessDeniedNode(context, file); } // If there is a pageid Guid on the querystring, try to look up a web page by // that ID and return a node. Guid pageid; if (TryParseGuid(clientUrl.QueryString["pageid"], out pageid)) { var webPagesInCurrentWebsite = website.GetRelatedEntities(context, "adx_website_webpage"); page = webPagesInCurrentWebsite.Where(wp => wp.GetAttributeValue<Guid>("adx_webpageid") == pageid).FirstOrDefault(); if (page != null) { return GetAccessibleNodeOrAccessDeniedNode(context, page); } } // If the above lookups failed, try find a node in any other site map providers. foreach (SiteMapProvider subProvider in SiteMap.Providers) { // Skip this provider if it is the same as this one. if (subProvider.Name == Name) continue; var node = subProvider.FindSiteMapNode(clientUrl.PathWithQueryString); if (node != null) { return node; } } return GetNotFoundNode(); } public override SiteMapNodeCollection GetChildNodes(SiteMapNode node) { TraceInfo("GetChildNodes({0})", node.Key); var children = new List<SiteMapNode>(); var portal = PortalContext; var context = portal.ServiceContext; var website = portal.Website; var page = UrlMapping.LookupPageByUrlPath(context, website, node.Url); // If the node URL is that of a web page... if (page != null) { var childEntities = context.GetChildPages(page).Union(context.GetChildFiles(page)); // Add the (valid) child pages and files of that page to the children we will return. foreach (var entity in childEntities) { var childNode = GetNode(context, entity); if (ChildNodeValidator.Validate(context, childNode)) { children.Add(childNode); } } } // Append values from other site map providers. foreach (SiteMapProvider subProvider in SiteMap.Providers) { // Skip this provider if it is the same as this one. if (subProvider.Name == Name) continue; var subProviderChildNodes = subProvider.GetChildNodes(node); if (subProviderChildNodes == null) continue; foreach (SiteMapNode childNode in subProviderChildNodes) { children.Add(childNode); } } children.Sort(new SiteMapNodeDisplayOrderComparer()); return new SiteMapNodeCollection(children.ToArray()); } public override SiteMapNode GetParentNode(SiteMapNode node) { TraceInfo("GetParentNode({0})", node.Key); var portal = PortalContext; var context = portal.ServiceContext; var website = portal.Website; var page = UrlMapping.LookupPageByUrlPath(context, website, node.Url); if (page == null) { return null; } var parentPage = page.GetRelatedEntity(context, "adx_webpage_webpage", EntityRole.Referencing); if (parentPage == null) { return null; } return GetAccessibleNodeOrAccessDeniedNode(context, parentPage); } protected override SiteMapNode GetRootNodeCore() { TraceInfo("GetRootNodeCore()"); var portal = PortalContext; var context = portal.ServiceContext; var website = portal.Website; var homePage = context.GetPageBySiteMarkerName(website, "Home"); if (homePage == null) { throw new InvalidOperationException(@"Website ""{0}"" must have a web page with the site marker ""Home"".".FormatWith(website.GetAttributeValue<string>("adx_name"))); } return GetAccessibleNodeOrAccessDeniedNode(context, homePage); } protected override CrmSiteMapNode GetNode(OrganizationServiceContext context, Entity entity) { return GetNode(context, entity, HttpStatusCode.OK); } protected CrmSiteMapNode GetNode(OrganizationServiceContext context, Entity entity, HttpStatusCode statusCode) { entity.ThrowOnNull("entity"); var entityName = entity.LogicalName; if (entityName == "adx_webfile") { return GetWebFileNode(context, entity, statusCode); } if (entityName == "adx_webpage") { return GetWebPageNode(context, entity, statusCode); } throw new ArgumentException("Entity {0} ({1}) is not of a type supported by this provider.".FormatWith(entity.Id, entity.GetType().FullName), "entity"); } private CrmSiteMapNode GetWebFileNode(OrganizationServiceContext context, Entity file, HttpStatusCode statusCode) { var contentFormatter = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityContentFormatter>(GetType().FullName) ?? new PassthroughCrmEntityContentFormatter(); var url = context.GetUrl(file); var name = contentFormatter.Format(file.GetAttributeValue<string>("adx_name"), file, this); var summary = contentFormatter.Format(file.GetAttributeValue<string>("adx_summary"), file, this); var fileAttachmentProvider = PortalCrmConfigurationManager.CreateDependencyProvider(PortalName).GetDependency<ICrmEntityFileAttachmentProvider>(); var attachmentInfo = fileAttachmentProvider.GetAttachmentInfo(context, file).FirstOrDefault(); // apply a detached clone of the entity since the SiteMapNode is out of the scope of the current OrganizationServiceContext var fileClone = file.Clone(false); // If there's no file attached to the webfile, return a NotFound node with no rewrite path. if (attachmentInfo == null) { return new CrmSiteMapNode( this, url, url, name, summary, null, file.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow), fileClone, HttpStatusCode.NotFound); } return new CrmSiteMapNode( this, url, url, name, summary, attachmentInfo.Url, attachmentInfo.LastModified.GetValueOrDefault(DateTime.UtcNow), file, statusCode); } private static readonly Regex _notFoundServerRedirectPattern = new Regex(@"404;(?<ClientUrl>.*)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture); private static UrlBuilder ExtractClientUrlFromRawUrl(string rawUrl) { var rawUrlBuilder = new UrlBuilder(rawUrl); var notFoundServerRedirectMatch = _notFoundServerRedirectPattern.Match(rawUrl); if (!notFoundServerRedirectMatch.Success) { return rawUrlBuilder; } var clientUrl = new UrlBuilder(notFoundServerRedirectMatch.Groups["ClientUrl"].Value); if (!string.Equals(rawUrlBuilder.Host, clientUrl.Host, StringComparison.OrdinalIgnoreCase)) { throw new SecurityException(@"rawUrl host ""{0}"" and server internal redirect URL host ""{1}"" do not match.".FormatWith(rawUrlBuilder.Host, clientUrl.Host)); } return clientUrl; } public class SiteMapNodeDisplayOrderComparer : IComparer<SiteMapNode> { public int Compare(SiteMapNode x, SiteMapNode y) { var crmX = x as CrmSiteMapNode; var crmY = y as CrmSiteMapNode; // If neither are CrmSiteMapNodes, they are ordered equally. if (crmX == null && crmY == null) { return 0; } // If x is not a CrmSiteMapNode, and y is, order x after y. if (crmX == null) { return 1; } // If x is a CrmSiteMapNode, and y is not, order x before y. if (crmY == null) { return -1; } int? xDisplayOrder; // Try get a display order value for x. try { xDisplayOrder = crmX.Entity.GetAttributeValue<int?>("adx_displayorder"); } catch { xDisplayOrder = null; } int? yDisplayOrder; // Try get a display order value for y. try { yDisplayOrder = crmY.Entity.GetAttributeValue<int?>("adx_displayorder"); } catch { yDisplayOrder = null; } // If neither has a display order, they are ordered equally. if (!(xDisplayOrder.HasValue || yDisplayOrder.HasValue)) { return 0; } // If x has no display order, and y does, order x after y. if (!xDisplayOrder.HasValue) { return 1; } // If x has a display order, and y does not, order y after x. if (!yDisplayOrder.HasValue) { return -1; } // If both have display orders, order by the comparison of that value. return xDisplayOrder.Value.CompareTo(yDisplayOrder.Value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //--------------------------------------------------------------------------- // // Description: ResourceGenerator class // It generates the localized baml from translations // //--------------------------------------------------------------------------- using System; using System.IO; using System.Windows; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; using System.Reflection; using System.Reflection.Emit; using System.Diagnostics; using System.Resources; using System.Threading; using System.Windows.Threading; using System.Windows.Markup.Localizer; namespace BamlLocalization { /// <summary> /// ResourceGenerator class /// </summary> internal static class ResourceGenerator { /// <summary> /// Generates localized Baml from translations /// </summary> /// <param name="options">LocBaml options</param> /// <param name="dictionaries">the translation dictionaries</param> internal static void Generate(LocBamlOptions options, TranslationDictionariesReader dictionaries) { // base on the input, we generate differently switch(options.InputType) { case FileType.BAML : { // input file name string bamlName = Path.GetFileName(options.Input); // outpuf file name is Output dir + input file name string outputFileName = GetOutputFileName(options); // construct the full path string fullPathOutput = Path.Combine(options.Output, outputFileName); options.Write(StringLoader.Get("GenerateBaml", fullPathOutput)); using (Stream input = File.OpenRead(options.Input)) { using (Stream output = new FileStream(fullPathOutput, FileMode.Create)) { BamlLocalizationDictionary dictionary = dictionaries[bamlName]; // if it is null, just create an empty dictionary. if (dictionary == null) dictionary = new BamlLocalizationDictionary(); GenerateBamlStream(input, output, dictionary, options); } } options.WriteLine(StringLoader.Get("Done")); break; } case FileType.RESOURCES : { string outputFileName = GetOutputFileName(options); string fullPathOutput = Path.Combine(options.Output, outputFileName); using (Stream input = File.OpenRead(options.Input)) { using (Stream output = File.OpenWrite(fullPathOutput)) { // create a Resource reader on the input; IResourceReader reader = new ResourceReader(input); // create a writer on the output; IResourceWriter writer = new ResourceWriter(output); GenerateResourceStream( options, // options options.Input, // resources name reader, // resource reader writer, // resource writer dictionaries); // translations reader.Close(); // now generate and close writer.Generate(); writer.Close(); } } options.WriteLine(StringLoader.Get("DoneGeneratingResource", outputFileName)); break; } case FileType.EXE: case FileType.DLL: { GenerateAssembly(options, dictionaries); break; } default: { Debug.Assert(false, "Can't generate to this type"); break; } } } private static void GenerateBamlStream(Stream input, Stream output, BamlLocalizationDictionary dictionary, LocBamlOptions options) { string commentFile = Path.ChangeExtension(options.Input, "loc"); TextReader commentStream = null; try { if (File.Exists(commentFile)) { commentStream = new StreamReader(commentFile); } // create a localizabilty resolver based on reflection BamlLocalizabilityByReflection localizabilityReflector = new BamlLocalizabilityByReflection(options.Assemblies); // create baml localizer BamlLocalizer mgr = new BamlLocalizer( input, localizabilityReflector, commentStream ); // get the resources BamlLocalizationDictionary source = mgr.ExtractResources(); BamlLocalizationDictionary translations = new BamlLocalizationDictionary(); foreach (DictionaryEntry entry in dictionary) { BamlLocalizableResourceKey key = (BamlLocalizableResourceKey) entry.Key; // filter out unchanged items if (!source.Contains(key) || entry.Value == null || source[key].Content != ((BamlLocalizableResource)entry.Value).Content) { translations.Add(key, (BamlLocalizableResource)entry.Value); } } // update baml mgr.UpdateBaml(output, translations); } finally { if (commentStream != null) { commentStream.Close(); } } } private static void GenerateResourceStream( LocBamlOptions options, // options from the command line string resourceName, // the name of the .resources file IResourceReader reader, // the reader for the .resources IResourceWriter writer, // the writer for the output .resources TranslationDictionariesReader dictionaries // the translations ) { options.WriteLine(StringLoader.Get("GenerateResource", resourceName)); // enumerate through each resource and generate it foreach(DictionaryEntry entry in reader) { string name = entry.Key as string; object resourceValue = null; // See if it looks like a Baml resource if (BamlStream.IsResourceEntryBamlStream(name, entry.Value)) { Stream targetStream = null; options.Write(" "); options.Write(StringLoader.Get("GenerateBaml", name)); // grab the localizations available for this Baml string bamlName = BamlStream.CombineBamlStreamName(resourceName, name); BamlLocalizationDictionary localizations = dictionaries[bamlName]; if (localizations != null) { targetStream = new MemoryStream(); // generate into a new Baml stream GenerateBamlStream( (Stream) entry.Value, targetStream, localizations, options ); } options.WriteLine(StringLoader.Get("Done")); // sets the generated object to be the generated baml stream resourceValue = targetStream; } if (resourceValue == null) { // // The stream is not localized as Baml yet, so we will make a copy of this item into // the localized resources // // We will add the value as is if it is serializable. Otherwise, make a copy resourceValue = entry.Value; object[] serializableAttributes = resourceValue.GetType().GetCustomAttributes(typeof(SerializableAttribute), true); if (serializableAttributes.Length == 0) { // The item returned from resource reader is not serializable // If it is Stream, we can wrap all the values in a MemoryStream and // add to the resource. Otherwise, we had to skip this resource. Stream resourceStream = resourceValue as Stream; if (resourceStream != null) { Stream targetStream = new MemoryStream(); byte[] buffer = new byte[resourceStream.Length]; resourceStream.Read(buffer, 0, buffer.Length); targetStream = new MemoryStream(buffer); resourceValue = targetStream; } } } if (resourceValue != null) { writer.AddResource(name, resourceValue); } } } private static void GenerateStandaloneResource(string fullPathName, Stream resourceStream) { // simply do a copy for the stream using (FileStream file = new FileStream(fullPathName, FileMode.Create, FileAccess.Write)) { const int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = 1; while (bytesRead > 0) { bytesRead = resourceStream.Read(buffer, 0, BUFFER_SIZE); file.Write(buffer, 0, bytesRead); } } } //-------------------------------------------------- // The function follows Managed code parser // implementation. in the future, maybe they should // share the same code //-------------------------------------------------- private static void GenerateAssembly(LocBamlOptions options, TranslationDictionariesReader dictionaries) { // there are many names to be used when generating an assembly string sourceAssemblyFullName = options.Input; // source assembly full path string outputAssemblyDir = options.Output; // output assembly directory string outputAssemblyLocalName = GetOutputFileName(options); // output assembly name string moduleLocalName = GetAssemblyModuleLocalName(options, outputAssemblyLocalName); // the module name within the assmbly // get the source assembly Assembly srcAsm = Assembly.LoadFrom(sourceAssemblyFullName); // obtain the assembly name AssemblyName targetAssemblyNameObj = srcAsm.GetName(); // store the culture info of the source assembly CultureInfo srcCultureInfo = targetAssemblyNameObj.CultureInfo; // update it to use it for target assembly targetAssemblyNameObj.Name = Path.GetFileNameWithoutExtension(outputAssemblyLocalName); targetAssemblyNameObj.CultureInfo = options.CultureInfo; // we get a assembly builder AssemblyBuilder targetAssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly( targetAssemblyNameObj, // name of the assembly AssemblyBuilderAccess.RunAndSave, // access rights outputAssemblyDir // storage dir ); // we create a module builder for embeded resource modules ModuleBuilder moduleBuilder = targetAssemblyBuilder.DefineDynamicModule( moduleLocalName, outputAssemblyLocalName ); options.WriteLine(StringLoader.Get("GenerateAssembly")); // now for each resource in the assembly foreach (string resourceName in srcAsm.GetManifestResourceNames()) { // get the resource location for the resource ResourceLocation resourceLocation = srcAsm.GetManifestResourceInfo(resourceName).ResourceLocation; // if this resource is in another assemlby, we will skip it if ((resourceLocation & ResourceLocation.ContainedInAnotherAssembly) != 0) { continue; // in resource assembly, we don't have resource that is contained in another assembly } // gets the neutral resource name, giving it the source culture info string neutralResourceName = GetNeutralResModuleName(resourceName, srcCultureInfo); // gets the target resource name, by giving it the target culture info string targetResourceName = GetCultureSpecificResourceName(neutralResourceName, options.CultureInfo); // resource stream Stream resourceStream = srcAsm.GetManifestResourceStream(resourceName); // see if it is a .resources if (neutralResourceName.ToLower(CultureInfo.InvariantCulture).EndsWith(".resources")) { // now we think we have resource stream // get the resource writer IResourceWriter writer; // check if it is a embeded assembly if ((resourceLocation & ResourceLocation.Embedded) != 0) { // gets the resource writer from the module builder writer = moduleBuilder.DefineResource( targetResourceName, // resource name targetResourceName, // resource description ResourceAttributes.Public // visibilty of this resource to other assembly ); } else { // it is a standalone resource, we get the resource writer from the assembly builder writer = targetAssemblyBuilder.DefineResource( targetResourceName, // resource name targetResourceName, // description targetResourceName, // file name to save to ResourceAttributes.Public // visibility of this resource to other assembly ); } // get the resource reader IResourceReader reader = new ResourceReader(resourceStream); // generate the resources GenerateResourceStream(options, resourceName, reader, writer, dictionaries); // we don't call writer.Generate() or writer.Close() here // because the AssemblyBuilder will call them when we call Save() on it. } else { // else it is a stand alone untyped manifest resources. string extension = Path.GetExtension(targetResourceName); string fullFileName = Path.Combine(outputAssemblyDir, targetResourceName); // check if it is a .baml, case-insensitive if (string.Compare(extension, ".baml", true, CultureInfo.InvariantCulture) == 0) { // try to localized the the baml // find the resource dictionary BamlLocalizationDictionary dictionary = dictionaries[resourceName]; // if it is null, just create an empty dictionary. if (dictionary != null) { // it is a baml stream using (Stream output = File.OpenWrite(fullFileName)) { options.Write(" "); options.WriteLine(StringLoader.Get("GenerateStandaloneBaml", fullFileName)); GenerateBamlStream(resourceStream, output, dictionary, options); options.WriteLine(StringLoader.Get("Done")); } } else { // can't find localization of it, just copy it GenerateStandaloneResource( fullFileName, resourceStream); } } else { // it is an untyped resource stream, just copy it GenerateStandaloneResource( fullFileName, resourceStream); } // now add this resource file into the assembly targetAssemblyBuilder.AddResourceFile( targetResourceName, // resource name targetResourceName, // file name ResourceAttributes.Public // visibility of the resource to other assembly ); } } // at the end, generate the assembly targetAssemblyBuilder.Save(outputAssemblyLocalName); options.WriteLine(StringLoader.Get("DoneGeneratingAssembly")); } //----------------------------------------- // private function dealing with naming //----------------------------------------- // return the local output file name, i.e. without directory private static string GetOutputFileName(LocBamlOptions options) { string outputFileName; string inputFileName = Path.GetFileName(options.Input); switch(options.InputType) { case FileType.BAML: { return inputFileName; } case FileType.EXE: { inputFileName = inputFileName.Remove(inputFileName.LastIndexOf('.')) + ".resources.dll"; return inputFileName; } case FileType.DLL : { return inputFileName; } case FileType.RESOURCES : { // get the output file name outputFileName = inputFileName; // get to the last dot seperating filename and extension int lastDot = outputFileName.LastIndexOf('.'); int secondLastDot = outputFileName.LastIndexOf('.', lastDot - 1); if (secondLastDot > 0) { string cultureName = outputFileName.Substring(secondLastDot + 1, lastDot - secondLastDot - 1); if (LocBamlConst.IsValidCultureName(cultureName)) { string extension = outputFileName.Substring(lastDot); string frontPart = outputFileName.Substring(0, secondLastDot + 1); outputFileName = frontPart + options.CultureInfo.Name + extension; } } return outputFileName; } default : { throw new NotSupportedException(); } } } private static string GetAssemblyModuleLocalName(LocBamlOptions options, string targetAssemblyName) { string moduleName; if (targetAssemblyName.ToLower(CultureInfo.InvariantCulture).EndsWith(".resources.dll")) { // we create the satellite assembly name moduleName = string.Format( CultureInfo.InvariantCulture, "{0}.{1}.{2}", targetAssemblyName.Substring(0, targetAssemblyName.Length - ".resources.dll".Length), options.CultureInfo.Name, "resources.dll" ); } else { moduleName = targetAssemblyName; } return moduleName; } // return the neutral resource name private static string GetNeutralResModuleName(string resourceName, CultureInfo cultureInfo) { if (cultureInfo.Equals(CultureInfo.InvariantCulture)) { return resourceName; } else { // if it is an satellite assembly, we need to strip out the culture name string normalizedName = resourceName.ToLower(CultureInfo.InvariantCulture); int end = normalizedName.LastIndexOf(".resources"); if (end < 0) { return resourceName; } int start = normalizedName.LastIndexOf('.', end - 1); if (start > 0 && end - start > 0) { string cultureStr = resourceName.Substring( start + 1, end - start - 1); if (string.Compare(cultureStr, cultureInfo.Name, true) == 0) { // it has the correct culture name, so we can take it out return resourceName.Remove(start, end - start); } } return resourceName; } } private static string GetCultureSpecificResourceName(string neutralResourceName, CultureInfo culture) { // gets the extension string extension = Path.GetExtension(neutralResourceName); // swap in culture name string cultureName = Path.ChangeExtension(neutralResourceName, culture.Name); // return the new name with the same extension return cultureName + extension; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Grid.Framework; namespace OpenSim.Grid.UserServer.Modules { public delegate void logOffUser(UUID AgentID); public class UserManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event logOffUser OnLogOffUser; private logOffUser handlerLogOffUser; private UserDataBaseService m_userDataBaseService; private BaseHttpServer m_httpServer; /// <summary> /// /// </summary> /// <param name="userDataBaseService"></param> public UserManager(UserDataBaseService userDataBaseService) { m_userDataBaseService = userDataBaseService; } public void Initialise(IGridServiceCore core) { } public void PostInitialise() { } private string RESTGetUserProfile(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { UUID id; UserProfileData userProfile; try { id = new UUID(param); } catch (Exception) { httpResponse.StatusCode = 500; return "Malformed Param [" + param + "]"; } userProfile = m_userDataBaseService.GetUserProfile(id); if (userProfile == null) { httpResponse.StatusCode = 404; return "Not Found."; } return ProfileToXmlRPCResponse(userProfile).ToString(); } public void RegisterHandlers(BaseHttpServer httpServer) { m_httpServer = httpServer; m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/users/", RESTGetUserProfile)); m_httpServer.AddXmlRPCHandler("get_user_by_name", XmlRPCGetUserMethodName); m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); // Used by IAR module to do password checks m_httpServer.AddXmlRPCHandler("authenticate_user_by_password", XmlRPCAuthenticateUserMethodPassword); m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); m_httpServer.AddXmlRPCHandler("update_user_profile", XmlRpcResponseXmlRPCUpdateUserProfile); m_httpServer.AddStreamHandler(new RestStreamHandler("DELETE", "/usersessions/", RestDeleteUserSessionMethod)); } /// <summary> /// Deletes an active agent session /// </summary> /// <param name="request">The request</param> /// <param name="path">The path (eg /bork/narf/test)</param> /// <param name="param">Parameters sent</param> /// <param name="httpRequest">HTTP request header object</param> /// <param name="httpResponse">HTTP response header object</param> /// <returns>Success "OK" else error</returns> public string RestDeleteUserSessionMethod(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { // TODO! Important! return "OK"; } public XmlRpcResponse AvatarPickerListtoXmlRPCResponse(UUID queryID, List<AvatarPickerAvatar> returnUsers) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); // Query Result Information responseData["queryid"] = queryID.ToString(); responseData["avcount"] = returnUsers.Count.ToString(); for (int i = 0; i < returnUsers.Count; i++) { responseData["avatarid" + i] = returnUsers[i].AvatarID.ToString(); responseData["firstname" + i] = returnUsers[i].firstName; responseData["lastname" + i] = returnUsers[i].lastName; } response.Value = responseData; return response; } /// <summary> /// Converts a user profile to an XML element which can be returned /// </summary> /// <param name="profile">The user profile</param> /// <returns>A string containing an XML Document of the user profile</returns> public XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); // Account information responseData["firstname"] = profile.FirstName; responseData["lastname"] = profile.SurName; responseData["email"] = profile.Email; responseData["uuid"] = profile.ID.ToString(); // Server Information responseData["server_inventory"] = profile.UserInventoryURI; responseData["server_asset"] = profile.UserAssetURI; // Profile Information responseData["profile_about"] = profile.AboutText; responseData["profile_firstlife_about"] = profile.FirstLifeAboutText; responseData["profile_firstlife_image"] = profile.FirstLifeImage.ToString(); responseData["profile_can_do"] = profile.CanDoMask.ToString(); responseData["profile_want_do"] = profile.WantDoMask.ToString(); responseData["profile_image"] = profile.Image.ToString(); responseData["profile_created"] = profile.Created.ToString(); responseData["profile_lastlogin"] = profile.LastLogin.ToString(); // Home region information responseData["home_coordinates_x"] = profile.HomeLocation.X.ToString(); responseData["home_coordinates_y"] = profile.HomeLocation.Y.ToString(); responseData["home_coordinates_z"] = profile.HomeLocation.Z.ToString(); responseData["home_region"] = profile.HomeRegion.ToString(); responseData["home_region_id"] = profile.HomeRegionID.ToString(); responseData["home_look_x"] = profile.HomeLookAt.X.ToString(); responseData["home_look_y"] = profile.HomeLookAt.Y.ToString(); responseData["home_look_z"] = profile.HomeLookAt.Z.ToString(); responseData["user_flags"] = profile.UserFlags.ToString(); responseData["god_level"] = profile.GodLevel.ToString(); responseData["custom_type"] = profile.CustomType; responseData["partner"] = profile.Partner.ToString(); response.Value = responseData; return response; } #region XMLRPC User Methods /// <summary> /// Authenticate a user using their password /// </summary> /// <param name="request">Must contain values for "user_uuid" and "password" keys</param> /// <param name="remoteClient"></param> /// <returns></returns> public XmlRpcResponse XmlRPCAuthenticateUserMethodPassword(XmlRpcRequest request, IPEndPoint remoteClient) { // m_log.DebugFormat("[USER MANAGER]: Received authenticated user by password request from {0}", remoteClient); Hashtable requestData = (Hashtable)request.Params[0]; string userUuidRaw = (string)requestData["user_uuid"]; string password = (string)requestData["password"]; if (null == userUuidRaw) return Util.CreateUnknownUserErrorResponse(); UUID userUuid; if (!UUID.TryParse(userUuidRaw, out userUuid)) return Util.CreateUnknownUserErrorResponse(); UserProfileData userProfile = m_userDataBaseService.GetUserProfile(userUuid); if (null == userProfile) return Util.CreateUnknownUserErrorResponse(); string authed; if (null == password) { authed = "FALSE"; } else { if (m_userDataBaseService.AuthenticateUserByPassword(userUuid, password)) authed = "TRUE"; else authed = "FALSE"; } // m_log.DebugFormat( // "[USER MANAGER]: Authentication by password result from {0} for {1} is {2}", // remoteClient, userUuid, authed); XmlRpcResponse response = new XmlRpcResponse(); Hashtable responseData = new Hashtable(); responseData["auth_user"] = authed; response.Value = responseData; return response; } public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request, IPEndPoint remoteClient) { // XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; List<AvatarPickerAvatar> returnAvatar = new List<AvatarPickerAvatar>(); UUID queryID = new UUID(UUID.Zero.ToString()); if (requestData.Contains("avquery") && requestData.Contains("queryid")) { queryID = new UUID((string)requestData["queryid"]); returnAvatar = m_userDataBaseService.GenerateAgentPickerRequestResponse(queryID, (string)requestData["avquery"]); } m_log.InfoFormat("[AVATARINFO]: Servicing Avatar Query: " + (string)requestData["avquery"]); return AvatarPickerListtoXmlRPCResponse(queryID, returnAvatar); } public XmlRpcResponse XmlRPCAtRegion(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; Hashtable responseData = new Hashtable(); string returnstring = "FALSE"; if (requestData.Contains("avatar_id") && requestData.Contains("region_handle") && requestData.Contains("region_uuid")) { // ulong cregionhandle = 0; UUID regionUUID; UUID avatarUUID; UUID.TryParse((string)requestData["avatar_id"], out avatarUUID); UUID.TryParse((string)requestData["region_uuid"], out regionUUID); if (avatarUUID != UUID.Zero) { UserProfileData userProfile = m_userDataBaseService.GetUserProfile(avatarUUID); userProfile.CurrentAgent.Region = regionUUID; userProfile.CurrentAgent.Handle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); //userProfile.CurrentAgent. m_userDataBaseService.CommitAgent(ref userProfile); //setUserProfile(userProfile); returnstring = "TRUE"; } } responseData.Add("returnString", returnstring); response.Value = responseData; return response; } public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request, IPEndPoint remoteClient) { // XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; if (requestData.Contains("avatar_name")) { string query = (string)requestData["avatar_name"]; if (null == query) return Util.CreateUnknownUserErrorResponse(); // Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); string[] querysplit = query.Split(' '); if (querysplit.Length == 2) { userProfile = m_userDataBaseService.GetUserProfile(querysplit[0], querysplit[1]); if (userProfile == null) { return Util.CreateUnknownUserErrorResponse(); } } else { return Util.CreateUnknownUserErrorResponse(); } } else { return Util.CreateUnknownUserErrorResponse(); } return ProfileToXmlRPCResponse(userProfile); } public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request, IPEndPoint remoteClient) { // XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; //CFK: this clogs the UserServer log and is not necessary at this time. //CFK: m_log.Debug("METHOD BY UUID CALLED"); if (requestData.Contains("avatar_uuid")) { try { UUID guess = new UUID((string)requestData["avatar_uuid"]); userProfile = m_userDataBaseService.GetUserProfile(guess); } catch (FormatException) { return Util.CreateUnknownUserErrorResponse(); } if (userProfile == null) { return Util.CreateUnknownUserErrorResponse(); } } else { return Util.CreateUnknownUserErrorResponse(); } return ProfileToXmlRPCResponse(userProfile); } public XmlRpcResponse XmlRPCGetAgentMethodUUID(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; UserProfileData userProfile; //CFK: this clogs the UserServer log and is not necessary at this time. //CFK: m_log.Debug("METHOD BY UUID CALLED"); if (requestData.Contains("avatar_uuid")) { UUID guess; UUID.TryParse((string)requestData["avatar_uuid"], out guess); if (guess == UUID.Zero) { return Util.CreateUnknownUserErrorResponse(); } userProfile = m_userDataBaseService.GetUserProfile(guess); if (userProfile == null) { return Util.CreateUnknownUserErrorResponse(); } // no agent??? if (userProfile.CurrentAgent == null) { return Util.CreateUnknownUserErrorResponse(); } Hashtable responseData = new Hashtable(); responseData["handle"] = userProfile.CurrentAgent.Handle.ToString(); responseData["session"] = userProfile.CurrentAgent.SessionID.ToString(); if (userProfile.CurrentAgent.AgentOnline) responseData["agent_online"] = "TRUE"; else responseData["agent_online"] = "FALSE"; response.Value = responseData; } else { return Util.CreateUnknownUserErrorResponse(); } return response; } public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request, IPEndPoint remoteClient) { m_log.Debug("[UserManager]: Got request to update user profile"); XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; Hashtable responseData = new Hashtable(); if (!requestData.Contains("avatar_uuid")) { return Util.CreateUnknownUserErrorResponse(); } UUID UserUUID = new UUID((string)requestData["avatar_uuid"]); UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID); if (null == userProfile) { return Util.CreateUnknownUserErrorResponse(); } // don't know how yet. if (requestData.Contains("AllowPublish")) { } if (requestData.Contains("FLImageID")) { userProfile.FirstLifeImage = new UUID((string)requestData["FLImageID"]); } if (requestData.Contains("ImageID")) { userProfile.Image = new UUID((string)requestData["ImageID"]); } // dont' know how yet if (requestData.Contains("MaturePublish")) { } if (requestData.Contains("AboutText")) { userProfile.AboutText = (string)requestData["AboutText"]; } if (requestData.Contains("FLAboutText")) { userProfile.FirstLifeAboutText = (string)requestData["FLAboutText"]; } // not in DB yet. if (requestData.Contains("ProfileURL")) { } if (requestData.Contains("home_region")) { try { userProfile.HomeRegion = Convert.ToUInt64((string)requestData["home_region"]); } catch (ArgumentException) { m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument"); } catch (FormatException) { m_log.Error("[PROFILE]:Failed to set home region, Invalid Format"); } catch (OverflowException) { m_log.Error("[PROFILE]:Failed to set home region, Value was too large"); } } if (requestData.Contains("home_region_id")) { UUID regionID; UUID.TryParse((string)requestData["home_region_id"], out regionID); userProfile.HomeRegionID = regionID; } if (requestData.Contains("home_pos_x")) { try { userProfile.HomeLocationX = (float)Convert.ToDecimal((string)requestData["home_pos_x"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home postion x"); } } if (requestData.Contains("home_pos_y")) { try { userProfile.HomeLocationY = (float)Convert.ToDecimal((string)requestData["home_pos_y"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home postion y"); } } if (requestData.Contains("home_pos_z")) { try { userProfile.HomeLocationZ = (float)Convert.ToDecimal((string)requestData["home_pos_z"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home postion z"); } } if (requestData.Contains("home_look_x")) { try { userProfile.HomeLookAtX = (float)Convert.ToDecimal((string)requestData["home_look_x"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home lookat x"); } } if (requestData.Contains("home_look_y")) { try { userProfile.HomeLookAtY = (float)Convert.ToDecimal((string)requestData["home_look_y"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home lookat y"); } } if (requestData.Contains("home_look_z")) { try { userProfile.HomeLookAtZ = (float)Convert.ToDecimal((string)requestData["home_look_z"], Culture.NumberFormatInfo); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set home lookat z"); } } if (requestData.Contains("user_flags")) { try { userProfile.UserFlags = Convert.ToInt32((string)requestData["user_flags"]); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set user flags"); } } if (requestData.Contains("god_level")) { try { userProfile.GodLevel = Convert.ToInt32((string)requestData["god_level"]); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set god level"); } } if (requestData.Contains("custom_type")) { try { userProfile.CustomType = (string)requestData["custom_type"]; } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set custom type"); } } if (requestData.Contains("partner")) { try { userProfile.Partner = new UUID((string)requestData["partner"]); } catch (InvalidCastException) { m_log.Error("[PROFILE]:Failed to set partner"); } } else { userProfile.Partner = UUID.Zero; } // call plugin! bool ret = m_userDataBaseService.UpdateUserProfile(userProfile); responseData["returnString"] = ret.ToString(); response.Value = responseData; return response; } public XmlRpcResponse XmlRPCLogOffUserMethodUUID(XmlRpcRequest request, IPEndPoint remoteClient) { XmlRpcResponse response = new XmlRpcResponse(); Hashtable requestData = (Hashtable)request.Params[0]; if (requestData.Contains("avatar_uuid")) { try { UUID userUUID = new UUID((string)requestData["avatar_uuid"]); UUID RegionID = new UUID((string)requestData["region_uuid"]); ulong regionhandle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); Vector3 position = new Vector3( (float)Convert.ToDecimal(((string)requestData["region_pos_x"]).Replace(',','.'), Culture.NumberFormatInfo), (float)Convert.ToDecimal(((string)requestData["region_pos_y"]).Replace(',','.'), Culture.NumberFormatInfo), (float)Convert.ToDecimal(((string)requestData["region_pos_z"]).Replace(',','.'), Culture.NumberFormatInfo)); Vector3 lookat = new Vector3( (float)Convert.ToDecimal((string)requestData["lookat_x"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)requestData["lookat_y"], Culture.NumberFormatInfo), (float)Convert.ToDecimal((string)requestData["lookat_z"], Culture.NumberFormatInfo)); handlerLogOffUser = OnLogOffUser; if (handlerLogOffUser != null) handlerLogOffUser(userUUID); m_userDataBaseService.LogOffUser(userUUID, RegionID, regionhandle, position, lookat); } catch (FormatException) { m_log.Warn("[LOGOUT]: Error in Logout XMLRPC Params"); return response; } } else { return Util.CreateUnknownUserErrorResponse(); } return response; } #endregion public void HandleAgentLocation(UUID agentID, UUID regionID, ulong regionHandle) { UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); if (userProfile != null) { userProfile.CurrentAgent.Region = regionID; userProfile.CurrentAgent.Handle = regionHandle; m_userDataBaseService.CommitAgent(ref userProfile); } } public void HandleAgentLeaving(UUID agentID, UUID regionID, ulong regionHandle) { UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); if (userProfile != null) { if (userProfile.CurrentAgent.Region == regionID) { UserAgentData userAgent = userProfile.CurrentAgent; if (userAgent != null && userAgent.AgentOnline) { userAgent.AgentOnline = false; userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); if (regionID != UUID.Zero) { userAgent.Region = regionID; } userAgent.Handle = regionHandle; userProfile.LastLogin = userAgent.LogoutTime; m_userDataBaseService.CommitAgent(ref userProfile); handlerLogOffUser = OnLogOffUser; if (handlerLogOffUser != null) handlerLogOffUser(agentID); } } } } public void HandleRegionStartup(UUID regionID) { m_userDataBaseService.LogoutUsers(regionID); } public void HandleRegionShutdown(UUID regionID) { m_userDataBaseService.LogoutUsers(regionID); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Kyivsoft.GetBalance.Web.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * InformationMachineAPI.PCL * * */ using System; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using InformationMachineAPI.PCL; using InformationMachineAPI.PCL.Http.Request; using InformationMachineAPI.PCL.Http.Response; using InformationMachineAPI.PCL.Http.Client; using InformationMachineAPI.PCL.Exceptions; using InformationMachineAPI.PCL.Models; namespace InformationMachineAPI.PCL.Controllers { public partial class UserScansController: BaseController { #region Singleton Pattern //private static variables for the singleton pattern private static object syncObject = new object(); private static UserScansController instance = null; /// <summary> /// Singleton pattern implementation /// </summary> internal static UserScansController Instance { get { lock (syncObject) { if (null == instance) { instance = new UserScansController(); } } return instance; } } #endregion Singleton Pattern /// <summary> /// Upload a new product by barcode /// </summary> /// <param name="payload">Required parameter: POST payload example: { "bar_code" : "021130126026", "bar_code_type" : "UPC-A" }</param> /// <param name="userId">Required parameter: ID of user in your system</param> /// <return>Returns the UploadBarcodeWrapper response from the API call</return> public UploadBarcodeWrapper UserScansUploadBarcode(UploadBarcodeRequest payload, string userId) { Task<UploadBarcodeWrapper> t = UserScansUploadBarcodeAsync(payload, userId); Task.WaitAll(t); return t.Result; } /// <summary> /// Upload a new product by barcode /// </summary> /// <param name="payload">Required parameter: POST payload example: { "bar_code" : "021130126026", "bar_code_type" : "UPC-A" }</param> /// <param name="userId">Required parameter: ID of user in your system</param> /// <return>Returns the UploadBarcodeWrapper response from the API call</return> public async Task<UploadBarcodeWrapper> UserScansUploadBarcodeAsync(UploadBarcodeRequest payload, string userId) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/v1/users/{user_id}/barcode"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>() { { "user_id", userId } }); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>() { { "client_id", Configuration.ClientId }, { "client_secret", Configuration.ClientSecret } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "" }, { "accept", "application/json" }, { "content-type", "application/json; charset=utf-8" } }; //append body params var _body = APIHelper.JsonSerialize(payload); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.PostBody(_queryUrl, _headers, _body); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //Error handling using HTTP status codes if (_response.StatusCode == 400) throw new APIException(@"Bad request", _context); else if (_response.StatusCode == 401) throw new APIException(@"Unauthorized", _context); else if (_response.StatusCode == 500) throw new APIException(@"Internal Server Error", _context); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<UploadBarcodeWrapper>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } /// <summary> /// Get status of uploaded receipt /// </summary> /// <param name="userId">Required parameter: Example: </param> /// <param name="receiptId">Required parameter: Example: </param> /// <return>Returns the UploadReceiptStatusWrapper response from the API call</return> public UploadReceiptStatusWrapper UserScansGetReceiptStatus(string userId, string receiptId) { Task<UploadReceiptStatusWrapper> t = UserScansGetReceiptStatusAsync(userId, receiptId); Task.WaitAll(t); return t.Result; } /// <summary> /// Get status of uploaded receipt /// </summary> /// <param name="userId">Required parameter: Example: </param> /// <param name="receiptId">Required parameter: Example: </param> /// <return>Returns the UploadReceiptStatusWrapper response from the API call</return> public async Task<UploadReceiptStatusWrapper> UserScansGetReceiptStatusAsync(string userId, string receiptId) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/v1/users/{user_id}/receipt/{receipt_id}"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>() { { "user_id", userId }, { "receipt_id", receiptId } }); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>() { { "client_id", Configuration.ClientId }, { "client_secret", Configuration.ClientSecret } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "" }, { "accept", "application/json" } }; //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl,_headers); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //Error handling using HTTP status codes if (_response.StatusCode == 400) throw new APIException(@"Bad request", _context); else if (_response.StatusCode == 401) throw new APIException(@"Unauthorized", _context); else if (_response.StatusCode == 500) throw new APIException(@"Internal Server Error", _context); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<UploadReceiptStatusWrapper>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } /// <summary> /// Upload new product(s) by receipt /// </summary> /// <param name="payload">Required parameter: Example: </param> /// <param name="userId">Required parameter: Example: </param> /// <return>Returns the UploadReceiptWrapper response from the API call</return> public UploadReceiptWrapper UserScansUploadReceipt(UploadReceiptRequest payload, string userId) { Task<UploadReceiptWrapper> t = UserScansUploadReceiptAsync(payload, userId); Task.WaitAll(t); return t.Result; } /// <summary> /// Upload new product(s) by receipt /// </summary> /// <param name="payload">Required parameter: Example: </param> /// <param name="userId">Required parameter: Example: </param> /// <return>Returns the UploadReceiptWrapper response from the API call</return> public async Task<UploadReceiptWrapper> UserScansUploadReceiptAsync(UploadReceiptRequest payload, string userId) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/v1/users/{user_id}/receipt"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>() { { "user_id", userId } }); //process optional query parameters APIHelper.AppendUrlWithQueryParameters(_queryBuilder, new Dictionary<string, object>() { { "client_id", Configuration.ClientId }, { "client_secret", Configuration.ClientSecret } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "" }, { "accept", "application/json" }, { "content-type", "application/json; charset=utf-8" } }; //append body params var _body = APIHelper.JsonSerialize(payload); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.PostBody(_queryUrl, _headers, _body); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //Error handling using HTTP status codes if (_response.StatusCode == 400) throw new APIException(@"Bad request", _context); else if (_response.StatusCode == 401) throw new APIException(@"Unauthorized", _context); else if (_response.StatusCode == 422) throw new APIException(@"Unprocessable Entity", _context); else if (_response.StatusCode == 500) throw new APIException(@"Internal Server Error", _context); //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<UploadReceiptWrapper>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.Dns.Client { #region usings using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Text; #endregion /// <summary> /// Dns client. /// </summary> /// <example> /// <code> /// // Set dns servers /// Dns_Client.DnsServers = new string[]{"194.126.115.18"}; /// /// Dns_Client dns = Dns_Client(); /// /// // Get MX records. /// DnsServerResponse resp = dns.Query("lumisoft.ee",QTYPE.MX); /// if(resp.ConnectionOk &amp;&amp; resp.ResponseCode == RCODE.NO_ERROR){ /// MX_Record[] mxRecords = resp.GetMXRecords(); /// /// // Do your stuff /// } /// else{ /// // Handle error there, for more exact error info see RCODE /// } /// /// </code> /// </example> public class Dns_Client { #region Members private static IPAddress[] m_DnsServers; private static int m_ID = 100; private static bool m_UseDnsCache = true; #endregion #region Constructor /// <summary> /// Static constructor. /// </summary> static Dns_Client() { // Try to get system dns servers try { List<IPAddress> dnsServers = new List<IPAddress>(); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if (nic.OperationalStatus == OperationalStatus.Up) { foreach (IPAddress ip in nic.GetIPProperties().DnsAddresses) { if (ip.AddressFamily == AddressFamily.InterNetwork) { if (!dnsServers.Contains(ip)) { dnsServers.Add(ip); } } } } } m_DnsServers = dnsServers.ToArray(); } catch {} } #endregion #region Properties /// <summary> /// Gets or sets dns servers. /// </summary> /// <exception cref="ArgumentNullException">Is raised when null value is passed.</exception> public static string[] DnsServers { get { string[] retVal = new string[m_DnsServers.Length]; for (int i = 0; i < m_DnsServers.Length; i++) { retVal[i] = m_DnsServers[i].ToString(); } return retVal; } set { if (value == null) { throw new ArgumentNullException(); } IPAddress[] retVal = new IPAddress[value.Length]; for (int i = 0; i < value.Length; i++) { retVal[i] = IPAddress.Parse(value[i]); } m_DnsServers = retVal; } } /// <summary> /// Gets or sets if to use dns caching. /// </summary> public static bool UseDnsCache { get { return m_UseDnsCache; } set { m_UseDnsCache = value; } } /// <summary> /// Get next query ID. /// </summary> internal static int ID { get { if (m_ID >= 65535) { m_ID = 100; } return m_ID++; } } #endregion #region Methods /// <summary> /// Resolves host names to IP addresses. /// </summary> /// <param name="hosts">Host names to resolve.</param> /// <returns>Returns specified hosts IP addresses.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>hosts</b> is null.</exception> public static IPAddress[] Resolve(string[] hosts) { if (hosts == null) { throw new ArgumentNullException("hosts"); } List<IPAddress> retVal = new List<IPAddress>(); foreach (string host in hosts) { IPAddress[] addresses = Resolve(host); foreach (IPAddress ip in addresses) { if (!retVal.Contains(ip)) { retVal.Add(ip); } } } return retVal.ToArray(); } /// <summary> /// Resolves host name to IP addresses. /// </summary> /// <param name="host">Host name or IP address.</param> /// <returns>Return specified host IP addresses.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null.</exception> public static IPAddress[] Resolve(string host) { if (host == null) { throw new ArgumentNullException("host"); } // If hostName_IP is IP try { return new[] {IPAddress.Parse(host)}; } catch {} // This is probably NetBios name if (host.IndexOf(".") == -1) { return Dns.GetHostEntry(host).AddressList; } else { // hostName_IP must be host name, try to resolve it's IP Dns_Client dns = new Dns_Client(); DnsServerResponse resp = dns.Query(host, QTYPE.A); if (resp.ResponseCode == RCODE.NO_ERROR) { DNS_rr_A[] records = resp.GetARecords(); IPAddress[] retVal = new IPAddress[records.Length]; for (int i = 0; i < records.Length; i++) { retVal[i] = records[i].IP; } return retVal; } else { throw new Exception(resp.ResponseCode.ToString()); } } } /// <summary> /// Queries server with specified query. /// </summary> /// <param name="queryText">Query text. It depends on queryType.</param> /// <param name="queryType">Query type.</param> /// <returns></returns> public DnsServerResponse Query(string queryText, QTYPE queryType) { if (queryType == QTYPE.PTR) { string ip = queryText; // See if IP is ok. IPAddress ipA = IPAddress.Parse(ip); queryText = ""; // IPv6 if (ipA.AddressFamily == AddressFamily.InterNetworkV6) { // 4321:0:1:2:3:4:567:89ab // would be // b.a.9.8.7.6.5.0.4.0.0.0.3.0.0.0.2.0.0.0.1.0.0.0.0.0.0.0.1.2.3.4.IP6.ARPA char[] ipChars = ip.Replace(":", "").ToCharArray(); for (int i = ipChars.Length - 1; i > -1; i--) { queryText += ipChars[i] + "."; } queryText += "IP6.ARPA"; } // IPv4 else { // 213.35.221.186 // would be // 186.221.35.213.in-addr.arpa string[] ipParts = ip.Split('.'); //--- Reverse IP ---------- for (int i = 3; i > -1; i--) { queryText += ipParts[i] + "."; } queryText += "in-addr.arpa"; } } return QueryServer(2000, queryText, queryType, 1); } /// <summary> /// Gets specified host IP addresses(A and AAAA). /// </summary> /// <param name="host">Host name.</param> /// <returns>Returns specified host IP addresses.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>host</b> is null reference.</exception> public IPAddress[] GetHostAddresses(string host) { if (host == null) { throw new ArgumentNullException("host"); } List<IPAddress> retVal = new List<IPAddress>(); // This is probably NetBios name if (host.IndexOf(".") == -1) { return Dns.GetHostEntry(host).AddressList; } else { DnsServerResponse response = Query(host, QTYPE.A); if (response.ResponseCode != RCODE.NO_ERROR) { throw new DNS_ClientException(response.ResponseCode); } foreach (DNS_rr_A record in response.GetARecords()) { retVal.Add(record.IP); } response = Query(host, QTYPE.AAAA); if (response.ResponseCode != RCODE.NO_ERROR) { throw new DNS_ClientException(response.ResponseCode); } foreach (DNS_rr_A record in response.GetARecords()) { retVal.Add(record.IP); } } return retVal.ToArray(); } #endregion #region Internal methods internal static bool GetQName(byte[] reply, ref int offset, ref string name) { try { // Do while not terminator while (reply[offset] != 0) { // Check if it's pointer(In pointer first two bits always 1) bool isPointer = ((reply[offset] & 0xC0) == 0xC0); // If pointer if (isPointer) { // Pointer location number is 2 bytes long // 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 # byte 2 # 0 | 1 | 2 | | 3 | 4 | 5 | 6 | 7 // empty | < ---- pointer location number ---------------------------------> int pStart = ((reply[offset] & 0x3F) << 8) | (reply[++offset]); offset++; return GetQName(reply, ref pStart, ref name); } else { // label length (length = 8Bit and first 2 bits always 0) // 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 // empty | lablel length in bytes int labelLength = (reply[offset] & 0x3F); offset++; // Copy label into name name += Encoding.ASCII.GetString(reply, offset, labelLength); offset += labelLength; } // If the next char isn't terminator, // label continues - add dot between two labels if (reply[offset] != 0) { name += "."; } } // Move offset by terminator length offset++; return true; } catch { return false; } } /// <summary> /// Reads character-string from spefcified data and offset. /// </summary> /// <param name="data">Data from where to read.</param> /// <param name="offset">Offset from where to start reading.</param> /// <returns>Returns readed string.</returns> internal static string ReadCharacterString(byte[] data, ref int offset) { /* RFC 1035 3.3. <character-string> is a single length octet followed by that number of characters. <character-string> is treated as binary information, and can be up to 256 characters in length (including the length octet). */ int dataLength = data[offset++]; string retVal = Encoding.Default.GetString(data, offset, dataLength); offset += dataLength; return retVal; } #endregion #region Utility methods /// <summary> /// Sends query to server. /// </summary> /// <param name="timeout">Query timeout in milli seconds.</param> /// <param name="qname">Query text.</param> /// <param name="qtype">Query type.</param> /// <param name="qclass">Query class.</param> /// <returns></returns> private DnsServerResponse QueryServer(int timeout, string qname, QTYPE qtype, int qclass) { if (m_DnsServers == null || m_DnsServers.Length == 0) { throw new Exception("Dns server isn't specified !"); } // See if query is in cache if (m_UseDnsCache) { DnsServerResponse resopnse = DnsCache.GetFromCache(qname, (int) qtype); if (resopnse != null) { return resopnse; } } int queryID = ID; byte[] query = CreateQuery(queryID, qname, qtype, qclass); // Create sending UDP socket. Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpClient.SendTimeout = 500; // Send parallel query to all dns servers and get first answer. DateTime startTime = DateTime.Now; List<DnsServerResponse> responses = new List<DnsServerResponse>(); while (startTime.AddMilliseconds(timeout) > DateTime.Now) { foreach (IPAddress dnsServer in m_DnsServers) { try { udpClient.SendTo(query, new IPEndPoint(dnsServer, 53)); } catch {} } // Wait 10 ms response to arrive, if no response, retransmit query. if (udpClient.Poll(10, SelectMode.SelectRead)) { try { byte[] retVal = new byte[1024]; int countRecieved = udpClient.Receive(retVal); // If reply is ok, return it DnsServerResponse serverResponse = ParseQuery(retVal, queryID); // Cache query if (m_UseDnsCache && serverResponse.ResponseCode == RCODE.NO_ERROR) { DnsCache.AddToCache(qname, (int) qtype, serverResponse); } responses.Add(serverResponse); } catch {} } } udpClient.Close(); // If we reach so far, we probably won't get connection to dsn server return responses.Count>0?responses[0]:new DnsServerResponse(false, RCODE.SERVER_FAILURE, new List<DNS_rr_base>(), new List<DNS_rr_base>(), new List<DNS_rr_base>()); } /// <summary> /// Creates new query. /// </summary> /// <param name="ID">Query ID.</param> /// <param name="qname">Query text.</param> /// <param name="qtype">Query type.</param> /// <param name="qclass">Query class.</param> /// <returns></returns> private byte[] CreateQuery(int ID, string qname, QTYPE qtype, int qclass) { byte[] query = new byte[512]; //---- Create header --------------------------------------------// // Header is first 12 bytes of query /* 4.1.1. Header section format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QR A one bit field that specifies whether this message is a query (0), or a response (1). OPCODE A four bit field that specifies kind of query in this message. This value is set by the originator of a query and copied into the response. The values are: 0 a standard query (QUERY) 1 an inverse query (IQUERY) 2 a server status request (STATUS) */ //--------- Header part -----------------------------------// query[0] = (byte) (ID >> 8); query[1] = (byte) (ID & 0xFF); query[2] = 1; query[3] = 0; query[4] = 0; query[5] = 1; query[6] = 0; query[7] = 0; query[8] = 0; query[9] = 0; query[10] = 0; query[11] = 0; //---------------------------------------------------------// //---- End of header --------------------------------------------// //----Create query ------------------------------------// /* Rfc 1035 4.1.2. Question section format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | / QNAME / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QTYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QCLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QNAME a domain name represented as a sequence of labels, where each label consists of a length octet followed by that number of octets. The domain name terminates with the zero length octet for the null label of the root. Note that this field may be an odd number of octets; no padding is used. */ string[] labels = qname.Split(new[] {'.'}); int position = 12; // Copy all domain parts(labels) to query // eg. lumisoft.ee = 2 labels, lumisoft and ee. // format = label.length + label(bytes) foreach (string label in labels) { // add label lenght to query query[position++] = (byte) (label.Length); // convert label string to byte array byte[] b = Encoding.ASCII.GetBytes(label); b.CopyTo(query, position); // Move position by label length position += b.Length; } // Terminate domain (see note above) query[position++] = 0; // Set QTYPE query[position++] = 0; query[position++] = (byte) qtype; // Set QCLASS query[position++] = 0; query[position++] = (byte) qclass; //-------------------------------------------------------// string queryStr = Encoding.ASCII.GetString(query); return query; } /// <summary> /// Parses query. /// </summary> /// <param name="reply">Dns server reply.</param> /// <param name="queryID">Query id of sent query.</param> /// <returns></returns> private DnsServerResponse ParseQuery(byte[] reply, int queryID) { //--- Parse headers ------------------------------------// /* RFC 1035 4.1.1. Header section format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QDCOUNT an unsigned 16 bit integer specifying the number of entries in the question section. ANCOUNT an unsigned 16 bit integer specifying the number of resource records in the answer section. NSCOUNT an unsigned 16 bit integer specifying the number of name server resource records in the authority records section. ARCOUNT an unsigned 16 bit integer specifying the number of resource records in the additional records section. */ // Get reply code int id = (reply[0] << 8 | reply[1]); OPCODE opcode = (OPCODE) ((reply[2] >> 3) & 15); RCODE replyCode = (RCODE) (reply[3] & 15); int queryCount = (reply[4] << 8 | reply[5]); int answerCount = (reply[6] << 8 | reply[7]); int authoritiveAnswerCount = (reply[8] << 8 | reply[9]); int additionalAnswerCount = (reply[10] << 8 | reply[11]); //---- End of headers ---------------------------------// // Check that it's query what we want if (queryID != id) { throw new Exception("This isn't query with ID what we expected"); } int pos = 12; //----- Parse question part ------------// for (int q = 0; q < queryCount; q++) { string dummy = ""; GetQName(reply, ref pos, ref dummy); //qtype + qclass pos += 4; } //--------------------------------------// // 1) parse answers // 2) parse authoritive answers // 3) parse additional answers List<DNS_rr_base> answers = ParseAnswers(reply, answerCount, ref pos); List<DNS_rr_base> authoritiveAnswers = ParseAnswers(reply, authoritiveAnswerCount, ref pos); List<DNS_rr_base> additionalAnswers = ParseAnswers(reply, additionalAnswerCount, ref pos); return new DnsServerResponse(true, replyCode, answers, authoritiveAnswers, additionalAnswers); } /// <summary> /// Parses specified count of answers from query. /// </summary> /// <param name="reply">Server returned query.</param> /// <param name="answerCount">Number of answers to parse.</param> /// <param name="offset">Position from where to start parsing answers.</param> /// <returns></returns> private List<DNS_rr_base> ParseAnswers(byte[] reply, int answerCount, ref int offset) { /* RFC 1035 4.1.3. Resource record format 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | | / / / NAME / | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | TYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | CLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | TTL | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | RDLENGTH | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| / RDATA / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ */ List<DNS_rr_base> answers = new List<DNS_rr_base>(); //---- Start parsing answers ------------------------------------------------------------------// for (int i = 0; i < answerCount; i++) { string name = ""; if (!GetQName(reply, ref offset, ref name)) { throw new Exception("Error parsing anser"); } int type = reply[offset++] << 8 | reply[offset++]; int rdClass = reply[offset++] << 8 | reply[offset++]; int ttl = reply[offset++] << 24 | reply[offset++] << 16 | reply[offset++] << 8 | reply[offset++]; int rdLength = reply[offset++] << 8 | reply[offset++]; if ((QTYPE) type == QTYPE.A) { answers.Add(DNS_rr_A.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.NS) { answers.Add(DNS_rr_NS.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.CNAME) { answers.Add(DNS_rr_CNAME.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.SOA) { answers.Add(DNS_rr_SOA.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.PTR) { answers.Add(DNS_rr_PTR.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.HINFO) { answers.Add(DNS_rr_HINFO.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.MX) { answers.Add(DNS_rr_MX.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.TXT) { answers.Add(DNS_rr_TXT.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.AAAA) { answers.Add(DNS_rr_AAAA.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.SRV) { answers.Add(DNS_rr_SRV.Parse(reply, ref offset, rdLength, ttl)); } else if ((QTYPE) type == QTYPE.NAPTR) { answers.Add(DNS_rr_NAPTR.Parse(reply, ref offset, rdLength, ttl)); } else { // Unknown record, skip it. offset += rdLength; } } return answers; } #endregion } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using ProtoBuf; using OpenSim.Framework; using OpenMetaverse; namespace InWorldz.Region.Data.Thoosa.Serialization { /// <summary> /// Protobuf serializable PrimitiveBaseShape /// </summary> [ProtoContract] public class PrimShapeSnapshot { [ProtoMember(1)] public byte ProfileCurve; [ProtoMember(2)] public byte[] TextureEntry; [ProtoMember(3)] public byte[] ExtraParams; [ProtoMember(4)] public ushort PathBegin; [ProtoMember(5)] public byte PathCurve; [ProtoMember(6)] public ushort PathEnd; [ProtoMember(7)] public sbyte PathRadiusOffset; [ProtoMember(8)] public byte PathRevolutions; [ProtoMember(9)] public byte PathScaleX; [ProtoMember(10)] public byte PathScaleY; [ProtoMember(11)] public byte PathShearX; [ProtoMember(12)] public byte PathShearY; [ProtoMember(13)] public sbyte PathTwist; [ProtoMember(14)] public sbyte PathTwistBegin; [ProtoMember(15)] public byte PCode; [ProtoMember(16)] public ushort ProfileBegin; [ProtoMember(17)] public ushort ProfileEnd; [ProtoMember(18)] public ushort ProfileHollow; [ProtoMember(19)] public OpenMetaverse.Vector3 Scale; [ProtoMember(20)] public byte State; [ProtoMember(21)] public ProfileShape ProfileShape; [ProtoMember(22)] public HollowShape HollowShape; [ProtoMember(23)] public Guid SculptTexture; [ProtoMember(24)] public byte SculptType; [Obsolete("This attribute is no longer serialized")] [ProtoMember(25)] public byte[] SculptData { get { return null; } set { } } [ProtoMember(26)] public int FlexiSoftness; [ProtoMember(27)] public float FlexiTension; [ProtoMember(28)] public float FlexiDrag; [ProtoMember(29)] public float FlexiGravity; [ProtoMember(30)] public float FlexiWind; [ProtoMember(31)] public float FlexiForceX; [ProtoMember(32)] public float FlexiForceY; [ProtoMember(33)] public float FlexiForceZ; [ProtoMember(34)] public float[] LightColor; [ProtoMember(35)] public float LightRadius; [ProtoMember(36)] public float LightCutoff; [ProtoMember(37)] public float LightIntensity; [ProtoMember(38)] public bool FlexiEntry; [ProtoMember(39)] public bool LightEntry; [ProtoMember(40)] public bool SculptEntry; [ProtoMember(41)] public bool ProjectionEntry; [ProtoMember(42)] public Guid ProjectionTextureId; [ProtoMember(43)] public float ProjectionFOV; [ProtoMember(44)] public float ProjectionFocus; [ProtoMember(45)] public float ProjectionAmbiance; [ProtoMember(46)] public OpenMetaverse.PhysicsShapeType PreferredPhysicsShape; [ProtoMember(47)] public MediaEntrySnapshot[] MediaList; [ProtoMember(48)] public sbyte PathSkew; [ProtoMember(49)] public sbyte PathTaperX; [ProtoMember(50)] public sbyte PathTaperY; [ProtoMember(51)] public int VertexCount; [ProtoMember(52)] public int HighLODBytes; [ProtoMember(53)] public int MidLODBytes; [ProtoMember(54)] public int LowLODBytes; [ProtoMember(55)] public int LowestLODBytes; static PrimShapeSnapshot() { ProtoBuf.Serializer.PrepareSerializer<PrimShapeSnapshot>(); } public static PrimShapeSnapshot FromShape(PrimitiveBaseShape primitiveBaseShape) { return new PrimShapeSnapshot { ExtraParams = primitiveBaseShape.ExtraParams, FlexiDrag = primitiveBaseShape.FlexiDrag, FlexiEntry = primitiveBaseShape.FlexiEntry, FlexiForceX = primitiveBaseShape.FlexiForceX, FlexiForceY = primitiveBaseShape.FlexiForceY, FlexiForceZ = primitiveBaseShape.FlexiForceZ, FlexiGravity = primitiveBaseShape.FlexiGravity, FlexiSoftness = primitiveBaseShape.FlexiSoftness, FlexiTension = primitiveBaseShape.FlexiTension, FlexiWind = primitiveBaseShape.FlexiWind, HollowShape = primitiveBaseShape.HollowShape, LightColor = new float[] { primitiveBaseShape.LightColorA, primitiveBaseShape.LightColorR, primitiveBaseShape.LightColorG, primitiveBaseShape.LightColorB }, LightCutoff = primitiveBaseShape.LightCutoff, LightEntry = primitiveBaseShape.LightEntry, LightIntensity = primitiveBaseShape.LightIntensity, LightRadius = primitiveBaseShape.LightRadius, PathBegin = primitiveBaseShape.PathBegin, PathCurve = primitiveBaseShape.PathCurve, PathEnd = primitiveBaseShape.PathEnd, PathRadiusOffset = primitiveBaseShape.PathRadiusOffset, PathRevolutions = primitiveBaseShape.PathRevolutions, PathScaleX = primitiveBaseShape.PathScaleX, PathScaleY = primitiveBaseShape.PathScaleY, PathShearX = primitiveBaseShape.PathShearX, PathShearY = primitiveBaseShape.PathShearY, PathSkew = primitiveBaseShape.PathSkew, PathTaperX = primitiveBaseShape.PathTaperX, PathTaperY = primitiveBaseShape.PathTaperY, PathTwist = primitiveBaseShape.PathTwist, PathTwistBegin = primitiveBaseShape.PathTwistBegin, PCode = primitiveBaseShape.PCode, PreferredPhysicsShape = primitiveBaseShape.PreferredPhysicsShape, ProfileBegin = primitiveBaseShape.ProfileBegin, ProfileCurve = primitiveBaseShape.ProfileCurve, ProfileEnd = primitiveBaseShape.ProfileEnd, ProfileHollow = primitiveBaseShape.ProfileHollow, ProfileShape = primitiveBaseShape.ProfileShape, ProjectionAmbiance = primitiveBaseShape.ProjectionAmbiance, ProjectionEntry = primitiveBaseShape.ProjectionEntry, ProjectionFocus = primitiveBaseShape.ProjectionFocus, ProjectionFOV = primitiveBaseShape.ProjectionFOV, ProjectionTextureId = primitiveBaseShape.ProjectionTextureUUID.Guid, Scale = primitiveBaseShape.Scale, SculptEntry = primitiveBaseShape.SculptEntry, SculptTexture = primitiveBaseShape.SculptTexture.Guid, SculptType = primitiveBaseShape.SculptType, State = primitiveBaseShape.State, TextureEntry = primitiveBaseShape.TextureEntryBytes, MediaList = MediaEntrySnapshot.SnapshotArrayFromList(primitiveBaseShape.Media), VertexCount = primitiveBaseShape.VertexCount, HighLODBytes = primitiveBaseShape.HighLODBytes, MidLODBytes = primitiveBaseShape.MidLODBytes, LowLODBytes = primitiveBaseShape.LowLODBytes, LowestLODBytes = primitiveBaseShape.LowestLODBytes }; } public PrimitiveBaseShape ToPrimitiveBaseShape() { return new PrimitiveBaseShape { ExtraParams = this.ExtraParams, FlexiDrag = this.FlexiDrag, FlexiEntry = this.FlexiEntry, FlexiForceX = this.FlexiForceX, FlexiForceY = this.FlexiForceY, FlexiForceZ = this.FlexiForceZ, FlexiGravity = this.FlexiGravity, FlexiSoftness = this.FlexiSoftness, FlexiTension = this.FlexiTension, FlexiWind = this.FlexiWind, HollowShape = this.HollowShape, LightColorA = this.LightColor[0], LightColorR = this.LightColor[1], LightColorG = this.LightColor[2], LightColorB = this.LightColor[3], LightCutoff = this.LightCutoff, LightEntry = this.LightEntry, LightIntensity = this.LightIntensity, LightRadius = this.LightRadius, PathBegin = this.PathBegin, PathCurve = this.PathCurve, PathEnd = this.PathEnd, PathRadiusOffset = this.PathRadiusOffset, PathRevolutions = this.PathRevolutions, PathScaleX = this.PathScaleX, PathScaleY = this.PathScaleY, PathShearX = this.PathShearX, PathShearY = this.PathShearY, PathSkew = this.PathSkew, PathTaperX = this.PathTaperX, PathTaperY = this.PathTaperY, PathTwist = this.PathTwist, PathTwistBegin = this.PathTwistBegin, PCode = this.PCode, PreferredPhysicsShape = this.PreferredPhysicsShape, ProfileBegin = this.ProfileBegin, ProfileCurve = this.ProfileCurve, ProfileEnd = this.ProfileEnd, ProfileHollow = this.ProfileHollow, ProfileShape = this.ProfileShape, ProjectionAmbiance = this.ProjectionAmbiance, ProjectionEntry = this.ProjectionEntry, ProjectionFocus = this.ProjectionFocus, ProjectionFOV = this.ProjectionFOV, ProjectionTextureUUID = new OpenMetaverse.UUID(this.ProjectionTextureId), Scale = this.Scale, SculptEntry = this.SculptEntry, SculptTexture = new OpenMetaverse.UUID(this.SculptTexture), SculptType = this.SculptType, State = this.State, TextureEntryBytes = this.TextureEntry, Media = MediaEntrySnapshot.SnapshotArrayToList(this.MediaList), VertexCount = this.VertexCount, HighLODBytes = this.HighLODBytes, MidLODBytes = this.MidLODBytes, LowLODBytes = this.LowLODBytes, LowestLODBytes = this.LowestLODBytes }; } } }
namespace dotless.Core.configuration { using System; using Input; using Loggers; using Plugins; using System.Collections.Generic; public enum DotlessSessionStateMode { /// <summary> /// Session is not used. /// </summary> Disabled, /// <summary> /// Session is loaded for each request to Dotless HTTP handler. /// </summary> Enabled, /// <summary> /// Session is loaded when URL QueryString parameter specified by <seealso cref="DotlessConfiguration.SessionQueryParamName"/> is truthy. /// </summary> QueryParam } public class DotlessConfiguration { public const string DEFAULT_SESSION_QUERY_PARAM_NAME = "sstate"; public const int DefaultHttpExpiryInMinutes = 10080; //7 days internal static IConfigurationManager _configurationManager; public static DotlessConfiguration GetDefault() { return new DotlessConfiguration();; } public static DotlessConfiguration GetDefaultWeb() { return new DotlessConfiguration { Web = true }; } public DotlessConfiguration() { LessSource = typeof (FileReader); MinifyOutput = false; Debug = false; CacheEnabled = true; HttpExpiryInMinutes = DefaultHttpExpiryInMinutes; Web = false; SessionMode = DotlessSessionStateMode.Disabled; SessionQueryParamName = DEFAULT_SESSION_QUERY_PARAM_NAME; Logger = null; LogLevel = LogLevel.Error; Optimization = 1; Plugins = new List<IPluginConfigurator>(); MapPathsToWeb = true; HandleWebCompression = true; KeepFirstSpecialComment = false; RootPath = ""; StrictMath = false; } public DotlessConfiguration(DotlessConfiguration config) { LessSource = config.LessSource; MinifyOutput = config.MinifyOutput; Debug = config.Debug; CacheEnabled = config.CacheEnabled; Web = config.Web; SessionMode = config.SessionMode; SessionQueryParamName = config.SessionQueryParamName; Logger = null; LogLevel = config.LogLevel; Optimization = config.Optimization; Plugins = new List<IPluginConfigurator>(); Plugins.AddRange(config.Plugins); MapPathsToWeb = config.MapPathsToWeb; DisableUrlRewriting = config.DisableUrlRewriting; InlineCssFiles = config.InlineCssFiles; ImportAllFilesAsLess = config.ImportAllFilesAsLess; HandleWebCompression = config.HandleWebCompression; DisableParameters = config.DisableParameters; KeepFirstSpecialComment = config.KeepFirstSpecialComment; RootPath = config.RootPath; StrictMath = config.StrictMath; } public static IConfigurationManager ConfigurationManager { get { return _configurationManager ?? (_configurationManager = new ConfigurationManagerWrapper()); } set { if (value == null) { throw new ArgumentNullException("value"); } _configurationManager = value; } } /// <summary> /// Keep first comment begining /** /// </summary> public bool KeepFirstSpecialComment { get; set; } /// <summary> /// Disable using parameters /// </summary> public bool DisableParameters { get; set; } /// <summary> /// Stops URL's being adjusted depending on the imported file location /// </summary> public bool DisableUrlRewriting { get; set; } /// <summary> /// Allows you to add a path to every generated import and url in your output css. /// This corresponds to 'rootpath' option of lessc. /// </summary> public string RootPath { get; set; } /// <summary> /// Disables variables being redefined, so less will search from the bottom of the input up. /// Makes dotless behave like less.js with regard variables /// </summary> [Obsolete("The Variable Redefines feature has been removed to align with less.js")] public bool DisableVariableRedefines { get; set; } /// <summary> /// Disables hex color shortening /// </summary> [Obsolete("The Color Compression feature has been removed to align with less.js")] public bool DisableColorCompression { get; set; } /// <summary> /// Inlines css files into the less output /// </summary> public bool InlineCssFiles { get; set; } /// <summary> /// import all files (even if ending in .css) as less files /// </summary> public bool ImportAllFilesAsLess { get; set; } /// <summary> /// When this is a web configuration, whether to map the paths to the website or just /// be relative to the current directory /// </summary> public bool MapPathsToWeb { get; set; } /// <summary> /// Whether to minify the ouput /// </summary> public bool MinifyOutput { get; set; } /// <summary> /// Prints helpful comments in the output while debugging. /// </summary> public bool Debug { get; set; } /// <summary> /// For web handlers output in a cached mode. Reccommended on. /// </summary> public bool CacheEnabled { get; set; } /// <summary> /// When <seealso cref="CacheEnabled"/> is set to true, use this parameter to set how far in the future the expires header will be set. /// For example, to have the browser cache the CSS for five minutes, set this property to 5. /// </summary> public int HttpExpiryInMinutes { get; set; } /// <summary> /// IFileReader type to use to get imported files /// </summary> public Type LessSource { get; set; } /// <summary> /// Whether this is used in a web context or not /// </summary> public bool Web { get; set; } /// <summary> /// Specifies the mode the HttpContext.Session is loaded. /// </summary> public DotlessSessionStateMode SessionMode { get; set; } /// <summary> /// Gets or sets the URL QueryString parameter name used in conjunction with <seealso cref="SessionMode"/> set to <seealso cref="DotlessSessionStateMode.QueryParam"/>. /// </summary> public string SessionQueryParamName { get; set; } /// <summary> /// The ILogger type /// </summary> public Type Logger { get; set; } /// <summary> /// The Log level /// </summary> public LogLevel LogLevel { get; set; } /// <summary> /// Optimisation int /// 0 - do not chunk up the input /// > 0 - chunk up output /// /// Recommended value - 1 /// </summary> public int Optimization { get; set; } /// <summary> /// Whether to handle the compression (e.g. look at Accept-Encoding) - true or leave it to IIS - false /// </summary> public bool HandleWebCompression { get; set; } /// <summary> /// Plugins to use /// </summary> public List<IPluginConfigurator> Plugins { get; private set; } /// <summary> /// Whether to only evaluate mathematical expressions when they are wrapped in an extra set of parentheses. /// </summary> public bool StrictMath { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SortQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// The query operator for OrderBy and ThenBy. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TSortKey"></typeparam> internal sealed class SortQueryOperator<TInputOutput, TSortKey> : UnaryQueryOperator<TInputOutput, TInputOutput>, IOrderedEnumerable<TInputOutput> { private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting. private readonly IComparer<TSortKey> _comparer; // Key comparison logic to use during sorting. //--------------------------------------------------------------------------------------- // Instantiates a new sort operator. // internal SortQueryOperator(IEnumerable<TInputOutput> source, Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> comparer, bool descending) : base(source, true) { Debug.Assert(keySelector != null, "key selector must not be null"); _keySelector = keySelector; // If a comparer wasn't supplied, we use the default one for the key type. if (comparer == null) { _comparer = Util.GetDefaultComparer<TSortKey>(); } else { _comparer = comparer; } if (descending) { _comparer = new ReverseComparer<TSortKey>(_comparer); } SetOrdinalIndexState(OrdinalIndexState.Shuffled); } //--------------------------------------------------------------------------------------- // IOrderedEnumerable method for nesting an order by operator inside another. // IOrderedEnumerable<TInputOutput> IOrderedEnumerable<TInputOutput>.CreateOrderedEnumerable<TKey2>( Func<TInputOutput, TKey2> key2Selector, IComparer<TKey2> key2Comparer, bool descending) { key2Comparer = key2Comparer ?? Util.GetDefaultComparer<TKey2>(); if (descending) { key2Comparer = new ReverseComparer<TKey2>(key2Comparer); } IComparer<Pair<TSortKey, TKey2>> pairComparer = new PairComparer<TSortKey, TKey2>(_comparer, key2Comparer); Func<TInputOutput, Pair<TSortKey, TKey2>> pairKeySelector = (TInputOutput elem) => new Pair<TSortKey, TKey2>(_keySelector(elem), key2Selector(elem)); return new SortQueryOperator<TInputOutput, Pair<TSortKey, TKey2>>(Child, pairKeySelector, pairComparer, false); } //--------------------------------------------------------------------------------------- // Accessor the key selector. // //--------------------------------------------------------------------------------------- // Accessor the key comparer. // //--------------------------------------------------------------------------------------- // Opens the current operator. This involves opening the child operator tree, enumerating // the results, sorting them, and then returning an enumerator that walks the result. // internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping) { QueryResults<TInputOutput> childQueryResults = Child.Open(settings, false); return new SortQueryOperatorResults<TInputOutput, TSortKey>(childQueryResults, this, settings); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings) { PartitionedStream<TInputOutput, TSortKey> outputStream = new PartitionedStream<TInputOutput, TSortKey>(inputStream.PartitionCount, this._comparer, OrdinalIndexState); for (int i = 0; i < outputStream.PartitionCount; i++) { outputStream[i] = new SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey>( inputStream[i], _keySelector, _comparer); } recipient.Receive<TSortKey>(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.OrderBy(_keySelector, _comparer); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } } internal class SortQueryOperatorResults<TInputOutput, TSortKey> : QueryResults<TInputOutput> { protected QueryResults<TInputOutput> _childQueryResults; // Results of the child query private SortQueryOperator<TInputOutput, TSortKey> _op; // Operator that generated these results private QuerySettings _settings; // Settings collected from the query internal SortQueryOperatorResults( QueryResults<TInputOutput> childQueryResults, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings) { _childQueryResults = childQueryResults; _op = op; _settings = settings; } internal override bool IsIndexible { get { return false; } } internal override void GivePartitionedStream(IPartitionedStreamRecipient<TInputOutput> recipient) { _childQueryResults.GivePartitionedStream(new ChildResultsRecipient(recipient, _op, _settings)); } private class ChildResultsRecipient : IPartitionedStreamRecipient<TInputOutput> { private IPartitionedStreamRecipient<TInputOutput> _outputRecipient; private SortQueryOperator<TInputOutput, TSortKey> _op; private QuerySettings _settings; internal ChildResultsRecipient(IPartitionedStreamRecipient<TInputOutput> outputRecipient, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings) { _outputRecipient = outputRecipient; _op = op; _settings = settings; } public void Receive<TKey>(PartitionedStream<TInputOutput, TKey> childPartitionedStream) { _op.WrapPartitionedStream(childPartitionedStream, _outputRecipient, false, _settings); } } } //--------------------------------------------------------------------------------------- // This enumerator performs sorting based on a key selection and comparison routine. // internal class SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey> : QueryOperatorEnumerator<TInputOutput, TSortKey> { private readonly QueryOperatorEnumerator<TInputOutput, TKey> _source; // Data source to sort. private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting. private readonly IComparer<TSortKey> _keyComparer; // Key comparison logic to use during sorting. //--------------------------------------------------------------------------------------- // Instantiates a new sort operator enumerator. // internal SortQueryOperatorEnumerator(QueryOperatorEnumerator<TInputOutput, TKey> source, Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> keyComparer) { Debug.Assert(source != null); Debug.Assert(keySelector != null, "need a key comparer"); Debug.Assert(keyComparer != null, "expected a compiled operator"); _source = source; _keySelector = keySelector; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Accessor for the key comparison routine. // //--------------------------------------------------------------------------------------- // Moves to the next element in the sorted output. When called for the first time, the // descendents in the sort's child tree are executed entirely, the results accumulated // in memory, and the data sorted. // internal override bool MoveNext(ref TInputOutput currentElement, ref TSortKey currentKey) { Debug.Assert(_source != null); TKey keyUnused = default(TKey); if (!_source.MoveNext(ref currentElement, ref keyUnused)) { return false; } currentKey = _keySelector(currentElement); return true; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.IO; using EarLab.ReaderWriters; using EarLab.Utilities; namespace EarLab.Viewers.Layouts { /// <summary> /// Summary description for LayoutFullScrollable. /// </summary> public class LayoutFullScrollable : System.Windows.Forms.UserControl, ILayout { private EarLab.Viewers.Layouts.Layout2DColorFull layout2DColorFull; private EarLab.Controls.ExtendedScrollBar extendedScrollBar; private System.Windows.Forms.ContextMenu contextMenu; private System.Windows.Forms.MenuItem zoomInMenuItem; private System.Windows.Forms.MenuItem zoomOutMenuItem; private System.Windows.Forms.MenuItem zoomMenuItem; private System.Windows.Forms.MenuItem zoomLevelsMenuItem; private System.Windows.Forms.MenuItem seperatorMenuItem; private System.Windows.Forms.MenuItem optionsMenuItem; private System.Windows.Forms.MenuItem colorbarMenuItem; private System.Windows.Forms.MenuItem tipMenuItem; private System.Windows.Forms.MenuItem seperator1MenuItem; private System.Windows.Forms.MenuItem seperator2MenuItem; private System.Windows.Forms.MenuItem saveMenuItem; private System.Windows.Forms.SaveFileDialog saveFileDialog; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private double[,] dataArray; private ReaderWriterBinary readerWriterBinary; private MainMenu mainMenu; private bool toolTipShow = false; private double[] dimensionSteps; private DataTable fileTable; private int fileIndex = 0; public LayoutFullScrollable() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); EarLab.Utilities.EnableVisualStyles.EnableControl(this); // sign up to mouse move event of the viewer panel so we can display tooltip this.layout2DColorFull.Layout2DColor.ViewerPanel.MouseMove += new MouseEventHandler(ViewerPanel_MouseMove); // add the colorbar context menu into this context menu ContextMenu colorbarContextMenu = this.layout2DColorFull.Layout2DColor.ColorbarPanel.ContextMenu; MenuItem[] colorbarMenuItems = new MenuItem[colorbarContextMenu.MenuItems.Count]; for (int i=0; i<colorbarMenuItems.Length; i++) colorbarMenuItems[i] = colorbarContextMenu.MenuItems[i].CloneMenu(); this.colorbarMenuItem.MenuItems.AddRange(colorbarMenuItems); // add the analysis menu to the main menu this.optionsMenuItem.MenuItems.Add(4, this.layout2DColorFull.AnalysisMenu); } /// <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 Component 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.layout2DColorFull = new EarLab.Viewers.Layouts.Layout2DColorFull(); this.extendedScrollBar = new EarLab.Controls.ExtendedScrollBar(); this.contextMenu = new System.Windows.Forms.ContextMenu(); this.optionsMenuItem = new System.Windows.Forms.MenuItem(); this.zoomMenuItem = new System.Windows.Forms.MenuItem(); this.zoomInMenuItem = new System.Windows.Forms.MenuItem(); this.zoomOutMenuItem = new System.Windows.Forms.MenuItem(); this.seperatorMenuItem = new System.Windows.Forms.MenuItem(); this.zoomLevelsMenuItem = new System.Windows.Forms.MenuItem(); this.colorbarMenuItem = new System.Windows.Forms.MenuItem(); this.tipMenuItem = new System.Windows.Forms.MenuItem(); this.seperator1MenuItem = new System.Windows.Forms.MenuItem(); this.seperator2MenuItem = new System.Windows.Forms.MenuItem(); this.saveMenuItem = new System.Windows.Forms.MenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.SuspendLayout(); // // layout2DColorFull // this.layout2DColorFull.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.layout2DColorFull.Location = new System.Drawing.Point(0, 0); this.layout2DColorFull.Name = "layout2DColorFull"; this.layout2DColorFull.Size = new System.Drawing.Size(664, 352); this.layout2DColorFull.TabIndex = 0; // // extendedScrollBar // this.extendedScrollBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.extendedScrollBar.AutoScrolling = false; this.extendedScrollBar.LargeChange = 100; this.extendedScrollBar.Location = new System.Drawing.Point(140, 356); this.extendedScrollBar.Maximum = 100; this.extendedScrollBar.Minimum = 0; this.extendedScrollBar.Name = "extendedScrollBar"; this.extendedScrollBar.Size = new System.Drawing.Size(412, 17); this.extendedScrollBar.SmallChange = 10; this.extendedScrollBar.TabIndex = 1; this.extendedScrollBar.TimerAmount = 10; this.extendedScrollBar.TimerInterval = 100; this.extendedScrollBar.Value = 0; this.extendedScrollBar.Scroll += new System.Windows.Forms.ScrollEventHandler(this.extendedScrollBar_Scroll); // // contextMenu // this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.optionsMenuItem}); // // optionsMenuItem // this.optionsMenuItem.Index = 0; this.optionsMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.zoomMenuItem, this.colorbarMenuItem, this.tipMenuItem, this.seperator1MenuItem, this.seperator2MenuItem, this.saveMenuItem}); this.optionsMenuItem.Text = "&Options"; // // zoomMenuItem // this.zoomMenuItem.Index = 0; this.zoomMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.zoomInMenuItem, this.zoomOutMenuItem, this.seperatorMenuItem, this.zoomLevelsMenuItem}); this.zoomMenuItem.Text = "&Zoom"; // // zoomInMenuItem // this.zoomInMenuItem.Enabled = false; this.zoomInMenuItem.Index = 0; this.zoomInMenuItem.Shortcut = System.Windows.Forms.Shortcut.F1; this.zoomInMenuItem.Text = "Zoom &In"; this.zoomInMenuItem.Click += new System.EventHandler(this.zoomInMenuItem_Click); // // zoomOutMenuItem // this.zoomOutMenuItem.Index = 1; this.zoomOutMenuItem.Shortcut = System.Windows.Forms.Shortcut.F2; this.zoomOutMenuItem.Text = "Zoom &Out"; this.zoomOutMenuItem.Click += new System.EventHandler(this.zoomOutMenuItem_Click); // // seperatorMenuItem // this.seperatorMenuItem.Index = 2; this.seperatorMenuItem.Text = "-"; // // zoomLevelsMenuItem // this.zoomLevelsMenuItem.Index = 3; this.zoomLevelsMenuItem.Shortcut = System.Windows.Forms.Shortcut.F3; this.zoomLevelsMenuItem.Text = "&Zoom Levels"; // // colorbarMenuItem // this.colorbarMenuItem.Index = 1; this.colorbarMenuItem.Text = "&Colorbar"; // // tipMenuItem // this.tipMenuItem.Index = 2; this.tipMenuItem.Shortcut = System.Windows.Forms.Shortcut.CtrlT; this.tipMenuItem.Text = "&Show Tool Tip"; this.tipMenuItem.Click += new System.EventHandler(this.tipMenuItem_Click); // // seperator1MenuItem // this.seperator1MenuItem.Index = 3; this.seperator1MenuItem.Text = "-"; // // seperator2MenuItem // this.seperator2MenuItem.Index = 4; this.seperator2MenuItem.Text = "-"; // // saveMenuItem // this.saveMenuItem.Index = 5; this.saveMenuItem.Text = "Save &Image..."; this.saveMenuItem.Click += new System.EventHandler(this.saveMenuItem_Click); // // saveFileDialog // this.saveFileDialog.Filter = "BMP Windows Bitmap (*.bmp)|*.bmp|JPEG Joint Photographic Experts Group (*.jpg)|*." + "jpg|GIF Graphics Interchange Format (*.gif)|*.gif|PNG Portable Network Graphics " + "(*.png)|*.png|TIFF Tag Image File Format (*.tiff)|*.tiff"; this.saveFileDialog.Title = "Save File..."; // // LayoutFullScrollable // this.Controls.Add(this.extendedScrollBar); this.Controls.Add(this.layout2DColorFull); this.Name = "LayoutFullScrollable"; this.Size = new System.Drawing.Size(664, 376); this.ResumeLayout(false); } #endregion #region Methods public string Read(string fileName) { if (!this.GetRelatedFiles(fileName)) return "One of the downsampled files does not match expected format."; return this.SetupFile(fileName); } public void Close() { if (this.readerWriterBinary != null) { this.readerWriterBinary.Close(); this.readerWriterBinary = null; } // remove the options menu from the main menu (if we added it) if (this.mainMenu != null) this.mainMenu.MenuItems.Remove(this.optionsMenuItem); } private string SetupFile(string fileName) { // create a new instance of the binary file reader if (this.readerWriterBinary != null) this.readerWriterBinary.Close(); this.readerWriterBinary = new ReaderWriterBinary(); // open the file for reading string returnString = this.readerWriterBinary.Read(fileName); if (returnString != "0") return returnString; // set the viewer top axis label to the file name string[] fileParts = fileName.Split('\\'); this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.TopAxisLabel = fileParts[fileParts.Length-1]; this.SetupElements(); return "0"; } private bool GetRelatedFiles(string fileName) { FileInfo selectedFile = new FileInfo(fileName); this.fileTable = new DataTable("FileTable"); this.fileTable.Columns.Add("FileName", typeof(string)); this.fileTable.Columns.Add("ZoomLevel", typeof(int)); this.fileTable.Rows.Add(new object[] {selectedFile.FullName, 0}); this.fileIndex = 0; // get the file name and split it up on '.' character string[] filenameArray = selectedFile.Name.Split('.'); if (filenameArray.Length == 3) { string[] fileNames = Directory.GetFiles(selectedFile.Directory.FullName, filenameArray[0] + ".*.metadata"); if (fileNames.Length > 1) { this.fileTable.Clear(); int[] zoomLevels = new int[fileNames.Length]; // figure out zoom levels and store them for (int i=0; i<fileNames.Length; i++) { filenameArray = fileNames[i].Split('.'); try { zoomLevels[i] = int.Parse(filenameArray[filenameArray.Length-2]); } catch { MessageBox.Show(this.ParentForm, "One of the parameter file names was in an incorrect format.", "Incorrect Format", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } Array.Sort(zoomLevels, fileNames); Array.Sort(zoomLevels); for (int i=0; i<fileNames.Length; i++) { if (fileNames[i] == selectedFile.FullName) { this.fileIndex = i; break; } } // create the file table for (int i=0; i<fileNames.Length; i++) if (File.Exists(fileNames[i].Replace(".metadata", ".binary"))) this.fileTable.Rows.Add(new object[] {fileNames[i], zoomLevels[i]}); // create the zoom levels for zoom menu foreach(DataRow row in this.fileTable.Rows) this.zoomLevelsMenuItem.MenuItems.Add("Level " + row["ZoomLevel"].ToString(), new EventHandler(ZoomLevelMenuItem_Clicked)); this.ZoomMenuUpdate(); return true; } else return true; } else return true; } private void SetupElements() { // make sure we don't show zoom menu if it is a 3D file, but enable box selection if (this.readerWriterBinary.Dimensions.Length == 3) { this.zoomMenuItem.Enabled = false; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.TopAxisLabel += ", 0.00 " + this.readerWriterBinary.Dimensions[2].Name; } else { this.layout2DColorFull.BoxEnabled = true; } // create a new data array of the correct size, fill it with data, and send it to the viewer panel if (this.readerWriterBinary.Dimensions.Length ==2) dataArray = new double[this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width, this.readerWriterBinary.Dimensions[0].Size]; else dataArray = new double[this.readerWriterBinary.Dimensions[1].Size, this.readerWriterBinary.Dimensions[0].Size]; // get initial data from the file, send it to the viewer this.readerWriterBinary.GetData(ref dataArray, 0); this.layout2DColorFull.View(dataArray); // if we don't have a 3D viewer, we need to respond to a resize event by making a bigger array (due to our scroll) if (this.readerWriterBinary.Dimensions.Length == 2) { this.layout2DColorFull.Layout2DColor.Resize -= new EventHandler(Layout2DColor_Resize); this.layout2DColorFull.Layout2DColor.Resize += new EventHandler(Layout2DColor_Resize); } // calculate step sizes for the different dimensions dimensionSteps = new double[this.readerWriterBinary.Dimensions.Length]; for (int i=0;i<dimensionSteps.Length;i++) dimensionSteps[i] = (double)(Math.Abs(this.readerWriterBinary.Dimensions[i].End-this.readerWriterBinary.Dimensions[i].Start)/(double)this.readerWriterBinary.Dimensions[i].Size); // setup the viewer's axis to show correct values this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisLabel = this.readerWriterBinary.Dimensions[0].Name; if (this.readerWriterBinary.Dimensions[0].ElementArray == null) this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisMajorTickNumbersFormat = "0"; else this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisMajorTickNumbersFormat = "0.00e00"; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisStartValue = (float)this.readerWriterBinary.Dimensions[0].Start; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisEndValue = (float)this.readerWriterBinary.Dimensions[0].End; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisValueArray = this.readerWriterBinary.Dimensions[0].ElementArray; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisLabel = this.readerWriterBinary.Dimensions[1].Name; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisMajorTickNumbersFormat = "0.00"; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisStartValue = (float)this.readerWriterBinary.Dimensions[1].Start; // we set up the bottom axis and scrollbar to have enough values if (this.readerWriterBinary.Dimensions.Length == 2) { this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisEndValue = (float)(this.readerWriterBinary.Dimensions[1].Start+this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width*this.dimensionSteps[1]); if (this.readerWriterBinary.Dimensions[1].Size - 1 <= this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width) { this.extendedScrollBar.Value = 0; this.extendedScrollBar.Maximum = 1; this.extendedScrollBar.Enabled = false; } else { this.extendedScrollBar.Enabled = true; this.extendedScrollBar.Maximum = (int)this.readerWriterBinary.Dimensions[1].Size - 1 - this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width; } //this.extendedScrollBar.Maximum = (int)this.readerWriterBinary.Dimensions[1].Size - 1 - this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width; } else { this.extendedScrollBar.TimerAmount = 1; this.extendedScrollBar.SmallChange = 1; this.extendedScrollBar.LargeChange = 10; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisEndValue = (float)this.readerWriterBinary.Dimensions[1].End; this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisValueArray = this.readerWriterBinary.Dimensions[1].ElementArray; this.extendedScrollBar.Maximum = (int)this.readerWriterBinary.Dimensions[2].Size; } // setup the colorbar to have the correct values, and set up its axis this.layout2DColorFull.Layout2DColor.ColorbarPanel.SetMinMax(this.readerWriterBinary.Min, this.readerWriterBinary.Max, true); this.layout2DColorFull.Layout2DColor.ColorbarAxisPanel.RightAxisLabel = this.readerWriterBinary.Units; this.layout2DColorFull.Layout2DColor.ColorbarAxisPanel.RightAxisStartValue = (float)this.readerWriterBinary.Min; this.layout2DColorFull.Layout2DColor.ColorbarAxisPanel.RightAxisEndValue = (float)this.readerWriterBinary.Max; this.layout2DColorFull.Layout2DColor.ColorbarAxisPanel.Invalidate(); } private void RefreshViewer(int scrollPosition) { // get new data and send it to the viewer panel this.readerWriterBinary.GetData(ref dataArray, scrollPosition); this.layout2DColorFull.View(dataArray); // we set up the scrollbar to have enough values if (this.readerWriterBinary.Dimensions.Length == 2) { // set new bottom axis values and refresh the axis this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisStartValue = (float)(this.readerWriterBinary.Dimensions[1].Start+scrollPosition*this.dimensionSteps[1]); this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisEndValue = (float)(this.readerWriterBinary.Dimensions[1].Start+(scrollPosition+this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width)*this.dimensionSteps[1]); if (this.readerWriterBinary.Dimensions[1].Size - 1 <= this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width) { this.extendedScrollBar.Value = 0; this.extendedScrollBar.Maximum = 1; this.extendedScrollBar.Enabled = false; } else { this.extendedScrollBar.Enabled = true; this.extendedScrollBar.Maximum = (int)this.readerWriterBinary.Dimensions[1].Size - 1 - this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width; } } else this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.TopAxisLabel = this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.TopAxisLabel.Split(',')[0] + ", " + (this.readerWriterBinary.Dimensions[2].Start + this.dimensionSteps[2]*scrollPosition).ToString("0.00") + " " + this.readerWriterBinary.Dimensions[2].Name; // we need to redraw the axis so that the bottom values change as needed this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.Invalidate(); } #endregion #region Scrollbar and Resize Events private void extendedScrollBar_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) { this.RefreshViewer(e.NewValue); } private void Layout2DColor_Resize(object sender, EventArgs e) { if (this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width > 0) { this.dataArray = new double[this.layout2DColorFull.Layout2DColor.ViewerPanel.ClientSize.Width, this.readerWriterBinary.Dimensions[0].Size]; this.RefreshViewer(this.extendedScrollBar.Value); } } #endregion #region Zoom Code and Events private void ZoomMenuUpdate() { // check the zoom level menu items as needed foreach (MenuItem item in zoomLevelsMenuItem.MenuItems) item.Checked = false; this.zoomLevelsMenuItem.MenuItems[this.fileIndex].Checked = true; // enable or disable the zoom in and zoom out menu items as needed this.zoomInMenuItem.Enabled = this.zoomOutMenuItem.Enabled = true; if (this.zoomLevelsMenuItem.MenuItems[0].Checked) this.zoomInMenuItem.Enabled = false; if (this.zoomLevelsMenuItem.MenuItems[this.zoomLevelsMenuItem.MenuItems.Count-1].Checked) this.zoomOutMenuItem.Enabled = false; } private void ZoomSet(int zoomIndex) { int oldScroll = this.extendedScrollBar.Value; int oldMax = this.extendedScrollBar.Maximum; this.fileIndex = zoomIndex; this.ZoomMenuUpdate(); // try to use downsampled file, and if there is a problem, fail string returnValue = this.SetupFile((string)this.fileTable.Rows[this.fileIndex]["FileName"]); if (returnValue != "0" && this.CriticalError != null) { this.CriticalError(returnValue); return; } this.extendedScrollBar.Value = Math.Max(0, Math.Min(this.extendedScrollBar.Maximum, (int)(oldScroll/(float)oldMax*this.extendedScrollBar.Maximum))); this.RefreshViewer(this.extendedScrollBar.Value); } private void zoomInMenuItem_Click(object sender, System.EventArgs e) { this.ZoomSet(this.fileIndex-1); } private void zoomOutMenuItem_Click(object sender, System.EventArgs e) { this.ZoomSet(this.fileIndex+1); } private void ZoomLevelMenuItem_Clicked(object sender, System.EventArgs e) { if (!((MenuItem)sender).Checked) this.ZoomSet(this.zoomLevelsMenuItem.MenuItems.IndexOf((MenuItem)sender)); } // event and delegate for scroll (see above for use) public event CriticalErrorHandler CriticalError; #endregion #region Properties public MainMenu MainMenu { set { this.mainMenu = value; this.mainMenu.MenuItems.Add(1, this.optionsMenuItem); } } #endregion #region Tool Tip Code private void ViewerPanel_MouseMove(object sender, MouseEventArgs e) { ToolTip toolTip = this.layout2DColorFull.Layout2DColor.ViewerPanel.ToolTip; Point mousePoint = new Point(e.X, e.Y); String tipString; if (e.Button == MouseButtons.None && this.toolTipShow) { EarLab.ReaderWriters.ReaderWriterBinary.Dimension[] dimensions = this.readerWriterBinary.Dimensions; int xIndex, yIndex; double xValue, yValue, zValue=0.0, dValue; dValue = this.layout2DColorFull.Layout2DColor.PointData(mousePoint, out xIndex, out yIndex); if (this.readerWriterBinary.Dimensions[0].ElementArray != null) yValue = this.readerWriterBinary.Dimensions[0].ElementArray[yIndex]; else yValue = this.readerWriterBinary.Dimensions[0].Start + this.dimensionSteps[0]*yIndex; if (this.readerWriterBinary.Dimensions.Length == 2) xValue = this.readerWriterBinary.Dimensions[1].Start + this.dimensionSteps[1]*(xIndex+this.extendedScrollBar.Value); else { if (this.readerWriterBinary.Dimensions[1].ElementArray != null) xValue = this.readerWriterBinary.Dimensions[1].ElementArray[xIndex]; else xValue = this.readerWriterBinary.Dimensions[1].Start + this.dimensionSteps[1]*xIndex; zValue = this.readerWriterBinary.Dimensions[2].Start + this.dimensionSteps[2]*this.extendedScrollBar.Value; } tipString = " Location: " + xValue.ToString(this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.BottomAxisMajorTickNumbersFormat) + ", "; tipString += yValue.ToString(this.layout2DColorFull.Layout2DColor.ViewerAxisPanel.LeftAxisMajorTickNumbersFormat); if (this.readerWriterBinary.Dimensions.Length == 3) tipString += ", " + zValue.ToString("0.00"); tipString += "\nData Value: " + dValue.ToString("0.00e00"); toolTip.SetToolTip((Control)this.layout2DColorFull.Layout2DColor.ViewerPanel, tipString); toolTip.Active = true; } else { // hide the tool tip (it might have been showing toolTip.Active = false; } } private void tipMenuItem_Click(object sender, System.EventArgs e) { if (this.tipMenuItem.Checked) this.tipMenuItem.Checked = this.toolTipShow = false; else this.tipMenuItem.Checked = this.toolTipShow = true; } #endregion #region Save Image Code private void saveMenuItem_Click(object sender, System.EventArgs e) { if (this.saveFileDialog.ShowDialog() == DialogResult.OK) { Application.DoEvents(); Graphics layoutGraphics = this.layout2DColorFull.CreateGraphics(); Bitmap layoutBitmap = new Bitmap(this.layout2DColorFull.ClientSize.Width, this.layout2DColorFull.ClientSize.Height, layoutGraphics); Graphics bitmapGraphics = Graphics.FromImage(layoutBitmap); IntPtr layoutDeviceContext = layoutGraphics.GetHdc(); IntPtr bitmapDeviceContext = bitmapGraphics.GetHdc(); NativeMethods.BitBlt(bitmapDeviceContext, 0, 0, this.layout2DColorFull.ClientSize.Width, this.layout2DColorFull.ClientSize.Height, layoutDeviceContext, 0, 0, 13369376); layoutGraphics.ReleaseHdc(layoutDeviceContext); bitmapGraphics.ReleaseHdc(bitmapDeviceContext); layoutGraphics.Dispose(); bitmapGraphics.Dispose(); System.Drawing.Imaging.ImageFormat imageFormat; switch (saveFileDialog.FilterIndex) { case 2: imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case 3: imageFormat = System.Drawing.Imaging.ImageFormat.Gif; break; case 4: imageFormat = System.Drawing.Imaging.ImageFormat.Png; break; case 5: imageFormat = System.Drawing.Imaging.ImageFormat.Tiff; break; default: imageFormat = System.Drawing.Imaging.ImageFormat.Bmp; break; } layoutBitmap.Save(saveFileDialog.FileName, imageFormat); } } #endregion } }
using System; using System.Diagnostics; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data; namespace Glass.Mapper.Sc.FakeDb.DataMappers { [TestFixture] public class SitecoreFieldDateTimeMapperFixture : AbstractMapperFixture { #region Method - GetField [Test] public void GetField_FieldContainsValidDate_ReturnsDateTime() { //Assign string fieldValue = "20120101T010101"; DateTime expected = new DateTime(2012, 01, 01, 01, 01, 01); var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldDateTimeMapper(); //Act var result = (DateTime) mapper.GetField(field, null, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsValidIsoDate_ReturnsDateTime() { //Assign string fieldValue = "20121101T230000"; DateTime expected = new DateTime(2012, 11, 01, 23, 00, 00); var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldDateTimeMapper(); //Act var result = (DateTime)mapper.GetField(field, null, null); //Assert Assert.AreEqual(expected, result); } [Test] public void SitecoreTimeZoneDemo() { //Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("be-NL"); const string isoDateString = "20151013T220000Z"; const string serverDateString = "20120901T010101"; var serverDateTime = Sitecore.DateUtil.IsoDateToServerTimeIsoDate(isoDateString); var utcDate = Sitecore.DateUtil.IsoDateToUtcIsoDate(isoDateString); Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(utcDate)); var isoDate = Sitecore.DateUtil.IsoDateToDateTime(isoDateString); Console.WriteLine(isoDate); Console.WriteLine(Sitecore.DateUtil.ToServerTime(isoDate)); Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(serverDateTime)); // go the other way Console.WriteLine(Sitecore.DateUtil.ToIsoDate(DateTime.Now)); Console.WriteLine(Sitecore.DateUtil.ToIsoDate(DateTime.UtcNow)); Console.WriteLine(Sitecore.DateUtil.ToIsoDate(DateTime.Now, false, true)); var serverDate = Sitecore.DateUtil.IsoDateToDateTime(serverDateString); Console.WriteLine(serverDate); Console.WriteLine(Sitecore.DateUtil.ToServerTime(serverDate)); Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(serverDateString, DateTime.MinValue, false)); var crappyDate = Sitecore.DateUtil.IsoDateToDateTime(serverDateString, DateTime.MinValue, true); Console.WriteLine(crappyDate); Console.WriteLine(Sitecore.DateUtil.ToServerTime(serverDate)); Console.WriteLine(Sitecore.DateUtil.IsoDateToDateTime(isoDateString, DateTime.MinValue, true)); } [Test] [Ignore("POC only")] public void ConvertTimeToServerTime_using_date_lots() { const string isoDateString = "20151013T220000Z"; Stopwatch sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 1000000; i++) { var isoDate = Sitecore.DateUtil.IsoDateToDateTime(isoDateString); Sitecore.DateUtil.ToServerTime(isoDate); } sw.Stop(); Console.WriteLine(sw.ElapsedTicks); } [Test] [Ignore("POC only")] public void ConvertTimeToServerTime_checking_z_lots() { const string isoDateString = "20151013T220000Z"; const string serverDateString = "20120101T010101"; Stopwatch sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 1000000; i++) { var currentString = i%2 == 1 ? isoDateString : serverDateString; DateTime isoDate = Sitecore.DateUtil.IsoDateToDateTime(currentString); if (currentString.EndsWith("Z", StringComparison.OrdinalIgnoreCase)) { Sitecore.DateUtil.ToServerTime(isoDate); } } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } [Test] [Ignore("POC only")] public void ConvertTimeToServerTime_not_checking_z_lots() { const string isoDateString = "20151013T220000Z"; Stopwatch sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 1000000; i++) { var isoDate = Sitecore.DateUtil.IsoDateToDateTime(isoDateString); Sitecore.DateUtil.ToServerTime(isoDate); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } [Test] [Ignore("POC only")] public void ConvertTimeToServerTime_using_string_lots() { const string isoDateString = "20151013T220000Z"; Stopwatch sw = new Stopwatch(); sw.Start(); for (var i = 0; i < 1000000; i++) { var serverDateTime = Sitecore.DateUtil.IsoDateToServerTimeIsoDate(isoDateString); Sitecore.DateUtil.IsoDateToDateTime(serverDateTime); } sw.Stop(); Console.WriteLine(sw.ElapsedTicks); } #endregion #region Method - SetField [Test] public void SetField_DateTimePassed_SetsFieldValue() { //Assign string expected = "20120101T010101Z"; DateTime objectValue = new DateTime(2012, 01, 01, 01, 01, 01, DateTimeKind.Utc); var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldDateTimeMapper(); item.Editing.BeginEdit(); //Act mapper.SetField(field, objectValue, null, null); //Assert Assert.AreEqual(expected, field.Value); } [Test] public void SetField_NonDateTimePassed_ExceptionThrown() { //Assign string expected = "20120101T010101Z"; int objectValue = 4; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var mapper = new SitecoreFieldDateTimeMapper(); item.Editing.BeginEdit(); //Act Assert.Throws<NotSupportedException>(() => { mapper.SetField(field, objectValue, null, null); }); //Assert } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Vec4 { [TestFixture] public class FloatVec4Test { [Test] public void Constructors() { { var v = new vec4(0.5f); Assert.AreEqual(0.5f, v.x); Assert.AreEqual(0.5f, v.y); Assert.AreEqual(0.5f, v.z); Assert.AreEqual(0.5f, v.w); } { var v = new vec4(7.5f, -4.5f, -3.5f, 2f); Assert.AreEqual(7.5f, v.x); Assert.AreEqual(-4.5f, v.y); Assert.AreEqual(-3.5f, v.z); Assert.AreEqual(2f, v.w); } { var v = new vec4(new vec2(2.5f, -5f)); Assert.AreEqual(2.5f, v.x); Assert.AreEqual(-5f, v.y); Assert.AreEqual(0f, v.z); Assert.AreEqual(0f, v.w); } { var v = new vec4(new vec3(3.5f, -7.5f, -6.5f)); Assert.AreEqual(3.5f, v.x); Assert.AreEqual(-7.5f, v.y); Assert.AreEqual(-6.5f, v.z); Assert.AreEqual(0f, v.w); } { var v = new vec4(new vec4(2.5f, 8f, -9.5f, 0.5f)); Assert.AreEqual(2.5f, v.x); Assert.AreEqual(8f, v.y); Assert.AreEqual(-9.5f, v.z); Assert.AreEqual(0.5f, v.w); } } [Test] public void Indexer() { var v = new vec4(1.5f, -5f, 8f, 2.5f); Assert.AreEqual(1.5f, v[0]); Assert.AreEqual(-5f, v[1]); Assert.AreEqual(8f, v[2]); Assert.AreEqual(2.5f, v[3]); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-2147483648]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[-2147483648] = 0f; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-1]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[-1] = 0f; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[4]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[4] = 0f; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2147483647]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[2147483647] = 0f; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[5]; } ); Assert.Throws<ArgumentOutOfRangeException>(() => { v[5] = 0f; } ); v[1] = 0f; Assert.AreEqual(0f, v[1]); v[1] = 1f; Assert.AreEqual(1f, v[1]); v[3] = 2f; Assert.AreEqual(2f, v[3]); v[3] = 3f; Assert.AreEqual(3f, v[3]); v[0] = 4f; Assert.AreEqual(4f, v[0]); v[3] = 5f; Assert.AreEqual(5f, v[3]); v[0] = 6f; Assert.AreEqual(6f, v[0]); v[2] = 7f; Assert.AreEqual(7f, v[2]); v[1] = 8f; Assert.AreEqual(8f, v[1]); v[1] = 9f; Assert.AreEqual(9f, v[1]); v[0] = -1f; Assert.AreEqual(-1f, v[0]); v[1] = -2f; Assert.AreEqual(-2f, v[1]); v[3] = -3f; Assert.AreEqual(-3f, v[3]); v[0] = -4f; Assert.AreEqual(-4f, v[0]); v[3] = -5f; Assert.AreEqual(-5f, v[3]); v[3] = -6f; Assert.AreEqual(-6f, v[3]); v[0] = -7f; Assert.AreEqual(-7f, v[0]); v[3] = -8f; Assert.AreEqual(-8f, v[3]); v[2] = -9f; Assert.AreEqual(-9f, v[2]); v[2] = -9.5f; Assert.AreEqual(-9.5f, v[2]); v[0] = -8.5f; Assert.AreEqual(-8.5f, v[0]); v[3] = -7.5f; Assert.AreEqual(-7.5f, v[3]); v[0] = -6.5f; Assert.AreEqual(-6.5f, v[0]); v[2] = -5.5f; Assert.AreEqual(-5.5f, v[2]); v[0] = -4.5f; Assert.AreEqual(-4.5f, v[0]); v[1] = -3.5f; Assert.AreEqual(-3.5f, v[1]); v[3] = -2.5f; Assert.AreEqual(-2.5f, v[3]); v[3] = -1.5f; Assert.AreEqual(-1.5f, v[3]); v[0] = -0.5f; Assert.AreEqual(-0.5f, v[0]); v[1] = 0.5f; Assert.AreEqual(0.5f, v[1]); v[2] = 1.5f; Assert.AreEqual(1.5f, v[2]); v[2] = 2.5f; Assert.AreEqual(2.5f, v[2]); v[1] = 3.5f; Assert.AreEqual(3.5f, v[1]); v[3] = 4.5f; Assert.AreEqual(4.5f, v[3]); v[0] = 5.5f; Assert.AreEqual(5.5f, v[0]); v[3] = 6.5f; Assert.AreEqual(6.5f, v[3]); v[1] = 7.5f; Assert.AreEqual(7.5f, v[1]); v[1] = 8.5f; Assert.AreEqual(8.5f, v[1]); v[3] = 9.5f; Assert.AreEqual(9.5f, v[3]); } [Test] public void PropertyValues() { var v = new vec4(-6f, -9.5f, 0f, 5f); var vals = v.Values; Assert.AreEqual(-6f, vals[0]); Assert.AreEqual(-9.5f, vals[1]); Assert.AreEqual(0f, vals[2]); Assert.AreEqual(5f, vals[3]); Assert.That(vals.SequenceEqual(v.ToArray())); } [Test] public void StaticProperties() { Assert.AreEqual(0f, vec4.Zero.x); Assert.AreEqual(0f, vec4.Zero.y); Assert.AreEqual(0f, vec4.Zero.z); Assert.AreEqual(0f, vec4.Zero.w); Assert.AreEqual(1f, vec4.Ones.x); Assert.AreEqual(1f, vec4.Ones.y); Assert.AreEqual(1f, vec4.Ones.z); Assert.AreEqual(1f, vec4.Ones.w); Assert.AreEqual(1f, vec4.UnitX.x); Assert.AreEqual(0f, vec4.UnitX.y); Assert.AreEqual(0f, vec4.UnitX.z); Assert.AreEqual(0f, vec4.UnitX.w); Assert.AreEqual(0f, vec4.UnitY.x); Assert.AreEqual(1f, vec4.UnitY.y); Assert.AreEqual(0f, vec4.UnitY.z); Assert.AreEqual(0f, vec4.UnitY.w); Assert.AreEqual(0f, vec4.UnitZ.x); Assert.AreEqual(0f, vec4.UnitZ.y); Assert.AreEqual(1f, vec4.UnitZ.z); Assert.AreEqual(0f, vec4.UnitZ.w); Assert.AreEqual(0f, vec4.UnitW.x); Assert.AreEqual(0f, vec4.UnitW.y); Assert.AreEqual(0f, vec4.UnitW.z); Assert.AreEqual(1f, vec4.UnitW.w); Assert.AreEqual(float.MaxValue, vec4.MaxValue.x); Assert.AreEqual(float.MaxValue, vec4.MaxValue.y); Assert.AreEqual(float.MaxValue, vec4.MaxValue.z); Assert.AreEqual(float.MaxValue, vec4.MaxValue.w); Assert.AreEqual(float.MinValue, vec4.MinValue.x); Assert.AreEqual(float.MinValue, vec4.MinValue.y); Assert.AreEqual(float.MinValue, vec4.MinValue.z); Assert.AreEqual(float.MinValue, vec4.MinValue.w); Assert.AreEqual(float.Epsilon, vec4.Epsilon.x); Assert.AreEqual(float.Epsilon, vec4.Epsilon.y); Assert.AreEqual(float.Epsilon, vec4.Epsilon.z); Assert.AreEqual(float.Epsilon, vec4.Epsilon.w); Assert.AreEqual(float.NaN, vec4.NaN.x); Assert.AreEqual(float.NaN, vec4.NaN.y); Assert.AreEqual(float.NaN, vec4.NaN.z); Assert.AreEqual(float.NaN, vec4.NaN.w); Assert.AreEqual(float.NegativeInfinity, vec4.NegativeInfinity.x); Assert.AreEqual(float.NegativeInfinity, vec4.NegativeInfinity.y); Assert.AreEqual(float.NegativeInfinity, vec4.NegativeInfinity.z); Assert.AreEqual(float.NegativeInfinity, vec4.NegativeInfinity.w); Assert.AreEqual(float.PositiveInfinity, vec4.PositiveInfinity.x); Assert.AreEqual(float.PositiveInfinity, vec4.PositiveInfinity.y); Assert.AreEqual(float.PositiveInfinity, vec4.PositiveInfinity.z); Assert.AreEqual(float.PositiveInfinity, vec4.PositiveInfinity.w); } [Test] public void Operators() { var v1 = new vec4(-8.5f, -3f, -8.5f, 7.5f); var v2 = new vec4(-8.5f, -3f, -8.5f, 7.5f); var v3 = new vec4(7.5f, -8.5f, -3f, -8.5f); Assert.That(v1 == new vec4(v1)); Assert.That(v2 == new vec4(v2)); Assert.That(v3 == new vec4(v3)); Assert.That(v1 == v2); Assert.That(v1 != v3); Assert.That(v2 != v3); } [Test] public void StringInterop() { var v = new vec4(7f, -5.5f, -8f, 9.5f); var s0 = v.ToString(); var s1 = v.ToString("#"); var v0 = vec4.Parse(s0); var v1 = vec4.Parse(s1, "#"); Assert.AreEqual(v, v0); Assert.AreEqual(v, v1); var b0 = vec4.TryParse(s0, out v0); var b1 = vec4.TryParse(s1, "#", out v1); Assert.That(b0); Assert.That(b1); Assert.AreEqual(v, v0); Assert.AreEqual(v, v1); b0 = vec4.TryParse(null, out v0); Assert.False(b0); b0 = vec4.TryParse("", out v0); Assert.False(b0); b0 = vec4.TryParse(s0 + ", 0", out v0); Assert.False(b0); Assert.Throws<NullReferenceException>(() => { vec4.Parse(null); }); Assert.Throws<FormatException>(() => { vec4.Parse(""); }); Assert.Throws<FormatException>(() => { vec4.Parse(s0 + ", 0"); }); var s2 = v.ToString(";", CultureInfo.InvariantCulture); Assert.That(s2.Length > 0); var s3 = v.ToString("; ", "G"); var s4 = v.ToString("; ", "G", CultureInfo.InvariantCulture); var v3 = vec4.Parse(s3, "; ", NumberStyles.Number); var v4 = vec4.Parse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture); Assert.AreEqual(v, v3); Assert.AreEqual(v, v4); var b4 = vec4.TryParse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture, out v4); Assert.That(b4); Assert.AreEqual(v, v4); } [Test] public void SerializationJson() { var v0 = new vec4(-6f, -3.5f, -9.5f, 9f); var s0 = JsonConvert.SerializeObject(v0); var v1 = JsonConvert.DeserializeObject<vec4>(s0); var s1 = JsonConvert.SerializeObject(v1); Assert.AreEqual(v0, v1); Assert.AreEqual(s0, s1); } [Test] public void InvariantId() { { var v0 = new vec4(4f, 6.5f, -4.5f, -1f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(-0.5f, -1f, -8f, 7.5f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(-1f, -2f, -6.5f, -3.5f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(-1.5f, 0f, 8.5f, -6f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(1.5f, -5.5f, 5.5f, -9.5f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(8.5f, -7f, -5f, 8f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(-2.5f, -0.5f, 0.5f, 5.5f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(0.5f, 3f, 6f, -9.5f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(6f, 1f, -3f, -7f); Assert.AreEqual(v0, +v0); } { var v0 = new vec4(-4f, 2.5f, -1f, -5f); Assert.AreEqual(v0, +v0); } } [Test] public void InvariantDouble() { { var v0 = new vec4(-1.5f, 2.5f, -6f, -2f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(3.5f, -2.5f, 1.5f, 4f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(2f, -3.5f, -1f, -1f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(9.5f, -1f, -5.5f, -5f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(7.5f, 5.5f, -9.5f, -8.5f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(-1f, -3f, 0f, 7f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(2f, 5f, -0.5f, 0f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(8.5f, 2.5f, 2.5f, -8f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(-3f, -0.5f, 2f, 2.5f); Assert.AreEqual(v0 + v0, 2 * v0); } { var v0 = new vec4(-6.5f, -9f, 3.5f, 4f); Assert.AreEqual(v0 + v0, 2 * v0); } } [Test] public void InvariantTriple() { { var v0 = new vec4(4f, 3.5f, 6.5f, 1.5f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(-8f, -3.5f, 0f, -5.5f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(-5f, 5f, 8f, 3f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(8f, -4.5f, -7.5f, -8.5f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(9.5f, 1.5f, -7.5f, 4f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(0.5f, 1.5f, 4f, 1f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(4f, 3f, 9.5f, -7f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(2f, 2.5f, -4f, -2.5f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(7.5f, -1.5f, 8.5f, 1.5f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } { var v0 = new vec4(6f, -4f, 6f, -6.5f); Assert.AreEqual(v0 + v0 + v0, 3 * v0); } } [Test] public void InvariantCommutative() { { var v0 = new vec4(-6f, -4f, -9f, -2.5f); var v1 = new vec4(-8f, -4f, 0.5f, 1.5f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(4f, -0.5f, -0.5f, 6f); var v1 = new vec4(7.5f, 8.5f, -4.5f, 0.5f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(-6f, -4.5f, 5.5f, -9.5f); var v1 = new vec4(8f, 6f, -2f, -2f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(-2f, -4f, -7.5f, 3f); var v1 = new vec4(7.5f, 8.5f, -7.5f, -9f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(-6.5f, -2f, 6.5f, 1.5f); var v1 = new vec4(2f, -8.5f, -4.5f, -2f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(0f, 8f, 2f, 7f); var v1 = new vec4(-3f, -3.5f, 1.5f, 4.5f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(-4.5f, -2.5f, 2.5f, -6.5f); var v1 = new vec4(1.5f, 0f, -0.5f, 8f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(2f, 6f, -6f, 4f); var v1 = new vec4(2.5f, -2.5f, 4.5f, 5f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(6f, -1f, -5.5f, -4.5f); var v1 = new vec4(2f, 4.5f, -2.5f, 4.5f); Assert.AreEqual(v0 * v1, v1 * v0); } { var v0 = new vec4(9.5f, -5.5f, -9f, 0f); var v1 = new vec4(4f, 3f, 8.5f, -3.5f); Assert.AreEqual(v0 * v1, v1 * v0); } } [Test] public void InvariantAssociative() { { var v0 = new vec4(6.5f, 5f, -1f, -9.5f); var v1 = new vec4(5f, 2f, 9f, -5f); var v2 = new vec4(-7f, 8f, -2.5f, 9.5f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(2f, -2f, 0.5f, 3.5f); var v1 = new vec4(4f, 4.5f, -9f, 3f); var v2 = new vec4(9f, 8.5f, 9f, 8.5f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(-6f, 4.5f, -3.5f, -2.5f); var v1 = new vec4(-2.5f, -9.5f, -6f, 9.5f); var v2 = new vec4(7f, 8f, 5.5f, 7f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(4.5f, -7f, -1.5f, -8.5f); var v1 = new vec4(7f, 7.5f, -2.5f, -9f); var v2 = new vec4(3.5f, 5.5f, 1f, 3f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(5f, 6f, -5.5f, -5.5f); var v1 = new vec4(-0.5f, 9.5f, -2f, 7.5f); var v2 = new vec4(5.5f, -2f, 4f, -1f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(-7f, -7.5f, -1.5f, 6.5f); var v1 = new vec4(3.5f, -1.5f, 1.5f, 4.5f); var v2 = new vec4(-7f, -6.5f, 8.5f, -1.5f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(5f, 7.5f, 6.5f, -3f); var v1 = new vec4(-2f, 0.5f, 4f, -9.5f); var v2 = new vec4(3.5f, -7.5f, -7.5f, -9.5f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(6.5f, 1.5f, -1f, 8f); var v1 = new vec4(6.5f, 7.5f, -2f, -6.5f); var v2 = new vec4(-3f, -7f, 4f, -4.5f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(8f, 1.5f, -3.5f, 5f); var v1 = new vec4(3f, 7f, -2.5f, -6.5f); var v2 = new vec4(7f, 6.5f, -9f, 2.5f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } { var v0 = new vec4(2f, 9.5f, -3.5f, 4f); var v1 = new vec4(6f, -5.5f, -8f, 4.5f); var v2 = new vec4(0f, 7f, 9.5f, 1f); Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2); } } [Test] public void InvariantIdNeg() { { var v0 = new vec4(8.5f, 2.5f, 5f, -7f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(-8f, 2.5f, -3.5f, 4f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(-5.5f, 8.5f, -8.5f, -9f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(1.5f, 9.5f, 5f, -4.5f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(0f, 2.5f, 3f, -5.5f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(-9f, -2f, -9.5f, 9f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(3f, 5.5f, 4.5f, 0f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(2f, 5f, -6.5f, -3.5f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(-7f, -1.5f, -5.5f, -1f); Assert.AreEqual(v0, -(-v0)); } { var v0 = new vec4(-9.5f, -4f, 3.5f, 3f); Assert.AreEqual(v0, -(-v0)); } } [Test] public void InvariantCommutativeNeg() { { var v0 = new vec4(3f, -6f, -7.5f, -7.5f); var v1 = new vec4(4.5f, 5.5f, -9.5f, -5f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(-3f, -6.5f, 8f, -7f); var v1 = new vec4(8f, 4f, -5.5f, 0f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(9f, 7f, -9.5f, 3.5f); var v1 = new vec4(-9.5f, 0.5f, -2f, -4.5f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(-7.5f, 1f, 5.5f, 9.5f); var v1 = new vec4(-4.5f, 6f, 8f, -8.5f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(-2f, 6f, 0.5f, 2.5f); var v1 = new vec4(0.5f, 3.5f, 2.5f, -3f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(4.5f, 5.5f, 9.5f, -5f); var v1 = new vec4(-6f, 6f, 3f, -8.5f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(-6.5f, 7f, -8.5f, 5.5f); var v1 = new vec4(2f, -9.5f, 8.5f, -3f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(3f, 6.5f, 0f, 3.5f); var v1 = new vec4(0f, -9.5f, 0.5f, 5f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(-5f, -2.5f, 5f, 2f); var v1 = new vec4(-5f, 2.5f, -1f, -6f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } { var v0 = new vec4(-5f, 7f, 9.5f, -4.5f); var v1 = new vec4(1.5f, 7.5f, 8f, -5f); Assert.AreEqual(v0 - v1, -(v1 - v0)); } } [Test] public void InvariantAssociativeNeg() { { var v0 = new vec4(6.5f, -5.5f, 7f, 2f); var v1 = new vec4(3f, -1.5f, 8f, 6f); var v2 = new vec4(-6f, -5.5f, -4.5f, -2f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(3f, -7.5f, 0f, -7.5f); var v1 = new vec4(5f, -4f, -2.5f, -3f); var v2 = new vec4(6f, 2.5f, -7f, -1.5f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(5.5f, 2f, 5f, 7.5f); var v1 = new vec4(1.5f, 9.5f, 3.5f, 8f); var v2 = new vec4(-7f, 1.5f, 5.5f, -8f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(-9.5f, 6.5f, -9f, 1f); var v1 = new vec4(-9f, -7f, -9f, -4f); var v2 = new vec4(-9f, 3f, 9.5f, -4f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(-6f, 7f, -1.5f, -2f); var v1 = new vec4(0f, -9f, 1f, 4f); var v2 = new vec4(7f, -9.5f, 7f, 1f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(-7.5f, -1f, -5f, -7f); var v1 = new vec4(0.5f, -7f, 4.5f, -2f); var v2 = new vec4(-3.5f, -7.5f, 2f, 8f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(4.5f, -4.5f, 3.5f, 0.5f); var v1 = new vec4(-3f, 2f, 8f, 2.5f); var v2 = new vec4(2f, 2.5f, -7.5f, -6.5f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(-1f, -8.5f, 7f, 8.5f); var v1 = new vec4(-0.5f, 1.5f, 9f, 9.5f); var v2 = new vec4(-0.5f, -8f, -9.5f, 8f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(2f, 2f, -5.5f, 2f); var v1 = new vec4(8f, -2.5f, -2.5f, 3.5f); var v2 = new vec4(5f, -9.5f, -8f, -6f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } { var v0 = new vec4(-4.5f, -2f, 1.5f, 5f); var v1 = new vec4(-2f, -5f, 9.5f, 0.5f); var v2 = new vec4(-1.5f, 2.5f, 5f, 8f); Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2); } } [Test] public void TriangleInequality() { { var v0 = new vec4(0.5f, 3f, 0.5f, 6f); var v1 = new vec4(-6.5f, -6f, -4f, -8.5f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(3.5f, 8f, 7f, -8f); var v1 = new vec4(1f, 1.5f, 9f, 0f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(-4f, -6.5f, -7.5f, 1.5f); var v1 = new vec4(8f, -5f, 3f, -7.5f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(1.5f, 8f, -7f, 3f); var v1 = new vec4(-8.5f, -3f, 3f, 2.5f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(1.5f, -2.5f, -9.5f, 5f); var v1 = new vec4(4f, -3f, -1.5f, 5f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(6.5f, 8.5f, 1f, -7f); var v1 = new vec4(-6f, -5.5f, -6.5f, -8f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(-3.5f, 6.5f, 8f, -8f); var v1 = new vec4(-7.5f, 8f, -2.5f, -5f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(9.5f, 8f, -6f, -5f); var v1 = new vec4(8.5f, 9f, 0f, -8.5f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(4f, -6f, -3.5f, -5f); var v1 = new vec4(-1f, 4f, 6.5f, 1f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } { var v0 = new vec4(4.5f, -6f, 4.5f, 9f); var v1 = new vec4(-4f, -2.5f, 5f, 6f); Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax); } } [Test] public void InvariantNorm() { { var v0 = new vec4(-7f, 3f, 0f, -3f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(-9f, 0f, -6f, 7f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(-5f, -9f, -0.5f, -7.5f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(-1f, 6.5f, -6.5f, -1f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(4.5f, -9f, 6f, 7.5f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(6f, 5f, -7.5f, -1.5f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(-3.5f, 2f, -5.5f, -5f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(5f, 3.5f, 3.5f, 0.5f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(-2.5f, 3f, 6f, -9f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } { var v0 = new vec4(4.5f, -5.5f, 4f, 7f); Assert.LessOrEqual(v0.NormMax, v0.Norm); } } [Test] public void RandomUniform0() { var random = new Random(1862401202); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.Random(random, -2, 1); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, -0.5, 1.0); Assert.AreEqual(avg.y, -0.5, 1.0); Assert.AreEqual(avg.z, -0.5, 1.0); Assert.AreEqual(avg.w, -0.5, 1.0); Assert.AreEqual(variance.x, 0.75, 3.0); Assert.AreEqual(variance.y, 0.75, 3.0); Assert.AreEqual(variance.z, 0.75, 3.0); Assert.AreEqual(variance.w, 0.75, 3.0); } [Test] public void RandomUniform1() { var random = new Random(1143833200); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomUniform(random, 3, 5); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 4, 1.0); Assert.AreEqual(avg.y, 4, 1.0); Assert.AreEqual(avg.z, 4, 1.0); Assert.AreEqual(avg.w, 4, 1.0); Assert.AreEqual(variance.x, 0.333333333333333, 3.0); Assert.AreEqual(variance.y, 0.333333333333333, 3.0); Assert.AreEqual(variance.z, 0.333333333333333, 3.0); Assert.AreEqual(variance.w, 0.333333333333333, 3.0); } [Test] public void RandomUniform2() { var random = new Random(425265198); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.Random(random, -2, -1); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, -1.5, 1.0); Assert.AreEqual(avg.y, -1.5, 1.0); Assert.AreEqual(avg.z, -1.5, 1.0); Assert.AreEqual(avg.w, -1.5, 1.0); Assert.AreEqual(variance.x, 0.0833333333333333, 3.0); Assert.AreEqual(variance.y, 0.0833333333333333, 3.0); Assert.AreEqual(variance.z, 0.0833333333333333, 3.0); Assert.AreEqual(variance.w, 0.0833333333333333, 3.0); } [Test] public void RandomUniform3() { var random = new Random(1854180843); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomUniform(random, 3, 4); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 3.5, 1.0); Assert.AreEqual(avg.y, 3.5, 1.0); Assert.AreEqual(avg.z, 3.5, 1.0); Assert.AreEqual(avg.w, 3.5, 1.0); Assert.AreEqual(variance.x, 0.0833333333333333, 3.0); Assert.AreEqual(variance.y, 0.0833333333333333, 3.0); Assert.AreEqual(variance.z, 0.0833333333333333, 3.0); Assert.AreEqual(variance.w, 0.0833333333333333, 3.0); } [Test] public void RandomUniform4() { var random = new Random(441705916); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.Random(random, -2, 2); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0, 1.0); Assert.AreEqual(avg.y, 0, 1.0); Assert.AreEqual(avg.z, 0, 1.0); Assert.AreEqual(avg.w, 0, 1.0); Assert.AreEqual(variance.x, 1.33333333333333, 3.0); Assert.AreEqual(variance.y, 1.33333333333333, 3.0); Assert.AreEqual(variance.z, 1.33333333333333, 3.0); Assert.AreEqual(variance.w, 1.33333333333333, 3.0); } [Test] public void RandomGaussian0() { var random = new Random(2005409173); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random, 1.79478494999687f, 7.95614184250875f); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.79478494999687, 1.0); Assert.AreEqual(avg.y, 1.79478494999687, 1.0); Assert.AreEqual(avg.z, 1.79478494999687, 1.0); Assert.AreEqual(avg.w, 1.79478494999687, 1.0); Assert.AreEqual(variance.x, 7.95614184250875, 3.0); Assert.AreEqual(variance.y, 7.95614184250875, 3.0); Assert.AreEqual(variance.z, 7.95614184250875, 3.0); Assert.AreEqual(variance.w, 7.95614184250875, 3.0); } [Test] public void RandomGaussian1() { var random = new Random(1374422296); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomGaussian(random, 1.18552753105086f, 2.13010051852562f); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.18552753105086, 1.0); Assert.AreEqual(avg.y, 1.18552753105086, 1.0); Assert.AreEqual(avg.z, 1.18552753105086, 1.0); Assert.AreEqual(avg.w, 1.18552753105086, 1.0); Assert.AreEqual(variance.x, 2.13010051852562, 3.0); Assert.AreEqual(variance.y, 2.13010051852562, 3.0); Assert.AreEqual(variance.z, 2.13010051852562, 3.0); Assert.AreEqual(variance.w, 2.13010051852562, 3.0); } [Test] public void RandomGaussian2() { var random = new Random(785133147); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random, -0.292426896417712f, 8.82208540980801f); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, -0.292426896417712, 1.0); Assert.AreEqual(avg.y, -0.292426896417712, 1.0); Assert.AreEqual(avg.z, -0.292426896417712, 1.0); Assert.AreEqual(avg.w, -0.292426896417712, 1.0); Assert.AreEqual(variance.x, 8.82208540980801, 3.0); Assert.AreEqual(variance.y, 8.82208540980801, 3.0); Assert.AreEqual(variance.z, 8.82208540980801, 3.0); Assert.AreEqual(variance.w, 8.82208540980801, 3.0); } [Test] public void RandomGaussian3() { var random = new Random(949457533); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomGaussian(random, 1.33877771130706f, 0.00640877522826603f); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.33877771130706, 1.0); Assert.AreEqual(avg.y, 1.33877771130706, 1.0); Assert.AreEqual(avg.z, 1.33877771130706, 1.0); Assert.AreEqual(avg.w, 1.33877771130706, 1.0); Assert.AreEqual(variance.x, 0.00640877522826603, 3.0); Assert.AreEqual(variance.y, 0.00640877522826603, 3.0); Assert.AreEqual(variance.z, 0.00640877522826603, 3.0); Assert.AreEqual(variance.w, 0.00640877522826603, 3.0); } [Test] public void RandomGaussian4() { var random = new Random(1963711445); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random, 1.34592652849198f, 1.61838102229795f); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 1.34592652849198, 1.0); Assert.AreEqual(avg.y, 1.34592652849198, 1.0); Assert.AreEqual(avg.z, 1.34592652849198, 1.0); Assert.AreEqual(avg.w, 1.34592652849198, 1.0); Assert.AreEqual(variance.x, 1.61838102229795, 3.0); Assert.AreEqual(variance.y, 1.61838102229795, 3.0); Assert.AreEqual(variance.z, 1.61838102229795, 3.0); Assert.AreEqual(variance.w, 1.61838102229795, 3.0); } [Test] public void RandomNormal0() { var random = new Random(385671755); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0, 1.0); Assert.AreEqual(avg.y, 0, 1.0); Assert.AreEqual(avg.z, 0, 1.0); Assert.AreEqual(avg.w, 0, 1.0); Assert.AreEqual(variance.x, 1, 3.0); Assert.AreEqual(variance.y, 1, 3.0); Assert.AreEqual(variance.z, 1, 3.0); Assert.AreEqual(variance.w, 1, 3.0); } [Test] public void RandomNormal1() { var random = new Random(1411255583); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0, 1.0); Assert.AreEqual(avg.y, 0, 1.0); Assert.AreEqual(avg.z, 0, 1.0); Assert.AreEqual(avg.w, 0, 1.0); Assert.AreEqual(variance.x, 1, 3.0); Assert.AreEqual(variance.y, 1, 3.0); Assert.AreEqual(variance.z, 1, 3.0); Assert.AreEqual(variance.w, 1, 3.0); } [Test] public void RandomNormal2() { var random = new Random(289355764); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0, 1.0); Assert.AreEqual(avg.y, 0, 1.0); Assert.AreEqual(avg.z, 0, 1.0); Assert.AreEqual(avg.w, 0, 1.0); Assert.AreEqual(variance.x, 1, 3.0); Assert.AreEqual(variance.y, 1, 3.0); Assert.AreEqual(variance.z, 1, 3.0); Assert.AreEqual(variance.w, 1, 3.0); } [Test] public void RandomNormal3() { var random = new Random(1314939592); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0, 1.0); Assert.AreEqual(avg.y, 0, 1.0); Assert.AreEqual(avg.z, 0, 1.0); Assert.AreEqual(avg.w, 0, 1.0); Assert.AreEqual(variance.x, 1, 3.0); Assert.AreEqual(variance.y, 1, 3.0); Assert.AreEqual(variance.z, 1, 3.0); Assert.AreEqual(variance.w, 1, 3.0); } [Test] public void RandomNormal4() { var random = new Random(578303737); var sum = new dvec4(0.0); var sumSqr = new dvec4(0.0); const int count = 50000; for (var _ = 0; _ < count; ++_) { var v = vec4.RandomNormal(random); sum += (dvec4)v; sumSqr += glm.Pow2((dvec4)v); } var avg = sum / (double)count; var variance = sumSqr / (double)count - avg * avg; Assert.AreEqual(avg.x, 0, 1.0); Assert.AreEqual(avg.y, 0, 1.0); Assert.AreEqual(avg.z, 0, 1.0); Assert.AreEqual(avg.w, 0, 1.0); Assert.AreEqual(variance.x, 1, 3.0); Assert.AreEqual(variance.y, 1, 3.0); Assert.AreEqual(variance.z, 1, 3.0); Assert.AreEqual(variance.w, 1, 3.0); } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using MindTouch.Data; using MindTouch.Dream; namespace MindTouch.Deki.Data.MySql { public partial class MySqlDekiDataSession { // -- Types -- public enum VisibilityFilter : int { ANY = -1, VISIBLEONLY = 0, HIDDENONLY = 1 } private class ResourceQuery { // -- Types -- private class State { // -- Fields -- public ResourceBE resourceBE; public DeletionFilter resourceDeletionFilter; public IList<uint> resourceIds; public IList<string> nameFilter; public IList<uint> parentIds; public ResourceBE.Type parentType; public IList<ResourceBE.Type> resourceTypes; public IList<uint> changeSetId; public ResourceBE.ChangeOperations changeType; public VisibilityFilter revisionVisibilityFilter; public bool populateResourceCountOnly; public bool populateContent; public bool populateRevisions; public bool populateChildResources; public bool populateChildResourcesForRev; public ResourceOrderClause[] orderClauses; public uint? limit; public uint? offset; // -- Constructors -- public State() { resourceBE = ResourceBE.New(ResourceBE.Type.UNDEFINED); resourceDeletionFilter = DeletionFilter.ANY; revisionVisibilityFilter = VisibilityFilter.ANY; resourceIds = null; nameFilter = null; parentIds = null; parentType = ResourceBE.Type.UNDEFINED; resourceTypes = null; changeSetId = null; changeType = ResourceBE.ChangeOperations.UNDEFINED; populateResourceCountOnly = false; populateContent = true; populateRevisions = false; populateChildResourcesForRev = false; populateChildResources = false; orderClauses = null; limit = null; offset = null; } public State(State s) { resourceBE = ResourceBE.NewFrom(s.resourceBE); resourceDeletionFilter = s.resourceDeletionFilter; revisionVisibilityFilter = s.revisionVisibilityFilter; populateContent = s.populateContent; populateRevisions = s.populateRevisions; populateChildResources = s.populateChildResources; populateChildResourcesForRev = s.populateChildResourcesForRev; populateResourceCountOnly = s.populateResourceCountOnly; parentType = s.parentType; if(!ArrayUtil.IsNullOrEmpty(s.resourceIds)) { resourceIds = new List<uint>(s.resourceIds); } if(!ArrayUtil.IsNullOrEmpty(s.parentIds)) { parentIds = new List<uint>(s.parentIds); } if(!ArrayUtil.IsNullOrEmpty(s.resourceTypes)) { resourceTypes = new List<ResourceBE.Type>(s.resourceTypes); } if(!ArrayUtil.IsNullOrEmpty(s.nameFilter)) { nameFilter = new List<string>(s.nameFilter); } if(!ArrayUtil.IsNullOrEmpty(s.orderClauses)) { orderClauses = (ResourceOrderClause[]) s.orderClauses.Clone(); } if(!ArrayUtil.IsNullOrEmpty(s.changeSetId)) { changeSetId = new List<uint>(s.changeSetId).ToArray(); } changeType = s.changeType; limit = s.limit; offset = s.offset; } } public struct ResourceOrderClause { public enum SortTable { UNDEFINED, RESOURCES, RESOURCEREVISIONS } // -- Fields public SortDirection dir; public string column; public SortTable table; } // -- Fields -- State _state; // -- Constructors -- public ResourceQuery() { _state = new State(); } private ResourceQuery(State s) { _state = new State(s); } // -- Methods -- #region Filter columns public ResourceQuery WithResourceId(uint resourceId) { return WithResourceId(new uint[] { resourceId }); } public ResourceQuery WithResourceId(uint[] resourceIds) { State s = new State(_state); s.resourceIds = resourceIds; return new ResourceQuery(s); } public ResourceQuery WithChangeSetIds(uint changeSetId) { return WithChangeSetIds(new uint[] { changeSetId }); } public ResourceQuery WithChangeSetIds(uint[] changeSetIds) { State s = new State(_state); s.changeSetId = changeSetIds; return new ResourceQuery(s); } public ResourceQuery WithResourceType(ResourceBE.Type resourceType) { return WithResourceType(new ResourceBE.Type[] { resourceType }); } public ResourceQuery WithResourceType(IList<ResourceBE.Type> resourceTypes) { State s = new State(_state); s.resourceTypes = resourceTypes; return new ResourceQuery(s); } public ResourceQuery WithChangeType(ResourceBE.ChangeOperations changeType) { State s = new State(_state); s.changeType = changeType; return new ResourceQuery(s); } public ResourceQuery WithRevision(int? revision) { State s = new State(_state); s.resourceBE.Revision = revision ?? ResourceBE.HEADREVISION; s.populateRevisions = (revision ?? ResourceBE.HEADREVISION) != ResourceBE.HEADREVISION; return new ResourceQuery(s); } public ResourceQuery WithParent(uint? parentId, ResourceBE.Type parentType) { if(parentId == null) { return WithParent(new uint[] { }, parentType); } else { return WithParent(new uint[] { parentId.Value }, parentType); } } public ResourceQuery WithParent(IList<uint> parentIds, ResourceBE.Type parentType) { State s = new State(_state); s.parentIds = parentIds; s.parentType = parentType; return new ResourceQuery(s); } public ResourceQuery WithDeletionFilter(DeletionFilter deletionFilter) { State s = new State(_state); s.resourceDeletionFilter = deletionFilter; return new ResourceQuery(s); } public ResourceQuery WithNames(IList<string> names) { State s = new State(_state); s.nameFilter = names; return new ResourceQuery(s); } #endregion public ResourceQuery IncludeContent(bool populateContent) { State s = new State(_state); s.populateContent = populateContent; return new ResourceQuery(s); } public ResourceQuery IncludeRevisions(bool populateRevisions) { State s = new State(_state); s.populateRevisions = populateRevisions; return new ResourceQuery(s); } public ResourceQuery IncludeChildResources(bool populateChildResources) { State s = new State(_state); s.populateChildResources = populateChildResources; return new ResourceQuery(s); } public ResourceQuery IncludeChildResourcesForRev(bool populateChildResourcesForRev) { State s = new State(_state); s.populateChildResourcesForRev = populateChildResourcesForRev; return new ResourceQuery(s); } protected ResourceQuery IncludeResourceCountOnly(bool countResourcesOnly) { State s = new State(_state); s.populateResourceCountOnly = countResourcesOnly; if(countResourcesOnly) { s.populateContent = false; } return new ResourceQuery(s); } public ResourceQuery OrderBy(ResourceOrderClause.SortTable table, string column, SortDirection direction) { State s = new State(_state); ResourceOrderClause roc = new ResourceOrderClause(); roc.table = table; roc.column = column; roc.dir = direction; if(s.orderClauses == null) { s.orderClauses = new ResourceOrderClause[] { roc }; } else { List<ResourceOrderClause> temp = new List<ResourceOrderClause>(s.orderClauses); temp.Add(roc); s.orderClauses = temp.ToArray(); } return new ResourceQuery(s); } public ResourceQuery Limit(uint? limit) { State s = new State(_state); s.limit = limit; return new ResourceQuery(s); } public ResourceQuery Offset(uint? offset) { State s = new State(_state); s.offset = offset; return new ResourceQuery(s); } #region Query building and execution public override string ToString() { return ToString(string.Empty); } public string ToString(string methodName) { StringBuilder querySb = new StringBuilder(); const string RESOURCE_ALIAS = "r"; const string RREVISION_ALIAS = "rr"; const string RESOURCECONTENTS_ALIAS = "rc"; string queryColumnAlias = _state.populateRevisions ? RREVISION_ALIAS : RESOURCE_ALIAS; //Query Header if(!string.IsNullOrEmpty(methodName)) { querySb.AppendFormat(" /* Resources::{0} */", methodName); } //Columns if(!_state.populateResourceCountOnly) { querySb.AppendFormat("\n SELECT {0}", GetColumns(queryColumnAlias)); if(_state.populateContent) { querySb.AppendFormat(", {0}.*", RESOURCECONTENTS_ALIAS); } } else { querySb.AppendFormat("\n SELECT count(*)"); } //Main table querySb.AppendFormat("\n FROM resources {0}", RESOURCE_ALIAS); //Joins if(_state.populateRevisions) { querySb.AppendFormat("\n JOIN resourcerevs {0}\n\t ON {1}.res_id = {0}.resrev_res_id", RREVISION_ALIAS, RESOURCE_ALIAS); } if(_state.populateContent) { querySb.AppendFormat("\n LEFT JOIN resourcecontents {0}\n\t ON {1}.resrev_content_id = {0}.rescontent_id", RESOURCECONTENTS_ALIAS, queryColumnAlias); } //Where clauses querySb.AppendFormat("\n WHERE 1=1"); if(!ArrayUtil.IsNullOrEmpty(_state.resourceIds)) { string resourceIdsStr = string.Join(",", DbUtils.ConvertArrayToDelimittedString<uint>(',', _state.resourceIds)); querySb.AppendFormat("\n AND {0}.res_id in ({1})", RESOURCE_ALIAS, resourceIdsStr); } if(!ArrayUtil.IsNullOrEmpty(_state.changeSetId)) { string transactionIdsStr = string.Join(",", DbUtils.ConvertArrayToDelimittedString<uint>(',', _state.changeSetId)); querySb.AppendFormat("\n AND {0}.resrev_changeset_id in ({1})", RESOURCE_ALIAS, transactionIdsStr); } if(_state.resourceDeletionFilter != DeletionFilter.ANY) { querySb.AppendFormat("\n AND {0}.res_deleted = {1}", RESOURCE_ALIAS, (int) _state.resourceDeletionFilter); } if(!ArrayUtil.IsNullOrEmpty(_state.resourceTypes)) { byte[] tempTypes = Array.ConvertAll<ResourceBE.Type, byte>(_state.resourceTypes.ToArray(), new Converter<ResourceBE.Type, byte>(delegate(ResourceBE.Type t) { return (byte) t; })); string resourceTypesStr = string.Join(",", DbUtils.ConvertArrayToDelimittedString<byte>(',', tempTypes)); querySb.AppendFormat("\n AND {0}.res_type in ({1})", RESOURCE_ALIAS, resourceTypesStr); } if(_state.changeType != ResourceBE.ChangeOperations.UNDEFINED) { querySb.Append("\n AND ( "); bool firstChange = true; foreach(ResourceBE.ChangeOperations c in Enum.GetValues(typeof(ResourceBE.ChangeOperations))) { if((_state.changeType & c) == c && c != ResourceBE.ChangeOperations.UNDEFINED) { if(!firstChange) { querySb.Append(" OR "); } querySb.AppendFormat("{0}.resrev_change_mask & {1} = {1}", queryColumnAlias, (ushort) c); firstChange = false; } } querySb.Append(")"); } if(_state.resourceBE.Revision != ResourceBE.HEADREVISION) { if(_state.resourceBE.Revision > ResourceBE.HEADREVISION) { querySb.AppendFormat("\n AND {0}.resrev_rev = {1}", RREVISION_ALIAS, _state.resourceBE.Revision); } else if(_state.resourceBE.Revision < ResourceBE.HEADREVISION) { querySb.AppendFormat("\n AND {0}.resrev_rev = {1}.res_headrev - {2}", RREVISION_ALIAS, RESOURCE_ALIAS, Math.Abs(_state.resourceBE.Revision)); } } if(_state.parentType != ResourceBE.Type.UNDEFINED || !ArrayUtil.IsNullOrEmpty(_state.parentIds)) { string parentIdsStr = (ArrayUtil.IsNullOrEmpty(_state.parentIds) ? "NULL" : string.Join(",", DbUtils.ConvertArrayToDelimittedString<uint>(',', _state.parentIds))); switch(_state.parentType) { case ResourceBE.Type.PAGE: querySb.AppendFormat("\n AND {0}.resrev_parent_page_id in ({1})", RESOURCE_ALIAS, parentIdsStr); break; case ResourceBE.Type.USER: querySb.AppendFormat("\n AND {0}.resrev_parent_user_id in ({1})", RESOURCE_ALIAS, parentIdsStr); break; case ResourceBE.Type.SITE: //SITE resources always have a parent_id=null, parent_user_id=null, parent_page_id=null querySb.AppendFormat("\n AND {0}.resrev_parent_id is null", RESOURCE_ALIAS); querySb.AppendFormat("\n AND {0}.resrev_parent_page_id is null", RESOURCE_ALIAS); querySb.AppendFormat("\n AND {0}.resrev_parent_user_id is null", RESOURCE_ALIAS); break; default: querySb.AppendFormat("\n AND {0}.resrev_parent_id in ({1})", RESOURCE_ALIAS, parentIdsStr); break; } } if(!ArrayUtil.IsNullOrEmpty(_state.nameFilter)) { querySb.Append("\n " + BuildNameFilterWhereClause(_state.nameFilter, RESOURCE_ALIAS)); } //Sort if(!ArrayUtil.IsNullOrEmpty(_state.orderClauses)) { StringBuilder orderList = new StringBuilder(); for(int i = 0; i < _state.orderClauses.Length; i++) { ResourceOrderClause roc = _state.orderClauses[i]; if(i > 0) { orderList.Append(","); } string tableAlias = string.Empty; switch(roc.table) { case ResourceOrderClause.SortTable.RESOURCES: tableAlias = RESOURCE_ALIAS + "."; break; case ResourceOrderClause.SortTable.RESOURCEREVISIONS: tableAlias = RREVISION_ALIAS + "."; break; } orderList.AppendFormat("{0}{1} {2}", tableAlias, roc.column, roc.dir.ToString()); } querySb.AppendFormat("\n ORDER BY {0}", orderList); } //Limit+offset uint? limit = _state.limit; if(limit == null && _state.offset != null) { limit = uint.MaxValue; } if(limit != null) { querySb.AppendFormat("\n LIMIT {0}", limit); } if(_state.offset != null) { querySb.AppendFormat("\n OFFSET {0}", _state.offset.Value); } //Child resources if(_state.populateChildResources || _state.populateChildResourcesForRev) { } return querySb.ToString(); } private string GetColumns(string revisionTablePrefix) { return string.Format( @"res_id,res_headrev,res_type,res_deleted,res_create_timestamp,res_update_timestamp,res_create_user_id,res_update_user_id, {0}resrev_rev,{0}resrev_user_id,{0}resrev_parent_id,{0}resrev_parent_page_id,{0}resrev_parent_page_id,{0}resrev_parent_user_id,{0}resrev_change_mask,{0}resrev_name,{0}resrev_change_description,{0}resrev_timestamp,{0}resrev_content_id,{0}resrev_deleted,{0}resrev_changeset_id,{0}resrev_size,{0}resrev_mimetype,{0}resrev_language,{0}resrev_is_hidden,{0}resrev_meta", string.IsNullOrEmpty(revisionTablePrefix) ? string.Empty : revisionTablePrefix + "."); } private static string BuildNameFilterWhereClause(IList<string> names, string tableAlias) { /* AND ( name in (1,2,3) OR name like %4% OR name like %5% ) */ StringBuilder nameSpecificQuery = new StringBuilder(); StringBuilder nameSubstringQuery = new StringBuilder(); if(!ArrayUtil.IsNullOrEmpty(names)) { for(int i = 0; i < names.Count; i++) { if(!names[i].Contains('*')) { if(nameSpecificQuery.Length == 0) { nameSpecificQuery.AppendFormat("{0}.resrev_name in (", tableAlias); } else { nameSpecificQuery.Append(i > 0 ? "," : string.Empty); } nameSpecificQuery.AppendFormat("'{0}'", DataCommand.MakeSqlSafe(names[i])); } else { //Change the name into a mysql substring expression string nameExpression = DataCommand.MakeSqlSafe(names[i]); if(nameExpression.StartsWith("*", StringComparison.InvariantCultureIgnoreCase)) { nameExpression = nameExpression.TrimStart('*').Insert(0, "%"); } if(nameExpression.EndsWith("*", StringComparison.InvariantCultureIgnoreCase)) { nameExpression = nameExpression.TrimEnd('*') + '%'; } if(nameSubstringQuery.Length > 0) { nameSubstringQuery.Append(" OR "); } nameSubstringQuery.AppendFormat(" {0}.resrev_name like \"{1}\"", tableAlias, nameExpression); } } if(nameSpecificQuery.Length > 0) { nameSpecificQuery.Append(")"); } } string ret = string.Empty; if(nameSpecificQuery.Length > 0 || nameSubstringQuery.Length > 0) { ret = string.Format(" AND ({0} {1} {2})", nameSpecificQuery.ToString(), (nameSpecificQuery.Length > 0 && nameSubstringQuery.Length > 0) ? "OR" : string.Empty, nameSubstringQuery.ToString()); } return ret; } public List<ResourceBE> SelectList(DataCatalog dbCatalog, string methodName) { List<ResourceBE> ret = new List<ResourceBE>(); string q = ToString(methodName); dbCatalog.NewQuery(q) .Execute(delegate(IDataReader dr) { while(dr.Read()) { ret.Add(Resources_Populate(dr)); } }); return ret; } public ResourceBE Select(DataCatalog dbCatalog, string methodName) { List<ResourceBE> ret = SelectList(dbCatalog, methodName); return ArrayUtil.IsNullOrEmpty(ret) ? null : ret[0]; } public uint? SelectCount(DataCatalog dbCatalog, string methodName) { ResourceQuery countRQ = IncludeResourceCountOnly(true); string q = countRQ.ToString(methodName + "(count only)"); return dbCatalog.NewQuery(q).ReadAsUInt(); } #endregion } // -- Methods -- #region SELECT Resources public IList<ResourceBE> Resources_GetByIds(params uint[] resourceIds) { return new ResourceQuery() .WithResourceId(resourceIds) .SelectList(Catalog, "Resources_GetByIds"); } public ResourceBE Resources_GetByIdAndRevision(uint resourceid, int revision) { return new ResourceQuery() .WithResourceId(resourceid) .WithRevision(revision) .Select(Catalog, string.Format("Resources_GetByIdAndRevision (rev: {0})", revision)); } public IList<ResourceBE> Resources_GetByQuery(IList<uint> parentIds, ResourceBE.Type parentType, IList<ResourceBE.Type> resourceTypes, IList<string> names, DeletionFilter deletionStateFilter, bool? populateRevisions, uint? offset, uint? limit) { ResourceQuery rq = new ResourceQuery(); rq = rq.WithParent(parentIds, parentType); rq = rq.WithResourceType(resourceTypes); rq = rq.WithNames(names); rq = rq.WithDeletionFilter(deletionStateFilter); rq = rq.IncludeRevisions(populateRevisions ?? false); rq = rq.Limit(limit); rq = rq.Offset(offset); rq = rq.OrderBy(ResourceQuery.ResourceOrderClause.SortTable.RESOURCES, "res_id", SortDirection.ASC); return rq.SelectList(Catalog, "Resources_Get"); } public IList<ResourceBE> Resources_GetRevisions(uint resourceId, ResourceBE.ChangeOperations changeTypesFilter, SortDirection sortRevisions, uint? limit) { return new ResourceQuery() .WithResourceId(resourceId) .WithChangeType(changeTypesFilter) .IncludeRevisions(true) .OrderBy(ResourceQuery.ResourceOrderClause.SortTable.RESOURCEREVISIONS, "resrev_rev", sortRevisions) .Limit(limit) .SelectList(Catalog, "Resources_GetRevisions"); } public IList<ResourceBE> Resources_GetByChangeSet(uint changeSetId, ResourceBE.Type resourceType) { if(changeSetId == 0) { return new List<ResourceBE>(); } return new ResourceQuery() .WithChangeSetIds(changeSetId) .WithResourceType(resourceType) .SelectList(Catalog, "Resources_GetByChangeSet"); } public Dictionary<Title, AttachmentBE> Resources_GetFileResourcesByTitlesWithMangling(IList<Title> fileTitles) { //A specialized query that retrieves file resources from titles. This is only used from DekiXmlParser.ConvertFileLinks Dictionary<Title, AttachmentBE> ret = new Dictionary<Title, AttachmentBE>(); if(ArrayUtil.IsNullOrEmpty(fileTitles)) { return ret; } string query = @" /* Resources_GetFileResourcesByTitlesWithMangling */ select resources.*, resourcecontents.*, pages.page_id, pages.page_namespace, pages.page_title, pages.page_display_name from pages join resources on resrev_parent_page_id = page_id left join resourcecontents on resources.resrev_content_id = resourcecontents.rescontent_id where res_type = 2 AND res_deleted = 0 AND( {0} ) "; StringBuilder whereQuery = new StringBuilder(); for(int i = 0; i < fileTitles.Count; i++) { if(i > 0) { whereQuery.Append("\n OR "); } whereQuery.AppendFormat("(pages.page_namespace={0} AND pages.page_title='{1}' AND REPLACE(resources.resrev_name, ' ', '_') = REPLACE('{2}', ' ', '_'))", (uint) fileTitles[i].Namespace, DataCommand.MakeSqlSafe(fileTitles[i].AsUnprefixedDbPath()), DataCommand.MakeSqlSafe(fileTitles[i].Filename)); } query = string.Format(query, whereQuery); Catalog.NewQuery(query.ToString()).Execute(delegate(IDataReader dr) { while(dr.Read()) { Title title = DbUtils.TitleFromDataReader(dr, "page_namespace", "page_title", "page_display_name", "resrev_name"); AttachmentBE r = Resources_Populate(dr) as AttachmentBE; if(r != null) { ret[title] = r; } } }); return ret; } #endregion #region Count Resources public uint Resources_GetRevisionCount(uint resourceId, ResourceBE.ChangeOperations changeTypesFilter) { return new ResourceQuery() .WithResourceId(resourceId) .WithChangeType(changeTypesFilter) .IncludeRevisions(true) .SelectCount(Catalog, "Resources_GetRevisionCount") ?? 0; } #endregion public ResourceBE Resources_SaveRevision(ResourceBE resource) { string query = string.Empty; string contentUpdateQuery = string.Empty; bool contentUpdated = false; if(resource.Content != null && resource.Content.IsNewContent()){ contentUpdated = true; ResourceContentBE content = Resources_ContentInsert(resource.Content); resource.Content = content; resource.ContentId = content.ContentId; } if(resource.IsNewResource()) { query = @" /* Resources_SaveRevision (new resource) */ set @resourceid = 0; insert into resources set res_headrev = ?RES_HEADREV, res_type = ?RES_TYPE, res_deleted = ?RES_DELETED, res_create_timestamp = ?RES_CREATE_TIMESTAMP, res_update_timestamp = ?RES_UPDATE_TIMESTAMP, res_create_user_id = ?RES_CREATE_USER_ID, res_update_user_id = ?RES_UPDATE_USER_ID, resrev_rev = ?RESREV_REV, resrev_user_id = ?RESREV_USER_ID, resrev_parent_id = ?RESREV_PARENT_ID, resrev_parent_page_id = ?RESREV_PARENT_PAGE_ID, resrev_parent_user_id = ?RESREV_PARENT_USER_ID, resrev_change_mask = ?RESREV_CHANGE_MASK, resrev_name = ?RESREV_NAME, resrev_change_description = ?RESREV_CHANGE_DESCRIPTION, resrev_timestamp = ?RESREV_TIMESTAMP, resrev_content_id = ?RESREV_CONTENT_ID, resrev_deleted = ?RESREV_DELETED, resrev_changeset_id = ?RESREV_CHANGESET_ID, resrev_size = ?RESREV_SIZE, resrev_mimetype = ?RESREV_MIMETYPE, resrev_language = ?RESREV_LANGUAGE, resrev_is_hidden = ?RESREV_IS_HIDDEN, resrev_meta = ?RESREV_META; select last_insert_id() into @resourceid; insert into resourcerevs set resrev_res_id = @resourceid, resrev_rev = ?RESREV_REV, resrev_user_id = ?RESREV_USER_ID, resrev_parent_id = ?RESREV_PARENT_ID, resrev_parent_page_id = ?RESREV_PARENT_PAGE_ID, resrev_parent_user_id = ?RESREV_PARENT_USER_ID, resrev_change_mask = ?RESREV_CHANGE_MASK, resrev_name = ?RESREV_NAME, resrev_change_description = ?RESREV_CHANGE_DESCRIPTION, resrev_timestamp = ?RESREV_TIMESTAMP, resrev_content_id = ?RESREV_CONTENT_ID, resrev_deleted = ?RESREV_DELETED, resrev_changeset_id = ?RESREV_CHANGESET_ID, resrev_size = ?RESREV_SIZE, resrev_mimetype = ?RESREV_MIMETYPE, resrev_language = ?RESREV_LANGUAGE, resrev_is_hidden = ?RESREV_IS_HIDDEN, resrev_meta = ?RESREV_META; update resourcecontents set rescontent_res_id = @resourceid, rescontent_res_rev = ?RESREV_REV where rescontent_id = ?RESREV_CONTENT_ID; select * from resources left join resourcecontents on resources.resrev_content_id = resourcecontents.rescontent_id where res_id = @resourceid; /* End of ResourceDA::InsertResourceRevision (new resource) */ "; } else { resource.Revision = ++resource.ResourceHeadRevision; if(contentUpdated) { resource.Content.Revision = (uint) resource.Revision; } query = @" /* Resources_SaveRevision + concurrency check (new revision) */ update resources set res_headrev = ?RES_HEADREV, res_type = ?RES_TYPE, res_deleted = ?RES_DELETED, res_update_timestamp = ?RESREV_TIMESTAMP, res_update_user_id = ?RES_UPDATE_USER_ID, resrev_rev = ?RESREV_REV, resrev_user_id = ?RESREV_USER_ID, resrev_parent_id = ?RESREV_PARENT_ID, resrev_parent_page_id = ?RESREV_PARENT_PAGE_ID, resrev_parent_user_id = ?RESREV_PARENT_USER_ID, resrev_change_mask = ?RESREV_CHANGE_MASK, resrev_name = ?RESREV_NAME, resrev_change_description = ?RESREV_CHANGE_DESCRIPTION, resrev_timestamp = ?RESREV_TIMESTAMP, resrev_content_id = ?RESREV_CONTENT_ID, resrev_deleted = ?RESREV_DELETED, resrev_changeset_id = ?RESREV_CHANGESET_ID, resrev_size = ?RESREV_SIZE, resrev_mimetype = ?RESREV_MIMETYPE, resrev_language = ?RESREV_LANGUAGE, resrev_is_hidden = ?RESREV_IS_HIDDEN, resrev_meta = ?RESREV_META WHERE res_id = ?RES_ID AND res_headrev = ?RES_HEADREV - 1 AND res_update_timestamp = ?RES_UPDATE_TIMESTAMP; select ROW_COUNT() into @affectedRows; select * from resources where @affectedrows > 0 and res_id = ?RES_ID; "; if(ArrayUtil.IsNullOrEmpty(Resources_ExecuteInsertUpdateQuery(resource, query))) { //Cleanup content row if resource could not be updated Resources_ContentDelete(resource.ContentId); throw new ResourceConcurrencyException(resource.ResourceId); } query = @" /* Resources_SaveRevision (new revision) */ replace into resourcerevs set resrev_res_id = ?RES_ID, resrev_rev = ?RESREV_REV, resrev_user_id = ?RESREV_USER_ID, resrev_parent_id = ?RESREV_PARENT_ID, resrev_parent_page_id = ?RESREV_PARENT_PAGE_ID, resrev_parent_user_id = ?RESREV_PARENT_USER_ID, resrev_change_mask = ?RESREV_CHANGE_MASK, resrev_name = ?RESREV_NAME, resrev_change_description = ?RESREV_CHANGE_DESCRIPTION, resrev_timestamp = ?RESREV_TIMESTAMP, resrev_content_id = ?RESREV_CONTENT_ID, resrev_deleted = ?RESREV_DELETED, resrev_changeset_id = ?RESREV_CHANGESET_ID, resrev_size = ?RESREV_SIZE, resrev_mimetype = ?RESREV_MIMETYPE, resrev_language = ?RESREV_LANGUAGE, resrev_is_hidden = ?RESREV_IS_HIDDEN, resrev_meta = ?RESREV_META; update resourcecontents set rescontent_res_id = ?RES_ID, rescontent_res_rev = ?RESCONTENT_RES_REV where rescontent_id = ?RESREV_CONTENT_ID; select * from resources left join resourcecontents on resources.resrev_content_id = resourcecontents.rescontent_id where res_id = ?RES_ID; "; } ResourceBE[] ret = Resources_ExecuteInsertUpdateQuery(resource, query); return (ArrayUtil.IsNullOrEmpty(ret)) ? null : ret[0]; } public ResourceBE Resources_UpdateRevision(ResourceBE resource) { //Prepare query for retrieving the resource after updating string selectQuery = new ResourceQuery() .WithResourceId(resource.ResourceId) .WithRevision(resource.Revision) .ToString(); //Note: The resrev_timestamp is not updated in order to preserve the initial timeline of revisions string query = string.Format(@" /* Resources_UpdateRevision */ update resourcerevs set resrev_rev = ?RESREV_REV, resrev_user_id = ?RESREV_USER_ID, resrev_parent_id = ?RESREV_PARENT_ID, resrev_parent_page_id = ?RESREV_PARENT_PAGE_ID, resrev_parent_user_id = ?RESREV_PARENT_USER_ID, resrev_change_mask = ?RESREV_CHANGE_MASK, resrev_name = ?RESREV_NAME, resrev_change_description=?RESREV_CHANGE_DESCRIPTION, resrev_content_id = ?RESREV_CONTENT_ID, resrev_deleted = ?RESREV_DELETED, resrev_changeset_id = ?RESREV_CHANGESET_ID, resrev_size = ?RESREV_SIZE, resrev_mimetype = ?RESREV_MIMETYPE, resrev_language = ?RESREV_LANGUAGE, resrev_is_hidden = ?RESREV_IS_HIDDEN, resrev_meta = ?RESREV_META WHERE resrev_res_id = ?RES_ID AND resrev_rev = ?RESREV_REV; {0} ", selectQuery); ResourceBE[] ret = Resources_ExecuteInsertUpdateQuery(resource, query); if(resource.IsHeadRevision()) { Resources_ResetHeadRevision(resource.ResourceId); } return (ArrayUtil.IsNullOrEmpty(ret)) ? null : ret[0]; } public void Resources_Delete(IList<uint> resourceIds) { //TODO MaxM: Remove content as well if(resourceIds.Count == 0) { return; } string resourceIdsText = string.Join(",", DbUtils.ConvertArrayToDelimittedString<uint>(',', resourceIds)); Catalog.NewQuery(string.Format(@" /* Resources_Delete */ delete from resources where res_id in ({0}); delete from resourcerevs where resrev_res_id in ({0});", resourceIdsText)) .Execute(); } public void Resources_DeleteRevision(uint resourceId, int revision) { //Wiping a revision is only done internally in the case where content doesn't get saved properly. ResourceBE rev = Head.Resources_GetByIdAndRevision(resourceId, revision); if(rev == null) return; //Only one revision exists: Wipe it. if(revision == AttachmentBE.TAILREVISION && rev.ResourceHeadRevision == revision) { Head.Resources_Delete(new List<uint>() { resourceId }); return; } //More than one revision exists: Delete the revision Catalog.NewQuery(@" /* Resources_DeleteRevision */ delete from resourcerevs where resrev_res_id = ?RES_ID and resrev_rev = ?RESREV_REV;") .With("RES_ID", resourceId) .With("RESREV_REV", revision) .Execute(); //Head revision was deleted: update head revision to new head. if(rev.ResourceHeadRevision == revision) { Resources_ResetHeadRevision(resourceId); } } private void Resources_ResetHeadRevision(uint resourceId) { //Update the HEAD revision in resources to latest revision in resourcerevs Catalog.NewQuery(@" /* Resources_ResetHeadRevision */ update resources f join resourcerevs fr join ( select max(resrev_rev) as resrev_rev from resourcerevs where resrev_res_id = ?RES_ID ) maxrev on fr.resrev_res_id = ?RES_ID and fr.resrev_rev = maxrev.resrev_rev set f.res_headrev =fr.resrev_rev, f.res_update_timestamp =fr.resrev_timestamp, f.res_update_user_id =fr.resrev_user_id, f.resrev_rev =fr.resrev_rev, f.resrev_user_id =fr.resrev_user_id, f.resrev_parent_id =fr.resrev_parent_id, f.resrev_parent_page_id =fr.resrev_parent_page_id, f.resrev_parent_user_id =fr.resrev_parent_user_id, f.resrev_change_mask =fr.resrev_change_mask, f.resrev_name =fr.resrev_name, f.resrev_change_description =fr.resrev_change_description, f.resrev_timestamp =fr.resrev_timestamp, f.resrev_content_id =fr.resrev_content_id, f.resrev_deleted =fr.resrev_deleted, f.resrev_changeset_id =fr.resrev_changeset_id, f.resrev_size =fr.resrev_size, f.resrev_mimetype =fr.resrev_mimetype, f.resrev_language =fr.resrev_language, f.resrev_is_hidden =fr.resrev_is_hidden, f.resrev_meta =fr.resrev_meta where fr.resrev_res_id = f.res_id;") .With("RES_ID", resourceId) .Execute(); } private static ResourceBE Resources_Populate(IDataReader dr) { ResourceBE.Type resourceType = (ResourceBE.Type)DbUtils.Convert.To<byte>(dr["res_type"], (byte)ResourceBE.Type.UNDEFINED); ResourceBE res = ResourceBE.New(resourceType); MimeType mimeTypeTmp = null; for(int i = 0; i < dr.FieldCount; i++) { #region ResourceBE and ResourceContentBE entity mapping switch(dr.GetName(i).ToLowerInvariant()) { case "res_id": res.ResourceId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "resrev_res_id": res.ResourceId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "resrev_rev": res.Revision = DbUtils.Convert.To<int>(dr.GetValue(i)) ?? 0; break; case "resrev_user_id": res.UserId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "resrev_change_mask": res.ChangeMask = (ResourceBE.ChangeOperations) (DbUtils.Convert.To<ushort>(dr.GetValue(i)) ?? (ushort) ResourceBE.ChangeOperations.UNDEFINED); break; case "resrev_name": res.Name = dr.GetValue(i) as string; break; case "resrev_change_description": res.ChangeDescription = dr.GetValue(i) as string; break; case "resrev_timestamp": res.Timestamp = new DateTime(dr.GetDateTime(i).Ticks, DateTimeKind.Utc); break; case "resrev_content_id": res.ContentId = DbUtils.Convert.To<uint>(dr.GetValue(i), 0); break; case "resrev_deleted": res.Deleted = DbUtils.Convert.To<bool>(dr.GetValue(i), false); break; case "resrev_size": res.Size = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "resrev_mimetype": MimeType.TryParse(dr.GetValue(i) as string, out mimeTypeTmp); res.MimeType = mimeTypeTmp; break; case "resrev_changeset_id": res.ChangeSetId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "resrev_parent_id": res.ParentId = DbUtils.Convert.To<uint>(dr.GetValue(i)); break; case "resrev_parent_page_id": res.ParentPageId = DbUtils.Convert.To<uint>(dr.GetValue(i)); break; case "resrev_parent_user_id": res.ParentUserId = DbUtils.Convert.To<uint>(dr.GetValue(i)); break; case "res_headrev": res.ResourceHeadRevision = DbUtils.Convert.To<int>(dr.GetValue(i)) ?? 0; break; case "res_type": res.ResourceType = (ResourceBE.Type) (DbUtils.Convert.To<byte>(dr.GetValue(i)) ?? (byte) ResourceBE.Type.UNDEFINED); break; case "res_deleted": res.ResourceIsDeleted = DbUtils.Convert.To<bool>(dr.GetValue(i), false); break; case "res_create_timestamp": res.ResourceCreateTimestamp = new DateTime(dr.GetDateTime(i).Ticks, DateTimeKind.Utc); break; case "res_update_timestamp": res.ResourceUpdateTimestamp = new DateTime(dr.GetDateTime(i).Ticks, DateTimeKind.Utc); break; case "res_create_user_id": res.ResourceCreateUserId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "res_update_user_id": res.ResourceUpdateUserId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "resrev_language": res.Language = dr.GetValue(i) as string; break; case "resrev_is_hidden": res.IsHidden = DbUtils.Convert.To<bool>(dr.GetValue(i), false); break; case "resrev_meta": res.Meta = dr.GetValue(i) as string; break; case "rescontent_id": res.Content.ContentId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "rescontent_res_id": res.Content.ResourceId = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "rescontent_res_rev": res.Content.Revision = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; case "rescontent_value": res.Content.SetData(dr.GetValue(i) as byte[]); break; case "rescontent_location": res.Content.Location = dr.GetValue(i) as string; break; case "rescontent_mimetype": MimeType.TryParse(dr.GetValue(i) as string, out mimeTypeTmp); res.Content.MimeType = mimeTypeTmp; break; case "rescontent_size": res.Content.Size = DbUtils.Convert.To<uint>(dr.GetValue(i)) ?? 0; break; default: break; } #endregion } //Resource contents may not always be retrieved. Make sure it's null if it's not there. if(res.Content != null && res.Content.IsNewContent()) { res.Content = null; } return res; } private ResourceBE[] Resources_ExecuteInsertUpdateQuery(ResourceBE resource, string query) { List<ResourceBE> resources = new List<ResourceBE>(); Catalog.NewQuery(query) .With("RES_ID", resource.ResourceId) .With("RES_HEADREV", resource.ResourceHeadRevision) .With("RES_TYPE", (uint) resource.ResourceType) .With("RES_CREATE_TIMESTAMP", resource.ResourceCreateTimestamp) .With("RES_UPDATE_TIMESTAMP", resource.ResourceUpdateTimestamp) .With("RES_CREATE_USER_ID", resource.ResourceCreateUserId) .With("RES_UPDATE_USER_ID", resource.ResourceUpdateUserId) .With("RES_DELETED", resource.ResourceIsDeleted) .With("RESREV_REV", resource.Revision) .With("RESREV_USER_ID", resource.UserId) .With("RESREV_PARENT_ID", resource.ParentId) .With("RESREV_PARENT_PAGE_ID", resource.ParentPageId) .With("RESREV_PARENT_USER_ID", resource.ParentUserId) .With("RESREV_CHANGE_MASK", (ushort) resource.ChangeMask) .With("RESREV_NAME", resource.Name) .With("RESREV_CHANGE_DESCRIPTION", resource.ChangeDescription) .With("RESREV_TIMESTAMP", resource.Timestamp) .With("RESREV_DELETED", resource.Deleted) .With("RESREV_CHANGESET_ID", resource.ChangeSetId) .With("RESREV_SIZE", resource.Size) .With("RESREV_MIMETYPE", resource.MimeType != null ? resource.MimeType.ToString() : null) .With("RESREV_CONTENT_ID", resource.ContentId) .With("RESREV_LANGUAGE", resource.Language) .With("RESREV_IS_HIDDEN", resource.IsHidden) .With("RESREV_META", resource.Meta) .With("RESCONTENT_RES_REV", resource.Content != null ? resource.Content.Revision : null) .Execute(delegate(IDataReader dr) { while(dr.Read()) { resources.Add(Resources_Populate(dr)); } }); return resources.ToArray(); } #region ResourceContents methods private ResourceContentBE Resources_ContentInsert(ResourceContentBE contents) { string query = @" /* ResourceDA::ContentInsert */ insert into resourcecontents (rescontent_res_id, rescontent_res_rev, rescontent_location, rescontent_mimetype, rescontent_size, rescontent_value) values (?RESCONTENT_RES_ID, ?RESCONTENT_RES_REV, ?RESCONTENT_LOCATION, ?RESCONTENT_MIMETYPE, ?RESCONTENT_SIZE, ?RESCONTENT_VALUE); select last_insert_id();"; contents.ContentId = Catalog.NewQuery(query) .With("RESCONTENT_RES_ID", contents.ResourceId) .With("RESCONTENT_RES_REV", contents.Revision) .With("RESCONTENT_LOCATION", contents.Location) .With("RESCONTENT_MIMETYPE", contents.MimeType.ToString()) .With("RESCONTENT_SIZE", contents.Size) .With("RESCONTENT_VALUE", contents.IsDbBased ? contents.ToBytes() : null) .ReadAsUInt() ?? 0; return contents; } private void Resources_ContentDelete(uint contentId) { string query = @" /* ResourceDA::ContentDelete */ delete from resourcecontents where rescontent_id = ?RESCONTENT_ID;"; Catalog.NewQuery(query) .With("RESCONTENT_ID", contentId) .Execute(); } #endregion } }
using System; namespace Bridge.QUnit { [External] public class Assert { /// <summary> /// Instruct QUnit to wait for an asynchronous operation. /// When your test has any asynchronous exit points, call assert.async() to get a unique resolution callback for each async operation. /// The callback returned from assert.async() will throw an Error if is invoked more than once. /// </summary> public virtual Action Async() { return null; } /// <summary> /// A non-strict comparison, roughly equivalent to JUnit's assertEquals. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void Equal(object actual, object expected) { } /// <summary> /// A non-strict comparison, roughly equivalent to JUnit's assertEquals. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void Equal(object actual, object expected, string message) { } /// <summary> /// A deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void DeepEqual(object actual, object expected) { } /// <summary> /// A deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void DeepEqual(object actual, object expected, string message) { } /// <summary> /// Specify how many assertions are expected to run within a test. /// If the number of assertions run does not match the expected count, the test will fail. /// </summary> /// <param name="number">Number of assertions in this test.</param> public virtual void Expect(int number) { } /// <summary> /// An inverted deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotDeepEqual(object actual, object expected) { } /// <summary> /// An inverted deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotDeepEqual(object actual, object expected, string message) { } /// <summary> /// A non-strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotEqual(object actual, object expected) { } /// <summary> /// A non-strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotEqual(object actual, object expected, string message) { } /// <summary> /// A strict comparison of an object's own properties, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotPropEqual(object actual, object expected) { } /// <summary> /// A strict comparison of an object's own properties, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotPropEqual(object actual, object expected, string message) { } /// <summary> /// A strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotStrictEqual(object actual, object expected) { } /// <summary> /// A strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotStrictEqual(object actual, object expected, string message) { } /// <summary> /// A boolean check, inverse of ok() and CommonJS's assert.ok(), and equivalent to JUnit's assertFalse(). Passes if the first argument is falsy. /// </summary> /// <param name="state">Expression being tested</param> public virtual void NotOk(object state) { } /// <summary> /// A boolean check, inverse of ok() and CommonJS's assert.ok(), and equivalent to JUnit's assertFalse(). Passes if the first argument is falsy. /// </summary> /// <param name="state">Expression being tested</param> /// <param name="message">A short description of the assertion</param> public virtual void NotOk(object state, string message) { } /// <summary> /// A boolean check, equivalent to CommonJS's assert.ok() and JUnit's assertTrue(). Passes if the first argument is truthy. /// </summary> /// <param name="state">Expression being tested</param> public virtual void Ok(object state) { } /// <summary> /// A boolean check, equivalent to CommonJS's assert.ok() and JUnit's assertTrue(). Passes if the first argument is truthy. /// </summary> /// <param name="state">Expression being tested</param> /// <param name="message">A short description of the assertion</param> public virtual void Ok(object state, string message) { } /// <summary> /// A strict type and value comparison of an object's own properties. /// </summary> /// <param name="actual">Object being tested</param> /// <param name="expected">Known comparison value</param> public virtual void PropEqual(object actual, object expected) { } /// <summary> /// A strict type and value comparison of an object's own properties. /// </summary> /// <param name="actual">Object being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void PropEqual(object actual, object expected, string message) { } /// <summary> /// Report the result of a custom assertion /// </summary> /// <param name="result">Result of the assertion</param> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void Push(bool result, object actual, object expected) { } /// <summary> /// Report the result of a custom assertion /// </summary> /// <param name="result">Result of the assertion</param> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void Push(bool result, object actual, object expected, string message) { } /// <summary> /// A strict type and value comparison. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void StrictEqual(object actual, object expected) { } /// <summary> /// A strict type and value comparison. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void StrictEqual(object actual, object expected, string message) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="message">A short description of the assertion</param> public virtual void Throws(Action block, string message) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">Expected error string representation or RegExp that matches (or partially matches)</param> public virtual void Throws(Action block, object expected) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">Expected error string representation or RegExp that matches (or partially matches)</param> /// <param name="message">A short description of the assertion</param> public virtual void Throws(Action block, object expected, string message) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">A callback Function that must return true to pass the assertion check</param> public virtual void Throws(Action block, Func<object, bool> expected) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">A callback Function that must return true to pass the assertion check</param> /// <param name="message">A short description of the assertion</param> public virtual void Throws(Action block, Func<object, bool> expected, string message) { } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Drawing; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using System.Xml; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using umbraco.cms.businesslogic.Files; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; namespace Umbraco.Web.PropertyEditors { [PropertyEditor(Constants.PropertyEditors.UploadFieldAlias, "File upload", "fileupload")] public class FileUploadPropertyEditor : PropertyEditor { /// <summary> /// We're going to bind to the MediaService Saving event so that we can populate the umbracoFile size, type, etc... label fields /// if we find any attached to the current media item. /// </summary> /// <remarks> /// I think this kind of logic belongs on this property editor, I guess it could exist elsewhere but it all has to do with the upload field. /// </remarks> static FileUploadPropertyEditor() { MediaService.Saving += MediaServiceSaving; MediaService.Created += MediaServiceCreating; ContentService.Copied += ContentServiceCopied; MediaService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange(ServiceDeleted(args.DeletedEntities.Cast<ContentBase>())); MediaService.EmptiedRecycleBin += (sender, args) => args.Files.AddRange(ServiceEmptiedRecycleBin(args.AllPropertyData)); ContentService.Deleted += (sender, args) => args.MediaFilesToDelete.AddRange(ServiceDeleted(args.DeletedEntities.Cast<ContentBase>())); ContentService.EmptiedRecycleBin += (sender, args) => args.Files.AddRange(ServiceEmptiedRecycleBin(args.AllPropertyData)); } /// <summary> /// Creates our custom value editor /// </summary> /// <returns></returns> protected override PropertyValueEditor CreateValueEditor() { var baseEditor = base.CreateValueEditor(); baseEditor.Validators.Add(new UploadFileTypeValidator()); return new FileUploadPropertyValueEditor(baseEditor); } protected override PreValueEditor CreatePreValueEditor() { return new FileUploadPreValueEditor(); } /// <summary> /// Ensures any files associated are removed /// </summary> /// <param name="allPropertyData"></param> static IEnumerable<string> ServiceEmptiedRecycleBin(Dictionary<int, IEnumerable<Property>> allPropertyData) { var list = new List<string>(); //Get all values for any image croppers found foreach (var uploadVal in allPropertyData .SelectMany(x => x.Value) .Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias) .Select(x => x.Value) .WhereNotNull()) { if (uploadVal.ToString().IsNullOrWhiteSpace() == false) { list.Add(uploadVal.ToString()); } } return list; } /// <summary> /// Ensures any files associated are removed /// </summary> /// <param name="deletedEntities"></param> static IEnumerable<string> ServiceDeleted(IEnumerable<ContentBase> deletedEntities) { var list = new List<string>(); foreach (var property in deletedEntities.SelectMany(deletedEntity => deletedEntity .Properties .Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias && x.Value != null && string.IsNullOrEmpty(x.Value.ToString()) == false))) { if (property.Value != null && property.Value.ToString().IsNullOrWhiteSpace() == false) { list.Add(property.Value.ToString()); } } return list; } /// <summary> /// After the content is copied we need to check if there are files that also need to be copied /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void ContentServiceCopied(IContentService sender, Core.Events.CopyEventArgs<IContent> e) { if (e.Original.Properties.Any(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias)) { bool isUpdated = false; var fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>(); //Loop through properties to check if the content contains media that should be deleted foreach (var property in e.Original.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias && x.Value != null && string.IsNullOrEmpty(x.Value.ToString()) == false)) { if (fs.FileExists(fs.GetRelativePath(property.Value.ToString()))) { var currentPath = fs.GetRelativePath(property.Value.ToString()); var propertyId = e.Copy.Properties.First(x => x.Alias == property.Alias).Id; var newPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(currentPath)); fs.CopyFile(currentPath, newPath); e.Copy.SetValue(property.Alias, fs.GetUrl(newPath)); //Copy thumbnails foreach (var thumbPath in fs.GetThumbnails(currentPath)) { var newThumbPath = fs.GetRelativePath(propertyId, System.IO.Path.GetFileName(thumbPath)); fs.CopyFile(thumbPath, newThumbPath); } isUpdated = true; } } if (isUpdated) { //need to re-save the copy with the updated path value sender.Save(e.Copy); } } } static void MediaServiceCreating(IMediaService sender, Core.Events.NewEventArgs<IMedia> e) { AutoFillProperties(e.Entity); } static void MediaServiceSaving(IMediaService sender, Core.Events.SaveEventArgs<IMedia> e) { foreach (var m in e.SavedEntities) { AutoFillProperties(m); } } static void AutoFillProperties(IContentBase model) { foreach (var p in model.Properties.Where(x => x.PropertyType.PropertyEditorAlias == Constants.PropertyEditors.UploadFieldAlias)) { var uploadFieldConfigNode = UmbracoConfig.For.UmbracoSettings().Content.ImageAutoFillProperties .FirstOrDefault(x => x.Alias == p.Alias); if (uploadFieldConfigNode != null) { model.PopulateFileMetaDataProperties(uploadFieldConfigNode, p.Value == null ? string.Empty : p.Value.ToString()); } } } /// <summary> /// A custom pre-val editor to ensure that the data is stored how the legacy data was stored in /// </summary> internal class FileUploadPreValueEditor : ValueListPreValueEditor { public FileUploadPreValueEditor() : base() { var field = Fields.First(); field.Description = "Enter a max width/height for each thumbnail"; field.Name = "Add thumbnail size"; //need to have some custom validation happening here field.Validators.Add(new ThumbnailListValidator()); } /// <summary> /// Format the persisted value to work with our multi-val editor. /// </summary> /// <param name="defaultPreVals"></param> /// <param name="persistedPreVals"></param> /// <returns></returns> public override IDictionary<string, object> ConvertDbToEditor(IDictionary<string, object> defaultPreVals, PreValueCollection persistedPreVals) { var result = new List<PreValue>(); //the pre-values just take up one field with a semi-colon delimiter so we'll just parse var dictionary = persistedPreVals.FormatAsDictionary(); if (dictionary.Any()) { //there should only be one val var delimited = dictionary.First().Value.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (var index = 0; index < delimited.Length; index++) { result.Add(new PreValue(index, delimited[index])); } } //the items list will be a dictionary of it's id -> value we need to use the id for persistence for backwards compatibility return new Dictionary<string, object> { { "items", result.ToDictionary(x => x.Id, x => PreValueAsDictionary(x)) } }; } private IDictionary<string, object> PreValueAsDictionary(PreValue preValue) { return new Dictionary<string, object> { { "value", preValue.Value }, { "sortOrder", preValue.SortOrder } }; } /// <summary> /// Take the posted values and convert them to a semi-colon separated list so that its backwards compatible /// </summary> /// <param name="editorValue"></param> /// <param name="currentValue"></param> /// <returns></returns> public override IDictionary<string, PreValue> ConvertEditorToDb(IDictionary<string, object> editorValue, PreValueCollection currentValue) { var result = base.ConvertEditorToDb(editorValue, currentValue); //this should just be a dictionary of values, we want to re-format this so that it is just one value in the dictionary that is // semi-colon delimited var values = result.Select(item => item.Value.Value).ToList(); result.Clear(); result.Add("thumbs", new PreValue(string.Join(";", values))); return result; } internal class ThumbnailListValidator : IPropertyValidator { public IEnumerable<ValidationResult> Validate(object value, PreValueCollection preValues, PropertyEditor editor) { var json = value as JArray; if (json == null) yield break; //validate each item which is a json object for (var index = 0; index < json.Count; index++) { var i = json[index]; var jItem = i as JObject; if (jItem == null || jItem["value"] == null) continue; //NOTE: we will be removing empty values when persisting so no need to validate var asString = jItem["value"].ToString(); if (asString.IsNullOrWhiteSpace()) continue; int parsed; if (int.TryParse(asString, out parsed) == false) { yield return new ValidationResult("The value " + asString + " is not a valid number", new[] { //we'll make the server field the index number of the value so it can be wired up to the view "item_" + index.ToInvariantString() }); } } } } } } }
// 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.Data.SqlClient; using System.Reflection; namespace System.Data.Common { internal static class DbConnectionStringBuilderUtil { internal static bool ConvertToBoolean(object value) { Debug.Assert(null != value, "ConvertToBoolean(null)"); string svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) return false; else { string tmp = svalue.Trim(); // Remove leading & trailing whitespace. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) return false; } return Boolean.Parse(svalue); } try { return Convert.ToBoolean(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e); } } internal static bool ConvertToIntegratedSecurity(object value) { Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)"); string svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) return false; else { string tmp = svalue.Trim(); // Remove leading & trailing whitespace. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) return false; } return Boolean.Parse(svalue); } try { return Convert.ToBoolean(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e); } } internal static int ConvertToInt32(object value) { try { return Convert.ToInt32(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Int32), e); } } internal static string ConvertToString(object value) { try { return Convert.ToString(value); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(String), e); } } private const string ApplicationIntentReadWriteString = "ReadWrite"; private const string ApplicationIntentReadOnlyString = "ReadOnly"; internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)"); if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString)) { result = ApplicationIntent.ReadOnly; return true; } else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString)) { result = ApplicationIntent.ReadWrite; return true; } else { result = DbConnectionStringDefaults.ApplicationIntent; return false; } } internal static bool IsValidApplicationIntentValue(ApplicationIntent value) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite; } internal static string ApplicationIntentToString(ApplicationIntent value) { Debug.Assert(IsValidApplicationIntentValue(value)); if (value == ApplicationIntent.ReadOnly) { return ApplicationIntentReadOnlyString; } else { return ApplicationIntentReadWriteString; } } /// <summary> /// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is: /// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer /// * if the value is from type ApplicationIntent, it will be used as is /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException /// /// in any case above, if the converted value is out of valid range, the method raises ArgumentOutOfRangeException. /// </summary> /// <returns>application intent value in the valid range</returns> internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) { Debug.Assert(null != value, "ConvertToApplicationIntent(null)"); string sValue = (value as string); ApplicationIntent result; if (null != sValue) { // We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like // "ReadOnly, ReadWrite" which are unwelcome here // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method. if (TryConvertToApplicationIntent(sValue, out result)) { return result; } // try again after remove leading & trailing whitespace. sValue = sValue.Trim(); if (TryConvertToApplicationIntent(sValue, out result)) { return result; } // string values must be valid throw ADP.InvalidConnectionOptionValue(keyword); } else { // the value is not string, try other options ApplicationIntent eValue; if (value is ApplicationIntent) { // quick path for the most common case eValue = (ApplicationIntent)value; } else if (value.GetType().GetTypeInfo().IsEnum) { // explicitly block scenarios in which user tries to use wrong enum types, like: // builder["ApplicationIntent"] = EnvironmentVariableTarget.Process; // workaround: explicitly cast non-ApplicationIntent enums to int throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null); } else { try { // Enum.ToObject allows only integral and enum values (enums are blocked above), raising ArgumentException for the rest eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value); } catch (ArgumentException e) { // to be consistent with the messages we send in case of wrong type usage, replace // the error with our exception, and keep the original one as inner one for troubleshooting throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e); } } // ensure value is in valid range if (IsValidApplicationIntentValue(eValue)) { return eValue; } else { throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue); } } } } internal static class DbConnectionStringDefaults { // all // internal const string NamedConnection = ""; // SqlClient internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite; internal const string ApplicationName = "Core .Net SqlClient Data Provider"; internal const string AttachDBFilename = ""; internal const int ConnectTimeout = 15; internal const string CurrentLanguage = ""; internal const string DataSource = ""; internal const bool Encrypt = false; internal const bool Enlist = true; internal const string FailoverPartner = ""; internal const string InitialCatalog = ""; internal const bool IntegratedSecurity = false; internal const int LoadBalanceTimeout = 0; // default of 0 means don't use internal const bool MultipleActiveResultSets = false; internal const bool MultiSubnetFailover = false; internal const int MaxPoolSize = 100; internal const int MinPoolSize = 0; internal const int PacketSize = 8000; internal const string Password = ""; internal const bool PersistSecurityInfo = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string TypeSystemVersion = "Latest"; internal const string UserID = ""; internal const bool UserInstance = false; internal const bool Replication = false; internal const string WorkstationID = ""; internal const string TransactionBinding = "Implicit Unbind"; internal const int ConnectRetryCount = 1; internal const int ConnectRetryInterval = 10; } internal static class DbConnectionStringKeywords { // all // internal const string NamedConnection = "Named Connection"; // SqlClient internal const string ApplicationIntent = "ApplicationIntent"; internal const string ApplicationName = "Application Name"; internal const string AsynchronousProcessing = "Asynchronous Processing"; internal const string AttachDBFilename = "AttachDbFilename"; internal const string ConnectTimeout = "Connect Timeout"; internal const string ConnectionReset = "Connection Reset"; internal const string ContextConnection = "Context Connection"; internal const string CurrentLanguage = "Current Language"; internal const string Encrypt = "Encrypt"; internal const string FailoverPartner = "Failover Partner"; internal const string InitialCatalog = "Initial Catalog"; internal const string MultipleActiveResultSets = "MultipleActiveResultSets"; internal const string MultiSubnetFailover = "MultiSubnetFailover"; internal const string NetworkLibrary = "Network Library"; internal const string PacketSize = "Packet Size"; internal const string Replication = "Replication"; internal const string TransactionBinding = "Transaction Binding"; internal const string TrustServerCertificate = "TrustServerCertificate"; internal const string TypeSystemVersion = "Type System Version"; internal const string UserInstance = "User Instance"; internal const string WorkstationID = "Workstation ID"; internal const string ConnectRetryCount = "ConnectRetryCount"; internal const string ConnectRetryInterval = "ConnectRetryInterval"; // common keywords (OleDb, OracleClient, SqlClient) internal const string DataSource = "Data Source"; internal const string IntegratedSecurity = "Integrated Security"; internal const string Password = "Password"; internal const string Driver = "Driver"; internal const string PersistSecurityInfo = "Persist Security Info"; internal const string UserID = "User ID"; // managed pooling (OracleClient, SqlClient) internal const string Enlist = "Enlist"; internal const string LoadBalanceTimeout = "Load Balance Timeout"; internal const string MaxPoolSize = "Max Pool Size"; internal const string Pooling = "Pooling"; internal const string MinPoolSize = "Min Pool Size"; } internal static class DbConnectionStringSynonyms { //internal const string AsynchronousProcessing = Async; internal const string Async = "async"; //internal const string ApplicationName = APP; internal const string APP = "app"; //internal const string AttachDBFilename = EXTENDEDPROPERTIES+","+INITIALFILENAME; internal const string EXTENDEDPROPERTIES = "extended properties"; internal const string INITIALFILENAME = "initial file name"; //internal const string ConnectTimeout = CONNECTIONTIMEOUT+","+TIMEOUT; internal const string CONNECTIONTIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; //internal const string CurrentLanguage = LANGUAGE; internal const string LANGUAGE = "language"; //internal const string OraDataSource = SERVER; //internal const string SqlDataSource = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS; internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORKADDRESS = "network address"; //internal const string InitialCatalog = DATABASE; internal const string DATABASE = "database"; //internal const string IntegratedSecurity = TRUSTEDCONNECTION; internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in Everett //internal const string LoadBalanceTimeout = ConnectionLifetime; internal const string ConnectionLifetime = "connection lifetime"; //internal const string NetworkLibrary = NET+","+NETWORK; internal const string NET = "net"; internal const string NETWORK = "network"; //internal const string Password = Pwd; internal const string Pwd = "pwd"; //internal const string PersistSecurityInfo = PERSISTSECURITYINFO; internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; //internal const string UserID = UID+","+User; internal const string UID = "uid"; internal const string User = "user"; //internal const string WorkstationID = WSID; internal const string WSID = "wsid"; } }
namespace HoughTransform { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose( bool disposing ) { if ( disposing && ( components != null ) ) { components.Dispose( ); } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent( ) { this.menuStrip1 = new System.Windows.Forms.MenuStrip( ); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( ); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( ); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator( ); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem( ); this.openFileDialog = new System.Windows.Forms.OpenFileDialog( ); this.tabControl = new System.Windows.Forms.TabControl( ); this.tabPage1 = new System.Windows.Forms.TabPage( ); this.sourcePictureBox = new System.Windows.Forms.PictureBox( ); this.tabPage2 = new System.Windows.Forms.TabPage( ); this.houghLinePictureBox = new System.Windows.Forms.PictureBox( ); this.tabPage3 = new System.Windows.Forms.TabPage( ); this.houghCirclePictureBox = new System.Windows.Forms.PictureBox( ); this.menuStrip1.SuspendLayout( ); this.tabControl.SuspendLayout( ); this.tabPage1.SuspendLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.sourcePictureBox ) ).BeginInit( ); this.tabPage2.SuspendLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.houghLinePictureBox ) ).BeginInit( ); this.tabPage3.SuspendLayout( ); ( (System.ComponentModel.ISupportInitialize) ( this.houghCirclePictureBox ) ).BeginInit( ); this.SuspendLayout( ); // // menuStrip1 // this.menuStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem} ); this.menuStrip1.Location = new System.Drawing.Point( 0, 0 ); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size( 632, 24 ); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "mainMenuStrip"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem, this.toolStripMenuItem1, this.exitToolStripMenuItem} ); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size( 35, 20 ); this.fileToolStripMenuItem.Text = "&File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ( (System.Windows.Forms.Keys) ( ( System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O ) ) ); this.openToolStripMenuItem.Size = new System.Drawing.Size( 151, 22 ); this.openToolStripMenuItem.Text = "&Open"; this.openToolStripMenuItem.Click += new System.EventHandler( this.openToolStripMenuItem_Click ); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size( 148, 6 ); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size( 151, 22 ); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler( this.exitToolStripMenuItem_Click ); // // openFileDialog // this.openFileDialog.Filter = "Image files (*.jpg,*.png,*.tif,*.bmp,*.gif)|*.jpg;*.png;*.tif;*.bmp;*.gif|JPG fil" + "es (*.jpg)|*.jpg|PNG files (*.png)|*.png|TIF files (*.tif)|*.tif|BMP files (*.bm" + "p)|*.bmp|GIF files (*.gif)|*.gif"; this.openFileDialog.Title = "Open image"; // // tabControl // this.tabControl.Controls.Add( this.tabPage1 ); this.tabControl.Controls.Add( this.tabPage2 ); this.tabControl.Controls.Add( this.tabPage3 ); this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl.Location = new System.Drawing.Point( 0, 24 ); this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; this.tabControl.Size = new System.Drawing.Size( 632, 442 ); this.tabControl.TabIndex = 1; // // tabPage1 // this.tabPage1.Controls.Add( this.sourcePictureBox ); this.tabPage1.Location = new System.Drawing.Point( 4, 22 ); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage1.Size = new System.Drawing.Size( 624, 416 ); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Original image"; this.tabPage1.UseVisualStyleBackColor = true; // // sourcePictureBox // this.sourcePictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.sourcePictureBox.Location = new System.Drawing.Point( 3, 3 ); this.sourcePictureBox.Name = "sourcePictureBox"; this.sourcePictureBox.Size = new System.Drawing.Size( 618, 410 ); this.sourcePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.sourcePictureBox.TabIndex = 0; this.sourcePictureBox.TabStop = false; // // tabPage2 // this.tabPage2.Controls.Add( this.houghLinePictureBox ); this.tabPage2.Location = new System.Drawing.Point( 4, 22 ); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding( 3 ); this.tabPage2.Size = new System.Drawing.Size( 624, 416 ); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Hough lines"; this.tabPage2.UseVisualStyleBackColor = true; // // houghLinePictureBox // this.houghLinePictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.houghLinePictureBox.Location = new System.Drawing.Point( 3, 3 ); this.houghLinePictureBox.Name = "houghLinePictureBox"; this.houghLinePictureBox.Size = new System.Drawing.Size( 618, 410 ); this.houghLinePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.houghLinePictureBox.TabIndex = 0; this.houghLinePictureBox.TabStop = false; // // tabPage3 // this.tabPage3.Controls.Add( this.houghCirclePictureBox ); this.tabPage3.Location = new System.Drawing.Point( 4, 22 ); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size( 624, 416 ); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Hough circles"; this.tabPage3.UseVisualStyleBackColor = true; // // houghCirclePictureBox // this.houghCirclePictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.houghCirclePictureBox.Location = new System.Drawing.Point( 0, 0 ); this.houghCirclePictureBox.Name = "houghCirclePictureBox"; this.houghCirclePictureBox.Size = new System.Drawing.Size( 624, 416 ); this.houghCirclePictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.houghCirclePictureBox.TabIndex = 0; this.houghCirclePictureBox.TabStop = false; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F ); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size( 632, 466 ); this.Controls.Add( this.tabControl ); this.Controls.Add( this.menuStrip1 ); this.MainMenuStrip = this.menuStrip1; this.Name = "MainForm"; this.Text = "Hough transformation"; this.menuStrip1.ResumeLayout( false ); this.menuStrip1.PerformLayout( ); this.tabControl.ResumeLayout( false ); this.tabPage1.ResumeLayout( false ); ( (System.ComponentModel.ISupportInitialize) ( this.sourcePictureBox ) ).EndInit( ); this.tabPage2.ResumeLayout( false ); ( (System.ComponentModel.ISupportInitialize) ( this.houghLinePictureBox ) ).EndInit( ); this.tabPage3.ResumeLayout( false ); ( (System.ComponentModel.ISupportInitialize) ( this.houghCirclePictureBox ) ).EndInit( ); this.ResumeLayout( false ); this.PerformLayout( ); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.PictureBox sourcePictureBox; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.PictureBox houghLinePictureBox; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.PictureBox houghCirclePictureBox; } }
/* C# implementation of xxHash optimized for producing random numbers from one or more input integers. Copyright (C) 2015, Rune Skovbo Johansen. (https://bitbucket.org/runevision/random-numbers-testing/) Based on C# implementation Copyright (C) 2014, Seok-Ju, Yun. (https://github.com/noricube/xxHashSharp) Original C Implementation Copyright (C) 2012-2014, Yann Collet. (https://code.google.com/p/xxhash/) BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; namespace Runevision.Structures { public class RandomHash : HashFunction { private uint seed; const uint PRIME32_1 = 2654435761U; const uint PRIME32_2 = 2246822519U; const uint PRIME32_3 = 3266489917U; const uint PRIME32_4 = 668265263U; const uint PRIME32_5 = 374761393U; public RandomHash (int seed) { this.seed = (uint)seed; } public uint GetHash (byte[] buf) { uint h32; int index = 0; int len = buf.Length; if (len >= 16) { int limit = len - 16; uint v1 = seed + PRIME32_1 + PRIME32_2; uint v2 = seed + PRIME32_2; uint v3 = seed + 0; uint v4 = seed - PRIME32_1; do { v1 = CalcSubHash (v1, buf, index); index += 4; v2 = CalcSubHash (v2, buf, index); index += 4; v3 = CalcSubHash (v3, buf, index); index += 4; v4 = CalcSubHash (v4, buf, index); index += 4; } while (index <= limit); h32 = RotateLeft (v1, 1) + RotateLeft (v2, 7) + RotateLeft (v3, 12) + RotateLeft (v4, 18); } else { h32 = seed + PRIME32_5; } h32 += (uint)len; while (index <= len - 4) { h32 += BitConverter.ToUInt32 (buf, index) * PRIME32_3; h32 = RotateLeft (h32, 17) * PRIME32_4; index += 4; } while (index<len) { h32 += buf[index] * PRIME32_5; h32 = RotateLeft (h32, 11) * PRIME32_1; index++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } public uint GetHash (params uint[] buf) { uint h32; int index = 0; int len = buf.Length; if (len >= 4) { int limit = len - 4; uint v1 = seed + PRIME32_1 + PRIME32_2; uint v2 = seed + PRIME32_2; uint v3 = seed + 0; uint v4 = seed - PRIME32_1; do { v1 = CalcSubHash (v1, buf[index]); index++; v2 = CalcSubHash (v2, buf[index]); index++; v3 = CalcSubHash (v3, buf[index]); index++; v4 = CalcSubHash (v4, buf[index]); index++; } while (index <= limit); h32 = RotateLeft (v1, 1) + RotateLeft (v2, 7) + RotateLeft (v3, 12) + RotateLeft (v4, 18); } else { h32 = seed + PRIME32_5; } h32 += (uint)len * 4; while (index < len) { h32 += buf[index] * PRIME32_3; h32 = RotateLeft (h32, 17) * PRIME32_4; index++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } public override uint GetHash (params int[] buf) { uint h32; int index = 0; int len = buf.Length; if (len >= 4) { int limit = len - 4; uint v1 = (uint)seed + PRIME32_1 + PRIME32_2; uint v2 = (uint)seed + PRIME32_2; uint v3 = (uint)seed + 0; uint v4 = (uint)seed - PRIME32_1; do { v1 = CalcSubHash (v1, (uint)buf[index]); index++; v2 = CalcSubHash (v2, (uint)buf[index]); index++; v3 = CalcSubHash (v3, (uint)buf[index]); index++; v4 = CalcSubHash (v4, (uint)buf[index]); index++; } while (index <= limit); h32 = RotateLeft (v1, 1) + RotateLeft (v2, 7) + RotateLeft (v3, 12) + RotateLeft (v4, 18); } else { h32 = (uint)seed + PRIME32_5; } h32 += (uint)len * 4; while (index < len) { h32 += (uint)buf[index] * PRIME32_3; h32 = RotateLeft (h32, 17) * PRIME32_4; index++; } h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } public override uint GetHash (int buf) { uint h32 = (uint)seed + PRIME32_5; h32 += 4U; h32 += (uint)buf * PRIME32_3; h32 = RotateLeft (h32, 17) * PRIME32_4; h32 ^= h32 >> 15; h32 *= PRIME32_2; h32 ^= h32 >> 13; h32 *= PRIME32_3; h32 ^= h32 >> 16; return h32; } private static uint CalcSubHash (uint value, byte[] buf, int index) { uint read_value = BitConverter.ToUInt32 (buf, index); value += read_value * PRIME32_2; value = RotateLeft (value, 13); value *= PRIME32_1; return value; } private static uint CalcSubHash (uint value, uint read_value) { value += read_value * PRIME32_2; value = RotateLeft (value, 13); value *= PRIME32_1; return value; } private static uint RotateLeft (uint value, int count) { return (value << count) | (value >> (32 - count)); } } }
using System.Linq; using System.Threading.Tasks; using AspNetCore.Identity.DynamoDB; using IdentitySample.Models.ManageViewModels; using IdentitySample.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace IdentitySamples.Controllers { [Authorize] public class ManageController : Controller { private readonly IEmailSender _emailSender; private readonly ILogger _logger; private readonly SignInManager<DynamoIdentityUser> _signInManager; private readonly ISmsSender _smsSender; private readonly UserManager<DynamoIdentityUser> _userManager; public ManageController( UserManager<DynamoIdentityUser> userManager, SignInManager<DynamoIdentityUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new {Message = message}); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new {model.PhoneNumber}); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel {PhoneNumber = phoneNumber}); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return RedirectToAction(nameof(Index), new {Message = ManageMessageId.AddPhoneSuccess}); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // GET: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return RedirectToAction(nameof(Index), new {Message = ManageMessageId.RemovePhoneSuccess}); } } return RedirectToAction(nameof(Index), new {Message = ManageMessageId.Error}); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new {Message = ManageMessageId.ChangePasswordSuccess}); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new {Message = ManageMessageId.Error}); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, false); return RedirectToAction(nameof(Index), new {Message = ManageMessageId.SetPasswordSuccess}); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new {Message = ManageMessageId.Error}); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes() .Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)) .ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return Challenge(properties, provider); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { return RedirectToAction(nameof(ManageLogins), new {Message = ManageMessageId.Error}); } var result = await _userManager.AddLoginAsync(user, info); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction(nameof(ManageLogins), new {Message = message}); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private Task<DynamoIdentityUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } #endregion } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Net; using System.IO; using System; using System.Reflection; using System.Xml.Serialization; using UnityEditor.XCodeEditor; namespace Igor { public class IgorXCodeProjUtils { public static void SetDevTeamID(IIgorModule ModuleInst, string ProjectPath, string DevTeamID) { if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); string ProjectGUID = CurrentProject.project.guid; object ProjectSectionObj = CurrentProject.GetObject(ProjectGUID); if(IgorAssert.EnsureTrue(ModuleInst, ProjectSectionObj != null, "Can't find Project Section in XCodeProj.")) { PBXDictionary ProjectSection = (PBXDictionary)ProjectSectionObj; object AttributesSectionObj = ProjectSection["attributes"]; if(IgorAssert.EnsureTrue(ModuleInst, AttributesSectionObj != null, "Can't find Attributes Section in Project Section.")) { object TargetAttributesObj = ((PBXDictionary)AttributesSectionObj)["TargetAttributes"]; if(IgorAssert.EnsureTrue(ModuleInst, TargetAttributesObj != null, "Can't find TargetAttributes Section in Attributes Section.")) { PBXDictionary TargetAttributes = (PBXDictionary)TargetAttributesObj; object TargetsObj = ProjectSection["targets"]; if(IgorAssert.EnsureTrue(ModuleInst, TargetsObj != null, "Can't find Targets Section in Project Section.")) { PBXList TargetsList = ((PBXList)TargetsObj); if(IgorAssert.EnsureTrue(ModuleInst, TargetsList.Count > 0, "No build targets defined in XCodeProj.")) { string PrimaryBuildTargetGUID = (string)(TargetsList[0]); PBXDictionary PrimaryBuildTargetToDevTeam = new PBXDictionary(); PBXDictionary DevTeamIDDictionary = new PBXDictionary(); DevTeamIDDictionary.Add("DevelopmentTeam", DevTeamID); PrimaryBuildTargetToDevTeam.Add(PrimaryBuildTargetGUID, DevTeamIDDictionary); if(TargetAttributes.ContainsKey(PrimaryBuildTargetGUID)) { object ExistingPrimaryBuildTargetObj = TargetAttributes[PrimaryBuildTargetGUID]; if(ExistingPrimaryBuildTargetObj != null) { PBXDictionary ExistingPrimaryBuildTarget = (PBXDictionary)ExistingPrimaryBuildTargetObj; if(!ExistingPrimaryBuildTarget.ContainsKey("DevelopmentTeam")) { ExistingPrimaryBuildTarget.Append(DevTeamIDDictionary); IgorDebug.Log(ModuleInst, "Added Development Team to XCodeProj."); } else { IgorDebug.Log(ModuleInst, "Development Team already set up in XCodeProj."); } } else { IgorDebug.LogError(ModuleInst, "Primary build target already has a key in TargetAttributes, but the value stored is invalid."); } } else { TargetAttributes.Append(PrimaryBuildTargetToDevTeam); IgorDebug.Log(ModuleInst, "Added Development Team to XCodeProj."); } CurrentProject.Save(); } } } } } } } public static void AddOrUpdateForAllBuildProducts(IIgorModule ModuleInst, string ProjectPath, string Key, string Value) { if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); foreach(KeyValuePair<string, XCBuildConfiguration> CurrentConfig in CurrentProject.buildConfigurations) { object BuildSettingsObj = CurrentConfig.Value.data["buildSettings"]; PBXDictionary BuildSettingsDict = (PBXDictionary)BuildSettingsObj; if(BuildSettingsDict.ContainsKey(Key)) { BuildSettingsDict[Key] = Value; IgorDebug.Log(ModuleInst, "Updated KeyValuePair (Key: " + Key + " Value: " + Value + ") to build target GUID " + CurrentConfig.Key); } else { BuildSettingsDict.Add(Key, Value); IgorDebug.Log(ModuleInst, "Added new KeyValuePair (Key: " + Key + " Value: " + Value + ") to build target GUID " + CurrentConfig.Key); } } CurrentProject.Save(); } } public static void AddFrameworkSearchPath(IIgorModule ModuleInst, string ProjectPath, string NewPath) { if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); CurrentProject.AddFrameworkSearchPaths(NewPath); IgorDebug.Log(ModuleInst, "Added framework search path " + NewPath); CurrentProject.Save(); } } public static string AddNewFileReference(IIgorModule ModuleInst, string ProjectPath, string Filename, TreeEnum TreeBase, string Path = "", int FileEncoding = -1, string LastKnownFileType = "", string Name = "") { if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); foreach(KeyValuePair<string, PBXFileReference> CurrentFileRef in CurrentProject.fileReferences) { if(CurrentFileRef.Value.name == Filename) { IgorDebug.Log(ModuleInst, "The file " + Filename + " is already referenced in the XCodeProj."); return CurrentFileRef.Value.guid; } } PBXFileReference NewFile = new PBXFileReference(Filename, TreeBase); if(Path != "") { if(NewFile.ContainsKey("path")) { NewFile.Remove("path"); } NewFile.Add("path", Path); } if(FileEncoding != -1) { if(NewFile.ContainsKey("fileEncoding")) { NewFile.Remove("fileEncoding"); } NewFile.Add("fileEncoding", FileEncoding); } if(LastKnownFileType != "") { if(NewFile.ContainsKey("lastKnownFileType")) { NewFile.Remove("lastKnownFileType"); } NewFile.Add("lastKnownFileType", LastKnownFileType); } if(Name != "") { if(NewFile.ContainsKey("name")) { NewFile.Remove("name"); } NewFile.Add("name", Name); } CurrentProject.fileReferences.Add(NewFile); IgorDebug.Log(ModuleInst, "File " + Filename + " has been added to the XCodeProj."); CurrentProject.Save(); return NewFile.guid; } return ""; } public static string AddNewBuildFile(IIgorModule ModuleInst, string ProjectPath, string FileRefGUID) { if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); foreach(KeyValuePair<string, PBXBuildFile> CurrentBuildFile in CurrentProject.buildFiles) { if(IgorAssert.EnsureTrue(ModuleInst, CurrentBuildFile.Value.ContainsKey("fileRef"), "PBXBuildFile doesn't contain a key for fileRef.")) { if(CurrentBuildFile.Value.data["fileRef"] == FileRefGUID) { IgorDebug.Log(ModuleInst, "The file GUID " + FileRefGUID + " already has an associated BuildFile in the XCodeProj."); return CurrentBuildFile.Value.guid; } } } foreach(KeyValuePair<string, PBXFileReference> CurrentFileRef in CurrentProject.fileReferences) { if(CurrentFileRef.Value.guid == FileRefGUID) { PBXBuildFile NewBuildFile = new PBXBuildFile(CurrentFileRef.Value); CurrentProject.buildFiles.Add(NewBuildFile); IgorDebug.Log(ModuleInst, "BuildFile for FileRefGUID " + FileRefGUID + " has been added to the XCodeProj."); CurrentProject.Save(); return NewBuildFile.guid; } } } return ""; } public static void AddFramework(IIgorModule ModuleInst, string ProjectPath, string Filename, TreeEnum TreeBase, string Path = "", int FileEncoding = -1, string LastKnownFileType = "", string Name = "") { string FrameworkFileRefGUID = AddNewFileReference(ModuleInst, ProjectPath, Filename, TreeBase, Path, FileEncoding, LastKnownFileType, Name); if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); if(IgorAssert.EnsureTrue(ModuleInst, CurrentProject != null, "XCodeProj couldn't be loaded.")) { bool bFoundFrameworksGroup = false; foreach(KeyValuePair<string, PBXGroup> CurrentGroup in CurrentProject.groups) { if(CurrentGroup.Value.name == "Frameworks") { if(IgorAssert.EnsureTrue(ModuleInst, CurrentGroup.Value.ContainsKey("children"), "XCodeProj Frameworks PBXGroup doesn't have a children array.")) { object FrameworkChildrenObj = CurrentGroup.Value.data["children"]; if(IgorAssert.EnsureTrue(ModuleInst, FrameworkChildrenObj != null, "XCodeProj Frameworks PBXGroup has a children key, but it can't be retrieved.")) { if(IgorAssert.EnsureTrue(ModuleInst, typeof(PBXList).IsAssignableFrom(FrameworkChildrenObj.GetType()), "XCodeProj Frameworks PBXGroup has a children key, but it can't be cast to PBXList.")) { PBXList FrameworkChildrenList = (PBXList)FrameworkChildrenObj; if(IgorAssert.EnsureTrue(ModuleInst, FrameworkChildrenList != null, "XCodeProj casted Framework Children List is null.")) { if(FrameworkChildrenList.Contains(FrameworkFileRefGUID)) { IgorDebug.Log(ModuleInst, "Framework " + Filename + " has already been added to the Framework Group " + CurrentGroup.Key + "."); } else { FrameworkChildrenList.Add(FrameworkFileRefGUID); CurrentGroup.Value.data["children"] = FrameworkChildrenList; IgorDebug.Log(ModuleInst, "Added the " + Filename + " framework to the Framework Group " + CurrentGroup.Key + "."); } } } } bFoundFrameworksGroup = true; break; } } } IgorAssert.EnsureTrue(ModuleInst, bFoundFrameworksGroup, "Couldn't find a Frameworks PBXGroup in the XCodeProj."); CurrentProject.Save(); } } string FrameworkBuildFileGUID = AddNewBuildFile(ModuleInst, ProjectPath, FrameworkFileRefGUID); if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); if(IgorAssert.EnsureTrue(ModuleInst, CurrentProject != null, "XCodeProj couldn't be loaded.")) { foreach(KeyValuePair<string, PBXFrameworksBuildPhase> CurrentTarget in CurrentProject.frameworkBuildPhases) { if(IgorAssert.EnsureTrue(ModuleInst, CurrentTarget.Value.ContainsKey("files"), "XCodeProj Framework Build Phase doesn't have a files array.")) { object FrameworkFilesObj = CurrentTarget.Value.data["files"]; if(IgorAssert.EnsureTrue(ModuleInst, FrameworkFilesObj != null, "XCodeProj Framework Build Phase has a files key, but it can't be retrieved.")) { if(IgorAssert.EnsureTrue(ModuleInst, typeof(PBXList).IsAssignableFrom(FrameworkFilesObj.GetType()), "XCodeProj Framework Build Phase has a files key, but it can't be cast to PBXList.")) { PBXList FrameworkFilesList = (PBXList)FrameworkFilesObj; if(IgorAssert.EnsureTrue(ModuleInst, FrameworkFilesList != null, "XCodeProj casted Framework File List is null.")) { if(FrameworkFilesList.Contains(FrameworkBuildFileGUID)) { IgorDebug.Log(ModuleInst, "Framework " + Filename + " has already been added to the Framework Build Phase " + CurrentTarget.Key + "."); } else { FrameworkFilesList.Add(FrameworkBuildFileGUID); CurrentTarget.Value.data["files"] = FrameworkFilesList; IgorDebug.Log(ModuleInst, "Added the " + Filename + " framework to the Framework Build Phase " + CurrentTarget.Key + "."); } } } } } } CurrentProject.Save(); } } } public static void SortGUIDIntoGroup(IIgorModule ModuleInst, string ProjectPath, string FileGUID, string GroupPath) { if(IgorAssert.EnsureTrue(ModuleInst, Directory.Exists(ProjectPath), "XCodeProj doesn't exist at path " + ProjectPath)) { XCProject CurrentProject = new XCProject(ProjectPath); CurrentProject.Backup(); if(IgorAssert.EnsureTrue(ModuleInst, CurrentProject != null, "XCodeProj couldn't be loaded.")) { bool bFoundGroup = false; foreach(KeyValuePair<string, PBXGroup> CurrentGroup in CurrentProject.groups) { if(CurrentGroup.Value.path == GroupPath) { if(IgorAssert.EnsureTrue(ModuleInst, CurrentGroup.Value.ContainsKey("children"), "XCodeProj PBXGroup " + GroupPath + " doesn't have a children array.")) { object GroupChildrenObj = CurrentGroup.Value.data["children"]; if(IgorAssert.EnsureTrue(ModuleInst, GroupChildrenObj != null, "XCodeProj PBXGroup " + GroupPath + " has a children key, but it can't be retrieved.")) { if(IgorAssert.EnsureTrue(ModuleInst, typeof(PBXList).IsAssignableFrom(GroupChildrenObj.GetType()), "XCodeProj PBXGroup " + GroupPath + " has a children key, but it can't be cast to PBXList.")) { PBXList GroupChildrenList = (PBXList)GroupChildrenObj; if(IgorAssert.EnsureTrue(ModuleInst, GroupChildrenList != null, "XCodeProj casted Children List is null.")) { if(GroupChildrenList.Contains(FileGUID)) { IgorDebug.Log(ModuleInst, "FileGUID " + FileGUID + " has already been added to the Group " + CurrentGroup.Key + "."); } else { GroupChildrenList.Add(FileGUID); CurrentGroup.Value.data["children"] = GroupChildrenList; IgorDebug.Log(ModuleInst, "Added the " + FileGUID + " file to the Group " + CurrentGroup.Key + "."); } } } } bFoundGroup = true; break; } } } IgorAssert.EnsureTrue(ModuleInst, bFoundGroup, "Couldn't find a PBXGroup with path " + GroupPath + " in the XCodeProj."); CurrentProject.Save(); } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Azure.Management.SiteRecovery.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices { /// <summary> /// Definition of vault extended info operations for the Site Recovery /// extension. /// </summary> internal partial class VaultExtendedInfoOperations : IServiceOperations<RecoveryServicesManagementClient>, IVaultExtendedInfoOperations { /// <summary> /// Initializes a new instance of the VaultExtendedInfoOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VaultExtendedInfoOperations(RecoveryServicesManagementClient client) { this._client = client; } private RecoveryServicesManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.RecoveryServicesManagementClient. /// </summary> public RecoveryServicesManagementClient Client { get { return this._client; } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Required. Create resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs == null) { throw new ArgumentNullException("extendedInfoArgs"); } if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "CreateExtendedInfoAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.SiteRecovery"; url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject resourceExtendedInformationArgsValue = new JObject(); requestDoc = resourceExtendedInformationArgsValue; resourceExtendedInformationArgsValue["ContractVersion"] = extendedInfoArgs.ContractVersion; resourceExtendedInformationArgsValue["ExtendedInfo"] = extendedInfoArgs.ExtendedInfo; resourceExtendedInformationArgsValue["ExtendedInfoETag"] = extendedInfoArgs.ExtendedInfoETag; requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode >= HttpStatusCode.BadRequest) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> GetExtendedInfoAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetExtendedInfoAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.SiteRecovery"; url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["ResourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["ExtendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["ExtendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["ResourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["ResourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["SubscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='extendedInfoArgs'> /// Optional. Update resource exnteded info input parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the resource extended information object /// </returns> public async Task<ResourceExtendedInformationResponse> UpdateExtendedInfoAsync(string resourceGroupName, string resourceName, ResourceExtendedInformationArgs extendedInfoArgs, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (extendedInfoArgs != null) { if (extendedInfoArgs.ContractVersion == null) { throw new ArgumentNullException("extendedInfoArgs.ContractVersion"); } if (extendedInfoArgs.ExtendedInfo == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfo"); } if (extendedInfoArgs.ExtendedInfoETag == null) { throw new ArgumentNullException("extendedInfoArgs.ExtendedInfoETag"); } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("extendedInfoArgs", extendedInfoArgs); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateExtendedInfoAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.SiteRecovery"; url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/ExtendedInfo"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ResourceExtendedInformationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ResourceExtendedInformationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ResourceExtendedInformation extendedInformationInstance = new ResourceExtendedInformation(); result.ResourceExtendedInformation = extendedInformationInstance; JToken resourceGroupNameValue = responseDoc["ResourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); extendedInformationInstance.ResourceGroupName = resourceGroupNameInstance; } JToken extendedInfoValue = responseDoc["ExtendedInfo"]; if (extendedInfoValue != null && extendedInfoValue.Type != JTokenType.Null) { string extendedInfoInstance = ((string)extendedInfoValue); extendedInformationInstance.ExtendedInfo = extendedInfoInstance; } JToken extendedInfoETagValue = responseDoc["ExtendedInfoETag"]; if (extendedInfoETagValue != null && extendedInfoETagValue.Type != JTokenType.Null) { string extendedInfoETagInstance = ((string)extendedInfoETagValue); extendedInformationInstance.ExtendedInfoETag = extendedInfoETagInstance; } JToken resourceIdValue = responseDoc["ResourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); extendedInformationInstance.ResourceId = resourceIdInstance; } JToken resourceNameValue = responseDoc["ResourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); extendedInformationInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = responseDoc["ResourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); extendedInformationInstance.ResourceType = resourceTypeInstance; } JToken subscriptionIdValue = responseDoc["SubscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { Guid subscriptionIdInstance = Guid.Parse(((string)subscriptionIdValue)); extendedInformationInstance.SubscriptionId = subscriptionIdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get the vault extended info. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group containing the job /// collection. /// </param> /// <param name='resourceName'> /// Required. The name of the resource. /// </param> /// <param name='parameters'> /// Required. Upload Vault Certificate input parameters. /// </param> /// <param name='certFriendlyName'> /// Required. Certificate friendly name /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the upload certificate response /// </returns> public async Task<UploadCertificateResponse> UploadCertificateAsync(string resourceGroupName, string resourceName, CertificateArgs parameters, string certFriendlyName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (certFriendlyName == null) { throw new ArgumentNullException("certFriendlyName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("certFriendlyName", certFriendlyName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UploadCertificateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.SiteRecovery"; url = url + "/"; url = url + "SiteRecoveryVault"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certFriendlyName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-03-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject parametersValue = new JObject(); requestDoc = parametersValue; if (parameters.Properties != null) { if (parameters.Properties is ILazyCollection == false || ((ILazyCollection)parameters.Properties).IsInitialized) { JObject propertiesDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Properties) { string propertiesKey = pair.Key; string propertiesValue = pair.Value; propertiesDictionary[propertiesKey] = propertiesValue; } parametersValue["properties"] = propertiesDictionary; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UploadCertificateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UploadCertificateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { CertificateProperties propertiesInstance = new CertificateProperties(); result.Properties = propertiesInstance; JToken friendlyNameValue = propertiesValue2["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); propertiesInstance.FriendlyName = friendlyNameInstance; } JToken globalAcsHostNameValue = propertiesValue2["globalAcsHostName"]; if (globalAcsHostNameValue != null && globalAcsHostNameValue.Type != JTokenType.Null) { string globalAcsHostNameInstance = ((string)globalAcsHostNameValue); propertiesInstance.GlobalAcsHostName = globalAcsHostNameInstance; } JToken globalAcsNamespaceValue = propertiesValue2["globalAcsNamespace"]; if (globalAcsNamespaceValue != null && globalAcsNamespaceValue.Type != JTokenType.Null) { string globalAcsNamespaceInstance = ((string)globalAcsNamespaceValue); propertiesInstance.GlobalAcsNamespace = globalAcsNamespaceInstance; } JToken globalAcsRPRealmValue = propertiesValue2["globalAcsRPRealm"]; if (globalAcsRPRealmValue != null && globalAcsRPRealmValue.Type != JTokenType.Null) { string globalAcsRPRealmInstance = ((string)globalAcsRPRealmValue); propertiesInstance.GlobalAcsRPRealm = globalAcsRPRealmInstance; } JToken resourceIdValue = propertiesValue2["resourceId"]; if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null) { long resourceIdInstance = ((long)resourceIdValue); propertiesInstance.ResourceId = resourceIdInstance; } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Threading.Tasks; namespace Orleans.Streams { public static class AsyncObservableExtensions { private static readonly Func<Exception, Task> DefaultOnError = _ => Task.CompletedTask; private static readonly Func<Task> DefaultOnCompleted = () => Task.CompletedTask; /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="onErrorAsync">Delegte that is called for IAsyncObserver.OnErrorAsync.</param> /// <param name="onCompletedAsync">Delegte that is called for IAsyncObserver.OnCompletedAsync.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed.</returns> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, Func<Exception, Task> onErrorAsync, Func<Task> onCompletedAsync) { var genericObserver = new GenericAsyncObserver<T>(onNextAsync, onErrorAsync, onCompletedAsync); return obs.SubscribeAsync(genericObserver); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="onErrorAsync">Delegte that is called for IAsyncObserver.OnErrorAsync.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed.</returns> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, Func<Exception, Task> onErrorAsync) { return obs.SubscribeAsync(onNextAsync, onErrorAsync, DefaultOnCompleted); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="onCompletedAsync">Delegte that is called for IAsyncObserver.OnCompletedAsync.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed.</returns> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, Func<Task> onCompletedAsync) { return obs.SubscribeAsync(onNextAsync, DefaultOnError, onCompletedAsync); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed.</returns> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync) { return obs.SubscribeAsync(onNextAsync, DefaultOnError, DefaultOnCompleted); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="onErrorAsync">Delegte that is called for IAsyncObserver.OnErrorAsync.</param> /// <param name="onCompletedAsync">Delegte that is called for IAsyncObserver.OnCompletedAsync.</param> /// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param> /// <param name="filterFunc">Filter to be applied for this subscription</param> /// <param name="filterData">Data object that will be passed in to the filterFunc. /// This will usually contain any paramaters required by the filterFunc to make it's filtering decision.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed. /// </returns> /// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable. /// Usually this is because it is not a static method. </exception> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, Func<Exception, Task> onErrorAsync, Func<Task> onCompletedAsync, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { var genericObserver = new GenericAsyncObserver<T>(onNextAsync, onErrorAsync, onCompletedAsync); return obs.SubscribeAsync(genericObserver, token, filterFunc, filterData); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="onErrorAsync">Delegte that is called for IAsyncObserver.OnErrorAsync.</param> /// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param> /// <param name="filterFunc">Filter to be applied for this subscription</param> /// <param name="filterData">Data object that will be passed in to the filterFunc. /// This will usually contain any paramaters required by the filterFunc to make it's filtering decision.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed. /// </returns> /// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable. /// Usually this is because it is not a static method. </exception> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, Func<Exception, Task> onErrorAsync, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { return obs.SubscribeAsync(onNextAsync, onErrorAsync, DefaultOnCompleted, token, filterFunc, filterData); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="onCompletedAsync">Delegte that is called for IAsyncObserver.OnCompletedAsync.</param> /// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param> /// <param name="filterFunc">Filter to be applied for this subscription</param> /// <param name="filterData">Data object that will be passed in to the filterFunc. /// This will usually contain any paramaters required by the filterFunc to make it's filtering decision.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed. /// </returns> /// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable. /// Usually this is because it is not a static method. </exception> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, Func<Task> onCompletedAsync, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { return obs.SubscribeAsync(onNextAsync, DefaultOnError, onCompletedAsync, token, filterFunc, filterData); } /// <summary> /// Subscribe a consumer to this observable using delegates. /// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the /// handler methods instead of requiring an instance of IAsyncObserver. /// </summary> /// <typeparam name="T">The type of object produced by the observable.</typeparam> /// <param name="obs">The Observable object.</param> /// <param name="onNextAsync">Delegte that is called for IAsyncObserver.OnNextAsync.</param> /// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param> /// <param name="filterFunc">Filter to be applied for this subscription</param> /// <param name="filterData">Data object that will be passed in to the filterFunc. /// This will usually contain any paramaters required by the filterFunc to make it's filtering decision.</param> /// <returns>A promise for a StreamSubscriptionHandle that represents the subscription. /// The consumer may unsubscribe by using this handle. /// The subscription remains active for as long as it is not explicitely unsubscribed. /// </returns> /// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable. /// Usually this is because it is not a static method. </exception> public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs, Func<T, StreamSequenceToken, Task> onNextAsync, StreamSequenceToken token, StreamFilterPredicate filterFunc = null, object filterData = null) { return obs.SubscribeAsync(onNextAsync, DefaultOnError, DefaultOnCompleted, token, filterFunc, filterData); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Newtonsoft.Json; using NodaTime; using NUnit.Framework; using Python.Runtime; using QuantConnect.Algorithm; using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Indicators; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Lean.Engine.HistoricalData; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Packets; using QuantConnect.Scheduling; using QuantConnect.Securities; namespace QuantConnect.Tests.Common.Util { [TestFixture] public class ExtensionsTests { [TestCase("A", "a")] [TestCase("", "")] [TestCase(null, null)] [TestCase("Buy", "buy")] [TestCase("BuyTheDip", "buyTheDip")] public void ToCamelCase(string toConvert, string expected) { Assert.AreEqual(expected, toConvert.ToCamelCase()); } [Test] public void BatchAlphaResultPacket() { var btcusd = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX); var insights = new List<Insight> { new Insight(DateTime.UtcNow, btcusd, Time.OneMillisecond, InsightType.Price, InsightDirection.Up, 1, 2, "sourceModel1"), new Insight(DateTime.UtcNow, btcusd, Time.OneSecond, InsightType.Price, InsightDirection.Down, 1, 2, "sourceModel1") }; var orderEvents = new List<OrderEvent> { new OrderEvent(1, btcusd, DateTime.UtcNow, OrderStatus.Submitted, OrderDirection.Buy, 0, 0, OrderFee.Zero, message: "OrderEvent1"), new OrderEvent(1, btcusd, DateTime.UtcNow, OrderStatus.Filled, OrderDirection.Buy, 1, 1000, OrderFee.Zero, message: "OrderEvent2") }; var orders = new List<Order> { new MarketOrder(btcusd, 1000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 } }; var packet1 = new AlphaResultPacket("1", 1, insights: insights); var packet2 = new AlphaResultPacket("1", 1, orders: orders); var packet3 = new AlphaResultPacket("1", 1, orderEvents: orderEvents); var result = new List<AlphaResultPacket> { packet1, packet2, packet3 }.Batch(); Assert.AreEqual(2, result.Insights.Count); Assert.AreEqual(2, result.OrderEvents.Count); Assert.AreEqual(1, result.Orders.Count); Assert.IsTrue(result.Insights.SequenceEqual(insights)); Assert.IsTrue(result.OrderEvents.SequenceEqual(orderEvents)); Assert.IsTrue(result.Orders.SequenceEqual(orders)); Assert.IsNull(new List<AlphaResultPacket>().Batch()); } [Test] public void BatchAlphaResultPacketDuplicateOrder() { var btcusd = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.GDAX); var orders = new List<Order> { new MarketOrder(btcusd, 1000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 }, new MarketOrder(btcusd, 100, DateTime.UtcNow, "ExpensiveOrder") { Id = 2 }, new MarketOrder(btcusd, 2000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 }, new MarketOrder(btcusd, 10, DateTime.UtcNow, "ExpensiveOrder") { Id = 3 }, new MarketOrder(btcusd, 3000, DateTime.UtcNow, "ExpensiveOrder") { Id = 1 } }; var orders2 = new List<Order> { new MarketOrder(btcusd, 200, DateTime.UtcNow, "ExpensiveOrder") { Id = 2 }, new MarketOrder(btcusd, 20, DateTime.UtcNow, "ExpensiveOrder") { Id = 3 } }; var packet1 = new AlphaResultPacket("1", 1, orders: orders); var packet2 = new AlphaResultPacket("1", 1, orders: orders2); var result = new List<AlphaResultPacket> { packet1, packet2 }.Batch(); // we expect just 1 order instance per order id Assert.AreEqual(3, result.Orders.Count); Assert.IsTrue(result.Orders.Any(order => order.Id == 1 && order.Quantity == 3000)); Assert.IsTrue(result.Orders.Any(order => order.Id == 2 && order.Quantity == 200)); Assert.IsTrue(result.Orders.Any(order => order.Id == 3 && order.Quantity == 20)); var expected = new List<Order> { orders[4], orders2[0], orders2[1] }; Assert.IsTrue(result.Orders.SequenceEqual(expected)); } [Test] public void SeriesIsNotEmpty() { var series = new Series("SadSeries") { Values = new List<ChartPoint> { new ChartPoint(1, 1) } }; Assert.IsFalse(series.IsEmpty()); } [Test] public void SeriesIsEmpty() { Assert.IsTrue((new Series("Cat")).IsEmpty()); } [Test] public void ChartIsEmpty() { Assert.IsTrue((new Chart("HappyChart")).IsEmpty()); } [Test] public void ChartIsEmptyWithEmptySeries() { Assert.IsTrue((new Chart("HappyChart") { Series = new Dictionary<string, Series> { { "SadSeries", new Series("SadSeries") } }}).IsEmpty()); } [Test] public void ChartIsNotEmptyWithNonEmptySeries() { var series = new Series("SadSeries") { Values = new List<ChartPoint> { new ChartPoint(1, 1) } }; Assert.IsFalse((new Chart("HappyChart") { Series = new Dictionary<string, Series> { { "SadSeries", series } } }).IsEmpty()); } [Test] public void IsSubclassOfGenericWorksWorksForNonGenericType() { Assert.IsTrue(typeof(Derived2).IsSubclassOfGeneric(typeof(Derived1))); } [Test] public void IsSubclassOfGenericWorksForGenericTypeWithParameter() { Assert.IsTrue(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<int>))); Assert.IsFalse(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<bool>))); } [Test] public void IsSubclassOfGenericWorksForGenericTypeDefinitions() { Assert.IsTrue(typeof(Derived1).IsSubclassOfGeneric(typeof(Super<>))); Assert.IsTrue(typeof(Derived2).IsSubclassOfGeneric(typeof(Super<>))); } [Test] public void DateTimeRoundDownFullDayDoesntRoundDownByDay() { var date = new DateTime(2000, 01, 01); var rounded = date.RoundDown(TimeSpan.FromDays(1)); Assert.AreEqual(date, rounded); } [Test] public void GetBetterTypeNameHandlesRecursiveGenericTypes() { var type = typeof (Dictionary<List<int>, Dictionary<int, string>>); const string expected = "Dictionary<List<Int32>, Dictionary<Int32, String>>"; var actual = type.GetBetterTypeName(); Assert.AreEqual(expected, actual); } [Test] public void ExchangeRoundDownSkipsWeekends() { var time = new DateTime(2015, 05, 02, 18, 01, 00); var expected = new DateTime(2015, 05, 01); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.FXCM, null, SecurityType.Forex); var exchangeRounded = time.ExchangeRoundDown(Time.OneDay, hours, false); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ExchangeRoundDownHandlesMarketOpenTime() { var time = new DateTime(2016, 1, 25, 9, 31, 0); var expected = time.Date; var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity); var exchangeRounded = time.ExchangeRoundDown(Time.OneDay, hours, false); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ConvertToSkipsDiscontinuitiesBecauseOfDaylightSavingsStart_AddingOneHour() { var expected = new DateTime(2014, 3, 9, 3, 0, 0); var time = new DateTime(2014, 3, 9, 2, 0, 0).ConvertTo(TimeZones.NewYork, TimeZones.NewYork); var time2 = new DateTime(2014, 3, 9, 2, 0, 1).ConvertTo(TimeZones.NewYork, TimeZones.NewYork); Assert.AreEqual(expected, time); Assert.AreEqual(expected, time2); } [Test] public void ConvertToIgnoreDaylightSavingsEnd_SubtractingOneHour() { var time1Expected = new DateTime(2014, 11, 2, 1, 59, 59); var time2Expected = new DateTime(2014, 11, 2, 2, 0, 0); var time3Expected = new DateTime(2014, 11, 2, 2, 0, 1); var time1 = time1Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork); var time2 = time2Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork); var time3 = time3Expected.ConvertTo(TimeZones.NewYork, TimeZones.NewYork); Assert.AreEqual(time1Expected, time1); Assert.AreEqual(time2Expected, time2); Assert.AreEqual(time3Expected, time3); } [Test] public void ExchangeRoundDownInTimeZoneSkipsWeekends() { // moment before EST market open in UTC (time + one day) var time = new DateTime(2017, 10, 01, 9, 29, 59).ConvertToUtc(TimeZones.NewYork); var expected = new DateTime(2017, 09, 29).ConvertFromUtc(TimeZones.NewYork); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneDay, hours, TimeZones.Utc, false); Assert.AreEqual(expected, exchangeRounded); } [Test] // This unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, in ExchangeRoundDownInTimeZone, GH issue 2368. public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_UTC() { var time = new DateTime(2014, 3, 9, 16, 0, 1); var expected = new DateTime(2014, 3, 7, 16, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, false); Assert.AreEqual(expected, exchangeRounded); } [Test] // This unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, in ExchangeRoundDownInTimeZone, GH issue 2368. public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_UTC() { var time = new DateTime(2014, 11, 2, 2, 0, 1); var expected = new DateTime(2014, 10, 31, 16, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, false); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_ExtendedHours_UTC() { var time = new DateTime(2014, 3, 9, 2, 0, 1); var expected = new DateTime(2014, 3, 9, 2, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, true); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_ExtendedHours_UTC() { var time = new DateTime(2014, 11, 2, 2, 0, 1); var expected = new DateTime(2014, 11, 2, 2, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.Utc, true); Assert.AreEqual(expected, exchangeRounded); } [Test] // this unit test reproduces a fixed infinite loop situation, due to a daylight saving time change, GH issue 3707. public void RoundDownInTimeZoneAroundDaylightTimeChanges() { // sydney time advanced Sunday, 6 October 2019, 02:00:00 clocks were turned forward 1 hour to // Sunday, 6 October 2019, 03:00:00 local daylight time instead. var timeAt = new DateTime(2019, 10, 6, 10, 0, 0); var expected = new DateTime(2019, 10, 5, 10, 0, 0); var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneDay, TimeZones.Sydney, TimeZones.Utc); // even though there is an entire 'roundingInterval' unit (1 day) between 'timeAt' and 'expected' round down // is affected by daylight savings and rounds down the timeAt Assert.AreEqual(expected, exchangeRoundedAt); timeAt = new DateTime(2019, 10, 7, 10, 0, 0); expected = new DateTime(2019, 10, 6, 11, 0, 0); exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneDay, TimeZones.Sydney, TimeZones.Utc); Assert.AreEqual(expected, exchangeRoundedAt); } [Test] public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_AddingOneHour_UTC() { var timeAt = new DateTime(2014, 3, 9, 2, 0, 0); var timeAfter = new DateTime(2014, 3, 9, 2, 0, 1); var timeBefore = new DateTime(2014, 3, 9, 1, 59, 59); var timeAfterDaylightTimeChanges = new DateTime(2014, 3, 9, 3, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var expected = new DateTime(2014, 3, 9, 3, 0, 0); Assert.AreEqual(expected, exchangeRoundedAt); Assert.AreEqual(expected, exchangeRoundedAfter); Assert.AreEqual(timeBefore, exchangeRoundedBefore); Assert.AreEqual(expected, exchangeRoundedAfterDaylightTimeChanges); } [Test] public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_UTC() { var timeAt = new DateTime(2014, 11, 2, 2, 0, 0); var timeAfter = new DateTime(2014, 11, 2, 2, 0, 1); var timeBefore = new DateTime(2014, 11, 2, 1, 59, 59); var timeAfterDaylightTimeChanges = new DateTime(2014, 11, 2, 3, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.Utc); Assert.AreEqual(timeAt, exchangeRoundedAt); Assert.AreEqual(timeAfter, exchangeRoundedAfter); Assert.AreEqual(timeBefore, exchangeRoundedBefore); Assert.AreEqual(timeAfterDaylightTimeChanges, exchangeRoundedAfterDaylightTimeChanges); } [Test] public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_NewYork() { var time = new DateTime(2014, 3, 9, 16, 0, 1); var expected = new DateTime(2014, 3, 7, 16, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, false); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_NewYork() { var time = new DateTime(2014, 11, 2, 2, 0, 1); var expected = new DateTime(2014, 10, 31, 16, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, false); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_AddingOneHour_ExtendedHours_NewYork() { var time = new DateTime(2014, 3, 9, 2, 0, 1); var expected = new DateTime(2014, 3, 9, 2, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, true); Assert.AreEqual(expected, exchangeRounded); } [Test] public void ExchangeRoundDownInTimeZoneCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_ExtendedHours_NewYork() { var time = new DateTime(2014, 11, 2, 2, 0, 1); var expected = new DateTime(2014, 11, 2, 2, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.GDAX, null, SecurityType.Crypto); var exchangeRounded = time.ExchangeRoundDownInTimeZone(Time.OneHour, hours, TimeZones.NewYork, true); Assert.AreEqual(expected, exchangeRounded); } [Test] public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_AddingOneHour_NewYork() { var timeAt = new DateTime(2014, 3, 9, 2, 0, 0); var timeAfter = new DateTime(2014, 3, 9, 2, 0, 1); var timeBefore = new DateTime(2014, 3, 9, 1, 59, 59); var timeAfterDaylightTimeChanges = new DateTime(2014, 3, 9, 3, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var expected = new DateTime(2014, 3, 9, 3, 0, 0); Assert.AreEqual(expected, exchangeRoundedAt); Assert.AreEqual(expected, exchangeRoundedAfter); Assert.AreEqual(timeBefore, exchangeRoundedBefore); Assert.AreEqual(expected, exchangeRoundedAfterDaylightTimeChanges); } [Test] public void RoundDownInTimeZoneReturnsCorrectValuesAroundDaylightTimeChanges_SubtractingOneHour_NewYork() { var timeAt = new DateTime(2014, 11, 2, 2, 0, 0); var timeAfter = new DateTime(2014, 11, 2, 2, 0, 1); var timeBefore = new DateTime(2014, 11, 2, 1, 59, 59); var timeAfterDaylightTimeChanges = new DateTime(2014, 11, 2, 3, 0, 0); var hours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Oanda, null, SecurityType.Forex); var exchangeRoundedAt = timeAt.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var exchangeRoundedAfter = timeAfter.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var exchangeRoundedBefore = timeBefore.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); var exchangeRoundedAfterDaylightTimeChanges = timeAfterDaylightTimeChanges.RoundDownInTimeZone(Time.OneSecond, hours.TimeZone, TimeZones.NewYork); Assert.AreEqual(timeAt, exchangeRoundedAt); Assert.AreEqual(timeAfter, exchangeRoundedAfter); Assert.AreEqual(timeBefore, exchangeRoundedBefore); Assert.AreEqual(timeAfterDaylightTimeChanges, exchangeRoundedAfterDaylightTimeChanges); } [Test] public void ConvertsInt32FromString() { const string input = "12345678"; var value = input.ToInt32(); Assert.AreEqual(12345678, value); } [Test] public void ConvertsInt32FromStringWithDecimalTruncation() { const string input = "12345678.9"; var value = input.ToInt32(); Assert.AreEqual(12345678, value); } [Test] public void ConvertsInt64FromString() { const string input = "12345678900"; var value = input.ToInt64(); Assert.AreEqual(12345678900, value); } [Test] public void ConvertsInt64FromStringWithDecimalTruncation() { const string input = "12345678900.12"; var value = input.ToInt64(); Assert.AreEqual(12345678900, value); } [Test] public void ToCsvDataParsesCorrectly() { var csv = "\"hello\",\"world\"".ToCsvData(); Assert.AreEqual(2, csv.Count); Assert.AreEqual("\"hello\"", csv[0]); Assert.AreEqual("\"world\"", csv[1]); var csv2 = "1,2,3,4".ToCsvData(); Assert.AreEqual(4, csv2.Count); Assert.AreEqual("1", csv2[0]); Assert.AreEqual("2", csv2[1]); Assert.AreEqual("3", csv2[2]); Assert.AreEqual("4", csv2[3]); } [Test] public void ToCsvDataParsesEmptyFinalValue() { var line = "\"hello\",world,"; var csv = line.ToCsvData(); Assert.AreEqual(3, csv.Count); Assert.AreEqual("\"hello\"", csv[0]); Assert.AreEqual("hello", csv[0].Trim('"')); Assert.AreEqual("world", csv[1]); Assert.AreEqual(string.Empty, csv[2]); } [Test] public void ToCsvDataParsesEmptyValue() { Assert.AreEqual(string.Empty, string.Empty.ToCsvData()[0]); } [Test] public void ConvertsDecimalFromString() { const string input = "123.45678"; var value = input.ToDecimal(); Assert.AreEqual(123.45678m, value); } [Test] public void ConvertsDecimalFromStringWithExtraWhiteSpace() { const string input = " 123.45678 "; var value = input.ToDecimal(); Assert.AreEqual(123.45678m, value); } [Test] public void ConvertsDecimalFromIntStringWithExtraWhiteSpace() { const string input = " 12345678 "; var value = input.ToDecimal(); Assert.AreEqual(12345678m, value); } [Test] public void ConvertsZeroDecimalFromString() { const string input = "0.45678"; var value = input.ToDecimal(); Assert.AreEqual(0.45678m, value); } [Test] public void ConvertsOneNumberDecimalFromString() { const string input = "1.45678"; var value = input.ToDecimal(); Assert.AreEqual(1.45678m, value); } [Test] public void ConvertsZeroDecimalValueFromString() { const string input = "0"; var value = input.ToDecimal(); Assert.AreEqual(0m, value); } [Test] public void ConvertsEmptyDecimalValueFromString() { const string input = ""; var value = input.ToDecimal(); Assert.AreEqual(0m, value); } [Test] public void ConvertsNegativeDecimalFromString() { const string input = "-123.45678"; var value = input.ToDecimal(); Assert.AreEqual(-123.45678m, value); } [Test] public void ConvertsNegativeDecimalFromStringWithExtraWhiteSpace() { const string input = " -123.45678 "; var value = input.ToDecimal(); Assert.AreEqual(-123.45678m, value); } [Test] public void ConvertsNegativeDecimalFromIntStringWithExtraWhiteSpace() { const string input = " -12345678 "; var value = input.ToDecimal(); Assert.AreEqual(-12345678m, value); } [Test] public void ConvertsNegativeZeroDecimalFromString() { const string input = "-0.45678"; var value = input.ToDecimal(); Assert.AreEqual(-0.45678m, value); } [Test] public void ConvertsNegavtiveOneNumberDecimalFromString() { const string input = "-1.45678"; var value = input.ToDecimal(); Assert.AreEqual(-1.45678m, value); } [Test] public void ConvertsNegativeZeroDecimalValueFromString() { const string input = "-0"; var value = input.ToDecimal(); Assert.AreEqual(-0m, value); } [TestCase("1.23%", 0.0123d)] [TestCase("-1.23%", -0.0123d)] [TestCase("31.2300%", 0.3123d)] [TestCase("20%", 0.2d)] [TestCase("-20%", -0.2d)] [TestCase("220%", 2.2d)] public void ConvertsPercent(string input, double expected) { Assert.AreEqual(new decimal(expected), input.ToNormalizedDecimal()); } [Test] public void ConvertsTimeSpanFromString() { const string input = "16:00"; var timespan = input.ConvertTo<TimeSpan>(); Assert.AreEqual(TimeSpan.FromHours(16), timespan); } [Test] public void ConvertsDictionaryFromString() { var expected = new Dictionary<string, int> {{"a", 1}, {"b", 2}}; var input = JsonConvert.SerializeObject(expected); var actual = input.ConvertTo<Dictionary<string, int>>(); CollectionAssert.AreEqual(expected, actual); } [Test] public void DictionaryAddsItemToExistsList() { const int key = 0; var list = new List<int> {1, 2}; var dictionary = new Dictionary<int, List<int>> {{key, list}}; Extensions.Add(dictionary, key, 3); Assert.AreEqual(3, list.Count); Assert.AreEqual(3, list[2]); } [Test] public void DictionaryAddCreatesNewList() { const int key = 0; var dictionary = new Dictionary<int, List<int>>(); Extensions.Add(dictionary, key, 1); Assert.IsTrue(dictionary.ContainsKey(key)); var list = dictionary[key]; Assert.AreEqual(1, list.Count); Assert.AreEqual(1, list[0]); } [Test] public void SafeDecimalCasts() { var input = 2d; var output = input.SafeDecimalCast(); Assert.AreEqual(2m, output); } [Test] public void SafeDecimalCastRespectsUpperBound() { var input = (double) decimal.MaxValue; var output = input.SafeDecimalCast(); Assert.AreEqual(decimal.MaxValue, output); } [Test] public void SafeDecimalCastRespectsLowerBound() { var input = (double) decimal.MinValue; var output = input.SafeDecimalCast(); Assert.AreEqual(decimal.MinValue, output); } [TestCase(Language.CSharp, double.NaN)] [TestCase(Language.Python, double.NaN)] [TestCase(Language.CSharp, double.NegativeInfinity)] [TestCase(Language.Python, double.NegativeInfinity)] [TestCase(Language.CSharp, double.PositiveInfinity)] [TestCase(Language.Python, double.PositiveInfinity)] public void SafeDecimalCastThrowsArgumentException(Language language, double number) { if (language == Language.CSharp) { Assert.Throws<ArgumentException>(() => number.SafeDecimalCast()); return; } using (Py.GIL()) { var pyNumber = number.ToPython(); var csNumber = pyNumber.As<double>(); Assert.Throws<ArgumentException>(() => csNumber.SafeDecimalCast()); } } [Test] [TestCase(1.200, "1.2")] [TestCase(1200, "1200")] [TestCase(123.456, "123.456")] public void NormalizeDecimalReturnsNoTrailingZeros(decimal input, string expectedOutput) { var output = input.Normalize(); Assert.AreEqual(expectedOutput, output.ToStringInvariant()); } [Test] [TestCase(0.072842, 3, "0.0728")] [TestCase(0.0019999, 2, "0.0020")] [TestCase(0.01234568423, 6, "0.0123457")] public void RoundToSignificantDigits(decimal input, int digits, string expectedOutput) { var output = input.RoundToSignificantDigits(digits).ToStringInvariant(); Assert.AreEqual(expectedOutput, output); } [Test] public void RoundsDownInTimeZone() { var dataTimeZone = TimeZones.Utc; var exchangeTimeZone = TimeZones.EasternStandard; var time = new DateTime(2000, 01, 01).ConvertTo(dataTimeZone, exchangeTimeZone); var roundedTime = time.RoundDownInTimeZone(Time.OneDay, exchangeTimeZone, dataTimeZone); Assert.AreEqual(time, roundedTime); } [Test] public void GetStringBetweenCharsTests() { const string expected = "python3.6"; // Different characters cases var input = "[ python3.6 ]"; var actual = input.GetStringBetweenChars('[', ']'); Assert.AreEqual(expected, actual); input = "[ python3.6 ] [ python2.7 ]"; actual = input.GetStringBetweenChars('[', ']'); Assert.AreEqual(expected, actual); input = "[ python2.7 [ python3.6 ] ]"; actual = input.GetStringBetweenChars('[', ']'); Assert.AreEqual(expected, actual); // Same character cases input = "\'python3.6\'"; actual = input.GetStringBetweenChars('\'', '\''); Assert.AreEqual(expected, actual); input = "\' python3.6 \' \' python2.7 \'"; actual = input.GetStringBetweenChars('\'', '\''); Assert.AreEqual(expected, actual); // In this case, it is not equal input = "\' python2.7 \' python3.6 \' \'"; actual = input.GetStringBetweenChars('\'', '\''); Assert.AreNotEqual(expected, actual); } [Test] public void PyObjectTryConvertQuoteBar() { // Wrap a QuoteBar around a PyObject and convert it back var value = ConvertToPyObject(new QuoteBar()); QuoteBar quoteBar; var canConvert = value.TryConvert(out quoteBar); Assert.IsTrue(canConvert); Assert.IsNotNull(quoteBar); Assert.IsAssignableFrom<QuoteBar>(quoteBar); } [Test] public void PyObjectTryConvertSMA() { // Wrap a SimpleMovingAverage around a PyObject and convert it back var value = ConvertToPyObject(new SimpleMovingAverage(14)); IndicatorBase<IndicatorDataPoint> indicatorBaseDataPoint; var canConvert = value.TryConvert(out indicatorBaseDataPoint); Assert.IsTrue(canConvert); Assert.IsNotNull(indicatorBaseDataPoint); Assert.IsAssignableFrom<SimpleMovingAverage>(indicatorBaseDataPoint); } [Test] public void PyObjectTryConvertATR() { // Wrap a AverageTrueRange around a PyObject and convert it back var value = ConvertToPyObject(new AverageTrueRange(14, MovingAverageType.Simple)); IndicatorBase<IBaseDataBar> indicatorBaseDataBar; var canConvert = value.TryConvert(out indicatorBaseDataBar); Assert.IsTrue(canConvert); Assert.IsNotNull(indicatorBaseDataBar); Assert.IsAssignableFrom<AverageTrueRange>(indicatorBaseDataBar); } [Test] public void PyObjectTryConvertAD() { // Wrap a AccumulationDistribution around a PyObject and convert it back var value = ConvertToPyObject(new AccumulationDistribution("AD")); IndicatorBase<TradeBar> indicatorBaseTradeBar; var canConvert = value.TryConvert(out indicatorBaseTradeBar); Assert.IsTrue(canConvert); Assert.IsNotNull(indicatorBaseTradeBar); Assert.IsAssignableFrom<AccumulationDistribution>(indicatorBaseTradeBar); } [Test] public void PyObjectTryConvertSymbolArray() { PyObject value; using (Py.GIL()) { // Wrap a Symbol Array around a PyObject and convert it back value = new PyList(new[] { Symbols.SPY.ToPython(), Symbols.AAPL.ToPython() }); } Symbol[] symbols; var canConvert = value.TryConvert(out symbols); Assert.IsTrue(canConvert); Assert.IsNotNull(symbols); Assert.IsAssignableFrom<Symbol[]>(symbols); } [Test] public void PyObjectTryConvertFailCSharp() { // Try to convert a AccumulationDistribution as a QuoteBar var value = ConvertToPyObject(new AccumulationDistribution("AD")); QuoteBar quoteBar; bool canConvert = value.TryConvert(out quoteBar); Assert.IsFalse(canConvert); Assert.IsNull(quoteBar); } [Test] public void PyObjectTryConvertFailPython() { using (Py.GIL()) { // Try to convert a python object as a IndicatorBase<TradeBar> var locals = new PyDict(); PythonEngine.Exec("class A:\n pass", null, locals.Handle); var value = locals.GetItem("A").Invoke(); IndicatorBase<TradeBar> indicatorBaseTradeBar; bool canConvert = value.TryConvert(out indicatorBaseTradeBar); Assert.IsFalse(canConvert); Assert.IsNull(indicatorBaseTradeBar); } } [Test] [TestCase("coarseSelector = lambda coarse: [ x.Symbol for x in coarse if x.Price % 2 == 0 ]")] [TestCase("def coarseSelector(coarse): return [ x.Symbol for x in coarse if x.Price % 2 == 0 ]")] public void PyObjectTryConvertToFunc(string code) { Func<IEnumerable<CoarseFundamental>, Symbol[]> coarseSelector; using (Py.GIL()) { var locals = new PyDict(); PythonEngine.Exec(code, null, locals.Handle); var pyObject = locals.GetItem("coarseSelector"); pyObject.TryConvertToDelegate(out coarseSelector); } var coarse = Enumerable .Range(0, 9) .Select(x => new CoarseFundamental { Symbol = Symbol.Create(x.ToStringInvariant(), SecurityType.Equity, Market.USA), Value = x }); var symbols = coarseSelector(coarse); Assert.AreEqual(5, symbols.Length); foreach (var symbol in symbols) { var price = symbol.Value.ConvertInvariant<int>(); Assert.AreEqual(0, price % 2); } } [Test] public void PyObjectTryConvertToAction1() { Action<int> action; using (Py.GIL()) { var locals = new PyDict(); PythonEngine.Exec("def raise_number(a): raise ValueError(a)", null, locals.Handle); var pyObject = locals.GetItem("raise_number"); pyObject.TryConvertToDelegate(out action); } try { action(2); Assert.Fail(); } catch (PythonException e) { Assert.AreEqual($"ValueError : {2}", e.Message); } } [Test] public void PyObjectTryConvertToAction2() { Action<int, decimal> action; using (Py.GIL()) { var locals = new PyDict(); PythonEngine.Exec("def raise_number(a, b): raise ValueError(a * b)", null, locals.Handle); var pyObject = locals.GetItem("raise_number"); pyObject.TryConvertToDelegate(out action); } try { action(2, 3m); Assert.Fail(); } catch (PythonException e) { Assert.AreEqual("ValueError : 6.0", e.Message); } } [Test] public void PyObjectTryConvertToNonDelegateFail() { int action; using (Py.GIL()) { var locals = new PyDict(); PythonEngine.Exec("def raise_number(a, b): raise ValueError(a * b)", null, locals.Handle); var pyObject = locals.GetItem("raise_number"); Assert.Throws<ArgumentException>(() => pyObject.TryConvertToDelegate(out action)); } } [Test] public void PyObjectStringConvertToSymbolEnumerable() { SymbolCache.Clear(); SymbolCache.Set("SPY", Symbols.SPY); IEnumerable<Symbol> symbols; using (Py.GIL()) { symbols = new PyString("SPY").ConvertToSymbolEnumerable(); } Assert.AreEqual(Symbols.SPY, symbols.Single()); } [Test] public void PyObjectStringListConvertToSymbolEnumerable() { SymbolCache.Clear(); SymbolCache.Set("SPY", Symbols.SPY); IEnumerable<Symbol> symbols; using (Py.GIL()) { symbols = new PyList(new[] { "SPY".ToPython() }).ConvertToSymbolEnumerable(); } Assert.AreEqual(Symbols.SPY, symbols.Single()); } [Test] public void PyObjectSymbolConvertToSymbolEnumerable() { IEnumerable<Symbol> symbols; using (Py.GIL()) { symbols = Symbols.SPY.ToPython().ConvertToSymbolEnumerable(); } Assert.AreEqual(Symbols.SPY, symbols.Single()); } [Test] public void PyObjectSymbolListConvertToSymbolEnumerable() { IEnumerable<Symbol> symbols; using (Py.GIL()) { symbols = new PyList(new[] {Symbols.SPY.ToPython()}).ConvertToSymbolEnumerable(); } Assert.AreEqual(Symbols.SPY, symbols.Single()); } [Test] public void PyObjectNonSymbolObjectConvertToSymbolEnumerable() { using (Py.GIL()) { Assert.Throws<ArgumentException>(() => new PyInt(1).ConvertToSymbolEnumerable().ToList()); } } [Test] public void PyObjectDictionaryConvertToDictionary_Success() { using (Py.GIL()) { var actualDictionary = PythonEngine.ModuleFromString( "PyObjectDictionaryConvertToDictionary_Success", @" from datetime import datetime as dt actualDictionary = dict() actualDictionary.update({'SPY': dt(2019,10,3)}) actualDictionary.update({'QQQ': dt(2019,10,4)}) actualDictionary.update({'IBM': dt(2019,10,5)}) " ).GetAttr("actualDictionary").ConvertToDictionary<string, DateTime>(); Assert.AreEqual(3, actualDictionary.Count); var expectedDictionary = new Dictionary<string, DateTime> { {"SPY", new DateTime(2019,10,3) }, {"QQQ", new DateTime(2019,10,4) }, {"IBM", new DateTime(2019,10,5) }, }; foreach (var kvp in expectedDictionary) { Assert.IsTrue(actualDictionary.ContainsKey(kvp.Key)); var actual = actualDictionary[kvp.Key]; Assert.AreEqual(kvp.Value, actual); } } } [Test] public void PyObjectDictionaryConvertToDictionary_FailNotDictionary() { using (Py.GIL()) { var pyObject = PythonEngine.ModuleFromString( "PyObjectDictionaryConvertToDictionary_FailNotDictionary", "actualDictionary = list()" ).GetAttr("actualDictionary"); Assert.Throws<ArgumentException>(() => pyObject.ConvertToDictionary<string, DateTime>()); } } [Test] public void PyObjectDictionaryConvertToDictionary_FailWrongItemType() { using (Py.GIL()) { var pyObject = PythonEngine.ModuleFromString( "PyObjectDictionaryConvertToDictionary_FailWrongItemType", @" actualDictionary = dict() actualDictionary.update({'SPY': 3}) actualDictionary.update({'QQQ': 4}) actualDictionary.update({'IBM': 5}) " ).GetAttr("actualDictionary"); Assert.Throws<ArgumentException>(() => pyObject.ConvertToDictionary<string, DateTime>()); } } [Test] public void BatchByDoesNotDropItems() { var list = new List<int> {1, 2, 3, 4, 5}; var by2 = list.BatchBy(2).ToList(); Assert.AreEqual(3, by2.Count); Assert.AreEqual(2, by2[0].Count); Assert.AreEqual(2, by2[1].Count); Assert.AreEqual(1, by2[2].Count); CollectionAssert.AreEqual(list, by2.SelectMany(x => x)); } [Test] public void ToOrderTicketCreatesCorrectTicket() { var orderRequest = new SubmitOrderRequest(OrderType.Limit, SecurityType.Equity, Symbols.USDJPY, 1000, 0, 1.11m, DateTime.Now, "Pepe"); var order = Order.CreateOrder(orderRequest); order.Status = OrderStatus.Submitted; order.Id = 11; var orderTicket = order.ToOrderTicket(null); Assert.AreEqual(order.Id, orderTicket.OrderId); Assert.AreEqual(order.Quantity, orderTicket.Quantity); Assert.AreEqual(order.Status, orderTicket.Status); Assert.AreEqual(order.Type, orderTicket.OrderType); Assert.AreEqual(order.Symbol, orderTicket.Symbol); Assert.AreEqual(order.Tag, orderTicket.Tag); Assert.AreEqual(order.Time, orderTicket.Time); Assert.AreEqual(order.SecurityType, orderTicket.SecurityType); } [TestCase(4000, "4K")] [TestCase(4103, "4.1K")] [TestCase(40000, "40K")] [TestCase(45321, "45.3K")] [TestCase(654321, "654K")] [TestCase(600031, "600K")] [TestCase(1304303, "1.3M")] [TestCase(2600000, "2.6M")] [TestCase(26000000, "26M")] [TestCase(260000000, "260M")] [TestCase(2600000000, "2.6B")] [TestCase(26000000000, "26B")] public void ToFinancialFigures(double number, string expected) { var value = ((decimal)number).ToFinancialFigures(); Assert.AreEqual(expected, value); } [Test] public void DecimalTruncateTo3DecimalPlaces() { var value = 10.999999m; Assert.AreEqual(10.999m, value.TruncateTo3DecimalPlaces()); } [Test] public void DecimalTruncateTo3DecimalPlacesDoesNotThrowException() { var value = decimal.MaxValue; Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces()); value = decimal.MinValue; Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces()); value = decimal.MaxValue - 1; Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces()); value = decimal.MinValue + 1; Assert.DoesNotThrow(() => value.TruncateTo3DecimalPlaces()); } [Test] public void DecimalAllowExponentTests() { const string strWithExponent = "5e-5"; Assert.AreEqual(strWithExponent.ToDecimalAllowExponent(), 0.00005); Assert.AreNotEqual(strWithExponent.ToDecimal(), 0.00005); Assert.AreEqual(strWithExponent.ToDecimal(), 10275); } [Test] public void DateRulesToFunc() { var dateRules = new DateRules(new SecurityManager( new TimeKeeper(new DateTime(2015, 1, 1), DateTimeZone.Utc)), DateTimeZone.Utc); var first = new DateTime(2015, 1, 10); var second = new DateTime(2015, 1, 30); var dateRule = dateRules.On(first, second); var func = dateRule.ToFunc(); Assert.AreEqual(first, func(new DateTime(2015, 1, 1))); Assert.AreEqual(first, func(new DateTime(2015, 1, 5))); Assert.AreEqual(second, func(first)); Assert.AreEqual(Time.EndOfTime, func(second)); Assert.AreEqual(Time.EndOfTime, func(second)); } [Test] [TestCase(OptionRight.Call, true, OrderDirection.Sell)] [TestCase(OptionRight.Call, false, OrderDirection.Buy)] [TestCase(OptionRight.Put, true, OrderDirection.Buy)] [TestCase(OptionRight.Put, false, OrderDirection.Sell)] public void GetsExerciseDirection(OptionRight right, bool isShort, OrderDirection expected) { var actual = right.GetExerciseDirection(isShort); Assert.AreEqual(expected, actual); } [Test] public void AppliesScalingToEquityTickQuotes() { // This test ensures that all Ticks with TickType == TickType.Quote have adjusted BidPrice and AskPrice. // Relevant issue: https://github.com/QuantConnect/Lean/issues/4788 var algo = new QCAlgorithm(); var dataFeed = new NullDataFeed(); algo.SubscriptionManager = new SubscriptionManager(); algo.SubscriptionManager.SetDataManager(new DataManager( dataFeed, new UniverseSelection( algo, new SecurityService( new CashBook(), MarketHoursDatabase.FromDataFolder(), SymbolPropertiesDatabase.FromDataFolder(), algo, null, null ), new DataPermissionManager(), new DefaultDataProvider() ), algo, new TimeKeeper(DateTime.UtcNow), MarketHoursDatabase.FromDataFolder(), false, null, new DataPermissionManager() )); using (var zipDataCacheProvider = new ZipDataCacheProvider(new DefaultDataProvider())) { algo.HistoryProvider = new SubscriptionDataReaderHistoryProvider(); algo.HistoryProvider.Initialize( new HistoryProviderInitializeParameters( null, null, null, zipDataCacheProvider, new LocalDiskMapFileProvider(), new LocalDiskFactorFileProvider(), (_) => {}, false, new DataPermissionManager())); algo.SetStartDate(DateTime.UtcNow.AddDays(-1)); var history = algo.History(new[] { Symbols.IBM }, new DateTime(2013, 10, 7), new DateTime(2013, 10, 8), Resolution.Tick).ToList(); Assert.AreEqual(57460, history.Count); foreach (var slice in history) { if (!slice.Ticks.ContainsKey(Symbols.IBM)) { continue; } foreach (var tick in slice.Ticks[Symbols.IBM]) { if (tick.BidPrice != 0) { Assert.LessOrEqual(Math.Abs(tick.Value - tick.BidPrice), 0.05); } if (tick.AskPrice != 0) { Assert.LessOrEqual(Math.Abs(tick.Value - tick.AskPrice), 0.05); } } } } } [Test] [TestCase(PositionSide.Long, OrderDirection.Buy)] [TestCase(PositionSide.Short, OrderDirection.Sell)] [TestCase(PositionSide.None, OrderDirection.Hold)] public void ToOrderDirection(PositionSide side, OrderDirection expected) { Assert.AreEqual(expected, side.ToOrderDirection()); } [Test] [TestCase(OrderDirection.Buy, PositionSide.Long, false)] [TestCase(OrderDirection.Buy, PositionSide.Short, true)] [TestCase(OrderDirection.Buy, PositionSide.None, false)] [TestCase(OrderDirection.Sell, PositionSide.Long, true)] [TestCase(OrderDirection.Sell, PositionSide.Short, false)] [TestCase(OrderDirection.Sell, PositionSide.None, false)] [TestCase(OrderDirection.Hold, PositionSide.Long, false)] [TestCase(OrderDirection.Hold, PositionSide.Short, false)] [TestCase(OrderDirection.Hold, PositionSide.None, false)] public void Closes(OrderDirection direction, PositionSide side, bool expected) { Assert.AreEqual(expected, direction.Closes(side)); } [Test] public void ListEquals() { var left = new[] {1, 2, 3}; var right = new[] {1, 2, 3}; Assert.IsTrue(left.ListEquals(right)); right[2] = 4; Assert.IsFalse(left.ListEquals(right)); } [Test] public void GetListHashCode() { var ints1 = new[] {1, 2, 3}; var ints2 = new[] {1, 3, 2}; var longs = new[] {1L, 2L, 3L}; var decimals = new[] {1m, 2m, 3m}; // ordering dependent Assert.AreNotEqual(ints1.GetListHashCode(), ints2.GetListHashCode()); Assert.AreEqual(ints1.GetListHashCode(), decimals.GetListHashCode()); // known type collision - long has same hash code as int within the int range // we could take a hash of typeof(T) but this would require ListEquals to enforce exact types // and we would prefer to allow typeof(T)'s GetHashCode and Equals to make this determination. Assert.AreEqual(ints1.GetListHashCode(), longs.GetListHashCode()); // deterministic Assert.AreEqual(ints1.GetListHashCode(), new[] {1, 2, 3}.GetListHashCode()); } [Test] [TestCase("0.999", "0.0001", "0.999")] [TestCase("0.999", "0.001", "0.999")] [TestCase("0.999", "0.01", "1.000")] [TestCase("0.999", "0.1", "1.000")] [TestCase("0.999", "1", "1.000")] [TestCase("0.999", "2", "0")] [TestCase("1.0", "0.15", "1.05")] [TestCase("1.05", "0.15", "1.05")] [TestCase("0.975", "0.15", "1.05")] [TestCase("-0.975", "0.15", "-1.05")] [TestCase("-1.0", "0.15", "-1.05")] [TestCase("-1.05", "0.15", "-1.05")] public void DiscretelyRoundBy(string valueString, string quantaString, string expectedString) { var value = decimal.Parse(valueString, CultureInfo.InvariantCulture); var quanta = decimal.Parse(quantaString, CultureInfo.InvariantCulture); var expected = decimal.Parse(expectedString, CultureInfo.InvariantCulture); var actual = value.DiscretelyRoundBy(quanta); Assert.AreEqual(expected, actual); } private PyObject ConvertToPyObject(object value) { using (Py.GIL()) { return value.ToPython(); } } private class Super<T> { } private class Derived1 : Super<int> { } private class Derived2 : Derived1 { } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.IO.Compression; using System.Reflection; using System.Net; using System.Text; using System.Web; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Simulation { public class AgentHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; public AgentHandler() { } public AgentHandler(ISimulationService sim) { m_SimulationService = sim; } public Hashtable Handler(Hashtable request) { // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); // // m_log.Debug("---------------------------"); // m_log.Debug(" >> uri=" + request["uri"]); // m_log.Debug(" >> content-type=" + request["content-type"]); // m_log.Debug(" >> http-method=" + request["http-method"]); // m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; responsedata["keepalive"] = false; UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } // Next, let's parse the verb string method = (string)request["http-method"]; if (method.Equals("DELETE")) { string auth_token = string.Empty; if (request.ContainsKey("auth")) auth_token = request["auth"].ToString(); DoAgentDelete(request, responsedata, agentID, action, regionID, auth_token); return responsedata; } else if (method.Equals("QUERYACCESS")) { DoQueryAccess(request, responsedata, agentID, regionID); return responsedata; } else { m_log.ErrorFormat("[AGENT HANDLER]: method {0} not supported in agent message {1} (caller is {2})", method, (string)request["uri"], Util.GetCallerIP(request)); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID) { if (m_SimulationService == null) { m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]); OSDMap args = Utils.GetOSDMap((string)request["body"]); bool viaTeleport = true; if (args.ContainsKey("viaTeleport")) viaTeleport = args["viaTeleport"].AsBoolean(); Vector3 position = Vector3.Zero; if (args.ContainsKey("position")) position = Vector3.Parse(args["position"].AsString()); string agentHomeURI = null; if (args.ContainsKey("agent_home_uri")) agentHomeURI = args["agent_home_uri"].AsString(); string theirVersion = string.Empty; if (args.ContainsKey("my_version")) theirVersion = args["my_version"].AsString(); GridRegion destination = new GridRegion(); destination.RegionID = regionID; string reason; string version; bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, theirVersion, out version, out reason); responsedata["int_response_code"] = HttpStatusCode.OK; OSDMap resp = new OSDMap(3); resp["success"] = OSD.FromBoolean(result); resp["reason"] = OSD.FromString(reason); resp["version"] = OSD.FromString(version); // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); // Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); } protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID, string auth_token) { if (string.IsNullOrEmpty(action)) m_log.DebugFormat("[AGENT HANDLER]: >>> DELETE <<< RegionID: {0}; from: {1}; auth_code: {2}", regionID, Util.GetCallerIP(request), auth_token); else m_log.DebugFormat("[AGENT HANDLER]: Release {0} to RegionID: {1}", id, regionID); GridRegion destination = new GridRegion(); destination.RegionID = regionID; if (action.Equals("release")) ReleaseAgent(regionID, id); else Util.FireAndForget( o => m_SimulationService.CloseAgent(destination, id, auth_token), null, "AgentHandler.DoAgentDelete"); responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = "OpenSim agent " + id.ToString(); //m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID); } protected virtual void ReleaseAgent(UUID regionID, UUID id) { m_SimulationService.ReleaseAgent(regionID, id, ""); } } public class AgentPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPostHandler(ISimulationService service) : base("POST", "/agent") { m_SimulationService = service; } public AgentPostHandler(string path) : base("POST", path) { m_SimulationService = null; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Encoding encoding = Encoding.UTF8; if (httpRequest.ContentType != "application/json") { httpResponse.StatusCode = 406; return encoding.GetBytes("false"); } string requestBody; Stream inputStream = request; Stream innerStream = null; try { if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) { innerStream = inputStream; inputStream = new GZipStream(innerStream, CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(inputStream, encoding)) { requestBody = reader.ReadToEnd(); } } finally { if (innerStream != null) innerStream.Dispose(); inputStream.Dispose(); } keysvals.Add("body", requestBody); Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPost(keysvals, responsedata, agentID); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } AgentDestinationData data = CreateAgentDestinationData(); UnpackData(args, data, request); GridRegion destination = new GridRegion(); destination.RegionID = data.uuid; destination.RegionLocX = data.x; destination.RegionLocY = data.y; destination.RegionName = data.name; GridRegion gatekeeper = ExtractGatekeeper(data); AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } GridRegion source = null; if (args.ContainsKey("source_uuid")) { source = new GridRegion(); source.RegionLocX = Int32.Parse(args["source_x"].AsString()); source.RegionLocY = Int32.Parse(args["source_y"].AsString()); source.RegionName = args["source_name"].AsString(); source.RegionID = UUID.Parse(args["source_uuid"].AsString()); if (args.ContainsKey("source_server_uri")) source.RawServerURI = args["source_server_uri"].AsString(); else source.RawServerURI = null; } OSDMap resp = new OSDMap(2); string reason = String.Empty; // This is the meaning of POST agent //m_regionClient.AdjustUserInformation(aCircuit); //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(GetCallerIP(request)); // TODO: add reason if not String.Empty? responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } protected virtual AgentDestinationData CreateAgentDestinationData() { return new AgentDestinationData(); } protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request) { // retrieve the input arguments if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out data.x); else m_log.WarnFormat(" -- request didn't have destination_x"); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out data.y); else m_log.WarnFormat(" -- request didn't have destination_y"); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) data.name = args["destination_name"].ToString(); if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) data.flags = args["teleport_flags"].AsUInteger(); } protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data) { return null; } protected string GetCallerIP(Hashtable request) { if (!m_Proxy) return Util.GetCallerIP(request); // We're behind a proxy Hashtable headers = (Hashtable)request["headers"]; //// DEBUG //foreach (object o in headers.Keys) // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString())); string xff = "X-Forwarded-For"; if (headers.ContainsKey(xff.ToLower())) xff = xff.ToLower(); if (!headers.ContainsKey(xff) || headers[xff] == null) { m_log.WarnFormat("[AGENT HANDLER]: No XFF header"); return Util.GetCallerIP(request); } m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]); IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]); if (ep != null) return ep.Address.ToString(); // Oops return Util.GetCallerIP(request); } // subclasses can override this protected virtual bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason) { return m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, out reason); } } public class AgentPutHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPutHandler(ISimulationService service) : base("PUT", "/agent") { m_SimulationService = service; } public AgentPutHandler(string path) : base("PUT", path) { m_SimulationService = null; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); String requestBody; Encoding encoding = Encoding.UTF8; Stream inputStream = request; Stream innerStream = null; try { if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) { innerStream = inputStream; inputStream = new GZipStream(innerStream, CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(inputStream, encoding)) { requestBody = reader.ReadToEnd(); } } finally { if (innerStream != null) innerStream.Dispose(); inputStream.Dispose(); } keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPut(keysvals, responsedata); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPut(Hashtable request, Hashtable responsedata) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; string messageType; if (args["message_type"] != null) messageType = args["message_type"].AsString(); else { m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. "); messageType = "AgentData"; } bool result = true; if ("AgentData".Equals(messageType)) { AgentData agent = new AgentData(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID)); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); } else if ("AgentPosition".Equals(messageType)) { AgentPosition agent = new AgentPosition(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID)); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); return; } //agent.Dump(); // This is one of the meanings of PUT agent result = m_SimulationService.UpdateAgent(destination, agent); } responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = result.ToString(); //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead } // subclasses can override this protected virtual bool UpdateAgent(GridRegion destination, AgentData agent) { return m_SimulationService.UpdateAgent(destination, agent); } } public class AgentDestinationData { public int x; public int y; public string name; public UUID uuid; public uint flags; public bool fromLogin; } }
// 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A user for a specific Azure Batch compute node. /// </summary> public partial class ComputeNodeUser : ITransportObjectProvider<Models.ComputeNodeUser>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<DateTime> ExpiryTimeProperty; public readonly PropertyAccessor<bool?> IsAdminProperty; public readonly PropertyAccessor<string> NameProperty; public readonly PropertyAccessor<string> PasswordProperty; public readonly PropertyAccessor<string> SshPublicKeyProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ExpiryTimeProperty = this.CreatePropertyAccessor<DateTime>("ExpiryTime", BindingAccess.Read | BindingAccess.Write); this.IsAdminProperty = this.CreatePropertyAccessor<bool?>("IsAdmin", BindingAccess.Read | BindingAccess.Write); this.NameProperty = this.CreatePropertyAccessor<string>("Name", BindingAccess.Read | BindingAccess.Write); this.PasswordProperty = this.CreatePropertyAccessor<string>("Password", BindingAccess.Read | BindingAccess.Write); this.SshPublicKeyProperty = this.CreatePropertyAccessor<string>("SshPublicKey", BindingAccess.Read | BindingAccess.Write); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; private readonly string parentPoolId; internal string ParentPoolId { get { return this.parentPoolId; } } private readonly string parentNodeId; internal string ParentNodeId { get { return this.parentNodeId; } } #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ComputeNodeUser"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> /// <param name='parentPoolId'>The parentPoolId.</param> /// <param name='parentNodeId'>The parentNodeId.</param> internal ComputeNodeUser( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors, string parentPoolId, string parentNodeId) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; this.parentPoolId = parentPoolId; this.parentNodeId = parentNodeId; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="ComputeNodeUser"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region ComputeNodeUser /// <summary> /// Gets or sets the expiry time. /// </summary> public DateTime ExpiryTime { get { return this.propertyContainer.ExpiryTimeProperty.Value; } set { this.propertyContainer.ExpiryTimeProperty.Value = value; } } /// <summary> /// Gets or sets the administrative privilege level of the user account. The value of this property is ignored when /// UpdateUser is specified for the commit operation. /// </summary> public bool? IsAdmin { get { return this.propertyContainer.IsAdminProperty.Value; } set { this.propertyContainer.IsAdminProperty.Value = value; } } /// <summary> /// Gets or sets the name. If AddUser is specified for the commit operation, the value of this property is the name /// of the local Windows account created. If UpdateUser is specified for the commit operation, the value of this /// property selects the local Windows account to modify. Changing this property does not rename the local Windows /// account on the compute node. /// </summary> public string Name { get { return this.propertyContainer.NameProperty.Value; } set { this.propertyContainer.NameProperty.Value = value; } } /// <summary> /// Gets or sets the password. /// </summary> public string Password { get { return this.propertyContainer.PasswordProperty.Value; } set { this.propertyContainer.PasswordProperty.Value = value; } } /// <summary> /// Gets or sets the SSH public key that can be used for remote login to the compute node. /// </summary> /// <remarks> /// <para>The public key should be compatible with Open SSH encoding and should be base 64 encoded. This property /// can be specified only for Linux nodes. The Batch service will return an error if this property is set for pools /// created with <see cref="Microsoft.Azure.Batch.CloudServiceConfiguration"/> or <see cref="Microsoft.Azure.Batch.VirtualMachineConfiguration"/> /// with Windows compute nodes.</para> /// </remarks> public string SshPublicKey { get { return this.propertyContainer.SshPublicKeyProperty.Value; } set { this.propertyContainer.SshPublicKeyProperty.Value = value; } } #endregion // ComputeNodeUser #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.ComputeNodeUser ITransportObjectProvider<Models.ComputeNodeUser>.GetTransportObject() { Models.ComputeNodeUser result = new Models.ComputeNodeUser() { ExpiryTime = this.ExpiryTime, IsAdmin = this.IsAdmin, Name = this.Name, Password = this.Password, SshPublicKey = this.SshPublicKey, }; return result; } #endregion // Internal/private methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Security.Cryptography.EcDsa.Tests; using System.Security.Cryptography.Tests; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Cng.Tests { public class ECDsaCngTests : ECDsaTestsBase { [Fact] public static void TestNegativeVerify256() { CngKey key = TestData.s_ECDsa256Key; ECDsaCng e = new ECDsaCng(key); byte[] tamperedSig = ("998791331eb2e1f4259297f5d9cb82fa20dec98e1cb0900e6b8f014a406c3d02cbdbf5238bde471c3155fc25565524301429" + "e8713dad9a67eb0a5c355e9e23dc").HexToByteArray(); bool verified = e.VerifyHash(EccTestData.s_hashSha512, tamperedSig); Assert.False(verified); } [Fact] public static void TestPositiveVerify384() { CngKey key = TestData.s_ECDsa384Key; ECDsaCng e = new ECDsaCng(key); byte[] sig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8" + "2366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray(); bool verified = e.VerifyHash(EccTestData.s_hashSha512, sig); Assert.True(verified); } [Fact] public static void TestNegativeVerify384() { CngKey key = TestData.s_ECDsa384Key; ECDsaCng e = new ECDsaCng(key); byte[] tamperedSig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8" + "f366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray(); bool verified = e.VerifyHash(EccTestData.s_hashSha512, tamperedSig); Assert.False(verified); } [Fact] public static void TestPositiveVerify521() { CngKey key = TestData.s_ECDsa521Key; ECDsaCng e = new ECDsaCng(key); byte[] sig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845" + "b6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7" + "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray(); bool verified = e.VerifyHash(EccTestData.s_hashSha512, sig); Assert.True(verified); } [Fact] public static void TestNegativeVerify521() { CngKey key = TestData.s_ECDsa521Key; ECDsaCng e = new ECDsaCng(key); byte[] tamperedSig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845" + "a6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7" + "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray(); bool verified = e.VerifyHash(EccTestData.s_hashSha512, tamperedSig); Assert.False(verified); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #18719")] public static void TestVerify521_EcdhKey() { byte[] keyBlob = (byte[])TestData.s_ECDsa521KeyBlob.Clone(); // Rewrite the dwMagic value to be ECDH // ECDSA prefix: 45 43 53 36 // ECDH prefix : 45 43 4b 36 keyBlob[2] = 0x4b; using (CngKey ecdh521 = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob)) { // Preconditions: Assert.Equal(CngAlgorithmGroup.ECDiffieHellman, ecdh521.AlgorithmGroup); Assert.Equal(CngAlgorithm.ECDiffieHellmanP521, ecdh521.Algorithm); using (ECDsa ecdsaFromEcdsaKey = new ECDsaCng(TestData.s_ECDsa521Key)) using (ECDsa ecdsaFromEcdhKey = new ECDsaCng(ecdh521)) { byte[] ecdhKeySignature = ecdsaFromEcdhKey.SignData(keyBlob, HashAlgorithmName.SHA512); byte[] ecdsaKeySignature = ecdsaFromEcdsaKey.SignData(keyBlob, HashAlgorithmName.SHA512); Assert.True( ecdsaFromEcdhKey.VerifyData(keyBlob, ecdsaKeySignature, HashAlgorithmName.SHA512), "ECDsaCng(ECDHKey) validates ECDsaCng(ECDsaKey)"); Assert.True( ecdsaFromEcdsaKey.VerifyData(keyBlob, ecdhKeySignature, HashAlgorithmName.SHA512), "ECDsaCng(ECDsaKey) validates ECDsaCng(ECDHKey)"); } } } [Fact] public static void CreateEcdsaFromRsaKey_Fails() { using (RSACng rsaCng = new RSACng()) { AssertExtensions.Throws<ArgumentException>("key", () => new ECDsaCng(rsaCng.Key)); } } [Fact] public static void TestCreateKeyFromCngAlgorithmNistP256() { CngAlgorithm alg = CngAlgorithm.ECDsaP256; using (CngKey key = CngKey.Create(alg)) { VerifyKey(key); using (ECDsaCng e = new ECDsaCng(key)) { Assert.Equal(CngAlgorithmGroup.ECDsa, e.Key.AlgorithmGroup); Assert.Equal(CngAlgorithm.ECDsaP256, e.Key.Algorithm); VerifyKey(e.Key); e.Exercise(); } } } [Fact] public static void TestCreateByKeySizeNistP256() { using (ECDsaCng cng = new ECDsaCng(256)) { CngKey key1 = cng.Key; Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup); // The three legacy nist curves are not treated as generic named curves Assert.Equal(CngAlgorithm.ECDsaP256, key1.Algorithm); Assert.Equal(256, key1.KeySize); VerifyKey(key1); } } #if netcoreapp [Fact] public static void TestPositive256WithBlob() { CngKey key = TestData.s_ECDsa256Key; ECDsaCng e = new ECDsaCng(key); Verify256(e, true); } [Theory, MemberData(nameof(TestCurves))] public static void TestKeyPropertyFromNamedCurve(CurveDef curveDef) { ECDsaCng e = new ECDsaCng(curveDef.Curve); CngKey key1 = e.Key; VerifyKey(key1); e.Exercise(); CngKey key2 = e.Key; Assert.Same(key1, key2); } [Fact] public static void TestCreateByNameNistP521() { using (ECDsaCng cng = new ECDsaCng(ECCurve.NamedCurves.nistP521)) { CngKey key1 = cng.Key; Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup); // The three legacy nist curves are not treated as generic named curves Assert.Equal(CngAlgorithm.ECDsaP521, key1.Algorithm); Assert.Equal(521, key1.KeySize); VerifyKey(key1); } } [Theory, MemberData(nameof(TestInvalidCurves))] public static void TestCreateKeyFromCngAlgorithmNegative(CurveDef curveDef) { CngAlgorithm alg = CngAlgorithm.ECDsa; Assert.ThrowsAny<Exception>(() => CngKey.Create(alg)); } [Theory, MemberData(nameof(SpecialNistKeys))] public static void TestSpecialNistKeys(int keySize, string curveName, CngAlgorithm algorithm) { using (ECDsaCng cng = (ECDsaCng)ECDsaFactory.Create(keySize)) { Assert.Equal(keySize, cng.KeySize); ECParameters param = cng.ExportParameters(false); Assert.Equal(curveName, param.Curve.Oid.FriendlyName); Assert.Equal(algorithm, cng.Key.Algorithm); } } #endif // netcoreapp public static IEnumerable<object[]> SpecialNistKeys { get { yield return new object[] { 256, "nistP256", CngAlgorithm.ECDsaP256}; yield return new object[] { 384, "nistP384", CngAlgorithm.ECDsaP384}; yield return new object[] { 521, "nistP521", CngAlgorithm.ECDsaP521}; } } private static void VerifyKey(CngKey key) { Assert.Equal("ECDSA", key.AlgorithmGroup.AlgorithmGroup); Assert.False(string.IsNullOrEmpty(key.Algorithm.Algorithm)); Assert.True(key.KeySize > 0); } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System.Net; using System.Web; using ECQRS.Commons.Commands; using ECQRS.Commons.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using UserManager.Core.Organizations.Commands; using UserManager.Core.Organizations.ReadModel; using UserManager.Model.Organizations; using UserManager.Core.Users.ReadModel; using UserManager.Core.Users.Commands; using UserManager.Core.Applications.ReadModel; using UserManager.Commons.ReadModel; namespace UserManager.Api { [Authorize] public class OrganizationGroupsController : ApiController { private readonly IRepository<OrganizationGroupItem> _groups; private readonly IRepository<OrganizationGroupRoleItem> _groupsRoles; private readonly IRepository<OrganizationRoleItem> _roles; private readonly IRepository<UserListItem> _users; private IRepository<OrganizationUserItem> _orgUsers; private readonly ICommandSender _bus; private IRepository<ApplicationRoleItem> _applicationRoles; private IRepository<OrganizationGroupUserItem> _groupUsers; public OrganizationGroupsController( IRepository<OrganizationGroupItem> list, IRepository<OrganizationGroupRoleItem> groupsRoles, IRepository<OrganizationRoleItem> roles, IRepository<UserListItem> users, IRepository<ApplicationRoleItem> applicationRoles, IRepository<OrganizationUserItem> orgUsers, IRepository<OrganizationGroupUserItem> groupUsers, ICommandSender bus) { _groups = list; _bus = bus; _groupsRoles = groupsRoles; _roles = roles; _users = users; _applicationRoles = applicationRoles; _orgUsers = orgUsers; _groupUsers = groupUsers; } // GET: api/Organizations [Route("api/OrganizationGroups/list/{organizationId}")] public IEnumerable<OrganizationGroupItem> GetList(Guid? organizationId, string range = null, string filter = null) { if (organizationId == null) throw new HttpException(400, "Invalid organization Id"); var parsedRange = AngularApiUtils.ParseRange(range); var parsedFilters = AngularApiUtils.ParseFilter(filter); var where = _groups.Where(); where = where.Where(a => a.OrganizationId == organizationId.Value && a.Deleted == false); if (parsedFilters.ContainsKey("Code")) where = where.Where(a => a.Code.Contains(parsedFilters["Code"].ToString())); if (parsedFilters.ContainsKey("Description")) where = where.Where(a => a.Description.Contains(parsedFilters["Description"].ToString())); return where .DoSkip(parsedRange.From).DoTake(parsedRange.Count); } // GET: api/Organizations/5/1 public OrganizationGroupItem Get(Guid id) { var res = _groups.Get(id); if (res != null) return res; return null; } // POST: api/Organizations public void Post([FromBody]OrganizationGroupCreateModel value) { _bus.SendSync(new OrganizationGroupCreate { Code = value.Code, Description = value.Description, OrganizationId = value.OrganizationId, GroupId = Guid.NewGuid() }); } // PUT: api/Organizations public void Put([FromBody]OrganizationGroupModifyModel value) { _bus.SendSync(new OrganizationGroupModify { Code = value.Code, Description = value.Description, OrganizationId = value.OrganizationId, GroupId = value.Id }); } // DELETE: api/Organizations/5 public void Delete(Guid id) { var item = _groups.Get(id); _bus.SendSync(new OrganizationGroupDelete { OrganizationId = item.OrganizationId, GroupId = item.Id }); } /// <summary> /// Retrieves all the roles associated with the given organization /// </summary> /// <param name="organizationId"></param> /// <param name="groupId"></param> /// <param name="range"></param> /// <param name="filter"></param> /// <returns></returns> [Route("api/OrganizationGroups/roles/{organizationId}/{groupId}")] public IEnumerable<OrganizationGroupRoleModel> GetList(Guid? organizationId, Guid? groupId, string range = null, string filter = null) { if (organizationId == null) throw new HttpException(400, "Invalid organization Id"); if (groupId == null) throw new HttpException(400, "Invalid group Id"); var parsedRange = AngularApiUtils.ParseRange(range); var parsedFilters = AngularApiUtils.ParseFilter(filter); //First take all the possible roles,filtered var allRoles = _applicationRoles.Where(a=>a.Deleted ==false); if (parsedFilters.ContainsKey("Code")) allRoles = allRoles.Where(a => a.Code.Contains(parsedFilters["Code"].ToString())); if (parsedFilters.ContainsKey("ApplicationName")) allRoles = allRoles.Where(a => a.ApplicationName.Contains(parsedFilters["ApplicationName"].ToString())); var allRolesList = allRoles.ToList(); //Takes all the available roles for the organization var availableRoles = _roles.Where(a => a.OrganizationId == organizationId.Value && a.Deleted == false).ToList().Select(r => r.RoleId); //Take only the role instance available allRolesList = allRolesList.Where(r => availableRoles.Contains(r.Id)).ToList(); //Takes the roles used by the current group var associatedRoles = _groupsRoles.Where(p => p.GroupId == groupId.Value && p.OrganizationId == organizationId.Value && p.Deleted == false).ToList(); return allRolesList .DoSkip(parsedRange.From).DoTake(parsedRange.Count) .Select(r => r.ToOrganizationGroupRoleModel(associatedRoles, organizationId.Value, groupId.Value)); } [HttpPost] [Route("api/OrganizationGroups/roles/{organizationId}/{groupId}")] public void AddOrganizationGroup(Guid? organizationId, Guid? groupId, OrganizationGroupRoleItem value) { if (organizationId == null) throw new HttpException(400, "Invalid organization Id"); if (groupId == null) throw new HttpException(400, "Invalid group Id"); _bus.SendSync(new OrganizationGroupRoleAdd { ApplicationId = value.ApplicationId, OrganizationId = organizationId.Value, GroupId = groupId.Value, RoleId = value.RoleId, GroupRoleId = Guid.NewGuid() }); } [HttpDelete] [Route("api/OrganizationGroups/roles/{organizationId}/{groupId}/{id}")] public void DeleteOrganizationGroup(Guid? organizationId, Guid? groupId, Guid? id) { if (organizationId == null) throw new HttpException(400, "Invalid organization Id"); if (groupId == null) throw new HttpException(400, "Invalid group Id"); if (id == null) throw new HttpException(400, "Invalid organization-group Id"); var item = _groupsRoles.Get(id.Value); _bus.SendSync(new OrganizationGroupRoleDelete { OrganizationId = organizationId.Value, GroupId = groupId.Value, RoleId = item.RoleId, GroupRoleId = item.Id }); } // GET: api/Organizations [Route("api/OrganizationUsers/list/{organizationId}/{groupId}")] public IEnumerable<OrganizationGroupUserModel> GetGroupUsers(Guid organizationId, Guid groupId, string range = null, string filter = null) { if (organizationId == Guid.Empty) throw new HttpException(400, "Invalid organization Id"); if (groupId == Guid.Empty) throw new HttpException(400, "Invalid group Id"); var parsedRange = AngularApiUtils.ParseRange(range); var parsedFilters = AngularApiUtils.ParseFilter(filter); var where = _users.Where(a=> a.Deleted == false); if (parsedFilters.ContainsKey("EMail")) where = where.Where(a => a.EMail.Contains(parsedFilters["EMail"].ToString())); if (parsedFilters.ContainsKey("UserName")) where = where.Where(a => a.UserName.Contains(parsedFilters["UserName"].ToString())); var organizationUsers = _orgUsers.Where(u => u.OrganizationId == organizationId && u.Deleted == false).ToList().Select(u => u.UserId).ToList(); var groupUserIds = _groupUsers.Where(u => u.OrganizationId == organizationId && u.GroupId == groupId && u.Deleted == false) .ToList(); if (organizationUsers.Count == 0) return new List<OrganizationGroupUserModel>(); return where .Where(u => organizationUsers.Contains(u.Id)) .DoSkip(parsedRange.From).DoTake(parsedRange.Count) .ToList() .Select(u=>u.ToOrganizationGroupUserModel(groupUserIds,organizationId,groupId)); } [HttpPost] [Route("api/OrganizationUsers/{organizationId}/{groupId}/{userId}")] public void AssociateUserWithGroup(Guid organizationId, Guid groupId, Guid userId) { _bus.SendSync(new UserOrganizationGroupAssociate { OrganizationId = organizationId, GroupId = groupId, UserId = userId }); } [HttpDelete] [Route("api/OrganizationUsers/{organizationId}/{groupId}/{userId}")] public void RemoveUserFromGroup(Guid organizationId, Guid groupId, Guid userId) { _bus.SendSync(new UserOrganizationGroupDeassociate { OrganizationId = organizationId, GroupId = groupId, UserId = userId }); } } }
/* ** $Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp $ ** Debug Interface ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace KopiLua { using TValue = Lua.LuaTypeValue; using StkId = Lua.LuaTypeValue; using Instruction = System.UInt32; public partial class Lua { public static int PCRel(InstructionPtr pc, Proto p) { Debug.Assert(pc.codes == p.code); return pc.pc - 1; } public static int GetLine(Proto f, int pc) { return (f.lineinfo != null) ? f.lineinfo[pc] : 0; } public static void ResetHookCount(LuaState L) { L.hookcount = L.basehookcount; } private static int CurrentPC (LuaState L, CallInfo ci) { if (!IsLua(ci)) return -1; /* function is not a Lua function? */ if (ci == L.ci) ci.savedpc = InstructionPtr.Assign(L.savedpc); return PCRel(ci.savedpc, CIFunc(ci).l.p); } private static int CurrentLine (LuaState L, CallInfo ci) { int pc = CurrentPC(L, ci); if (pc < 0) return -1; /* only active lua functions have current-line information */ else return GetLine(CIFunc(ci).l.p, pc); } /* ** this function can be called asynchronous (e.g. during a signal) */ public static int LuaSetHook (LuaState L, LuaHook func, int mask, int count) { if (func == null || mask == 0) { /* turn off hooks? */ mask = 0; func = null; } L.hook = func; L.basehookcount = count; ResetHookCount(L); L.hookmask = CastByte(mask); return 1; } public static LuaHook LuaGetHook (LuaState L) { return L.hook; } public static int LuaGetHookMask (LuaState L) { return L.hookmask; } public static int LuaGetHookCount (LuaState L) { return L.basehookcount; } public static int LuaGetStack (LuaState L, int level, ref LuaDebug ar) { int status; CallInfo ci; LuaLock(L); for (ci = L.ci; level > 0 && ci > L.base_ci[0]; CallInfo.Dec(ref ci)) { level--; if (FIsLua(ci)) /* Lua function? */ level -= ci.tailcalls; /* skip lost tail calls */ } if (level == 0 && ci > L.base_ci[0]) { /* level found? */ status = 1; ar.i_ci = ci - L.base_ci[0]; } else if (level < 0) { /* level is of a lost tail call? */ status = 1; ar.i_ci = 0; } else status = 0; /* no such level */ LuaUnlock(L); return status; } private static Proto GetLuaProto (CallInfo ci) { return (IsLua(ci) ? CIFunc(ci).l.p : null); } private static CharPtr FindLocal (LuaState L, CallInfo ci, int n) { CharPtr name; Proto fp = GetLuaProto(ci); if ((fp!=null) && (name = LuaFGetLocalName(fp, n, CurrentPC(L, ci))) != null) return name; /* is a local variable in a Lua function */ else { StkId limit = (ci == L.ci) ? L.top : (ci+1).func; if (limit - ci.base_ >= n && n > 0) /* is 'n' inside 'ci' stack? */ return "(*temporary)"; else return null; } } public static CharPtr LuaGetLocal (LuaState L, LuaDebug ar, int n) { CallInfo ci = L.base_ci[ar.i_ci]; CharPtr name = FindLocal(L, ci, n); LuaLock(L); if (name != null) LuaAPushObject(L, ci.base_[n - 1]); LuaUnlock(L); return name; } public static CharPtr LuaSetLocal (LuaState L, LuaDebug ar, int n) { CallInfo ci = L.base_ci[ar.i_ci]; CharPtr name = FindLocal(L, ci, n); LuaLock(L); if (name != null) SetObj2S(L, ci.base_[n - 1], L.top-1); StkId.Dec(ref L.top); /* pop value */ LuaUnlock(L); return name; } private static void FuncInfo (LuaDebug ar, Closure cl) { if (cl.c.isC != 0) { ar.source = "=[C]"; ar.linedefined = -1; ar.lastlinedefined = -1; ar.what = "C"; } else { ar.source = GetStr(cl.l.p.source); ar.linedefined = cl.l.p.linedefined; ar.lastlinedefined = cl.l.p.lastlinedefined; ar.what = (ar.linedefined == 0) ? "main" : "Lua"; } LuaOChunkID(ar.short_src, ar.source, LUA_IDSIZE); } private static void InfoTailCall (LuaDebug ar) { ar.name = ar.namewhat = ""; ar.what = "tail"; ar.lastlinedefined = ar.linedefined = ar.currentline = -1; ar.source = "=(tail call)"; LuaOChunkID(ar.short_src, ar.source, LUA_IDSIZE); ar.nups = 0; } private static void CollectValidLines (LuaState L, Closure f) { if (f == null || (f.c.isC!=0)) { SetNilValue(L.top); } else { Table t = luaH_new(L, 0, 0); int[] lineinfo = f.l.p.lineinfo; int i; for (i=0; i<f.l.p.sizelineinfo; i++) SetBValue(luaH_setnum(L, t, lineinfo[i]), 1); SetHValue(L, L.top, t); } IncrTop(L); } private static int AuxGetInfo (LuaState L, CharPtr what, LuaDebug ar, Closure f, CallInfo ci) { int status = 1; if (f == null) { InfoTailCall(ar); return status; } for (; what[0] != 0; what = what.next()) { switch (what[0]) { case 'S': { FuncInfo(ar, f); break; } case 'l': { ar.currentline = (ci != null) ? CurrentLine(L, ci) : -1; break; } case 'u': { ar.nups = f.c.nupvalues; break; } case 'n': { ar.namewhat = (ci!=null) ? GetFuncName(L, ci, ref ar.name) : null; if (ar.namewhat == null) { ar.namewhat = ""; /* not found */ ar.name = null; } break; } case 'L': case 'f': /* handled by lua_getinfo */ break; default: status = 0; break;/* invalid option */ } } return status; } public static int LuaGetInfo (LuaState L, CharPtr what, ref LuaDebug ar) { int status; Closure f = null; CallInfo ci = null; LuaLock(L); if (what == '>') { StkId func = L.top - 1; luai_apicheck(L, TTIsFunction(func)); what = what.next(); /* skip the '>' */ f = CLValue(func); StkId.Dec(ref L.top); /* pop function */ } else if (ar.i_ci != 0) { /* no tail call? */ ci = L.base_ci[ar.i_ci]; LuaAssert(TTIsFunction(ci.func)); f = CLValue(ci.func); } status = AuxGetInfo(L, what, ar, f, ci); if (strchr(what, 'f') != null) { if (f == null) SetNilValue(L.top); else SetCLValue(L, L.top, f); IncrTop(L); } if (strchr(what, 'L') != null) CollectValidLines(L, f); LuaUnlock(L); return status; } /* ** {====================================================== ** Symbolic Execution and code checker ** ======================================================= */ private static int CheckJump(Proto pt, int pc) { if (!(0 <= pc && pc < pt.sizecode)) return 0; return 1; } private static int CheckReg(Proto pt, int reg) { if (!((reg) < (pt).maxstacksize)) return 0; return 1; } private static int PreCheck (Proto pt) { if (!(pt.maxstacksize <= MAXSTACK)) return 0; if (!(pt.numparams+(pt.is_vararg & VARARG_HASARG) <= pt.maxstacksize)) return 0; if (!(((pt.is_vararg & VARARG_NEEDSARG)==0) || ((pt.is_vararg & VARARG_HASARG)!=0))) return 0; if (!(pt.sizeupvalues <= pt.nups)) return 0; if (!(pt.sizelineinfo == pt.sizecode || pt.sizelineinfo == 0)) return 0; if (!(pt.sizecode > 0 && GET_OPCODE(pt.code[pt.sizecode - 1]) == OpCode.OP_RETURN)) return 0; return 1; } public static int CheckOpenOp(Proto pt, int pc) { return LuaGCheckOpenOp(pt.code[pc + 1]); } [CLSCompliantAttribute(false)] public static int LuaGCheckOpenOp (Instruction i) { switch (GET_OPCODE(i)) { case OpCode.OP_CALL: case OpCode.OP_TAILCALL: case OpCode.OP_RETURN: case OpCode.OP_SETLIST: { if (!(GETARG_B(i) == 0)) return 0; return 1; } default: return 0; /* invalid instruction after an open call */ } } private static int CheckArgMode (Proto pt, int r, OpArgMask mode) { switch (mode) { case OpArgMask.OpArgN: if (r!=0) return 0; break; case OpArgMask.OpArgU: break; case OpArgMask.OpArgR: CheckReg(pt, r); break; case OpArgMask.OpArgK: if (!( (ISK(r) != 0) ? INDEXK(r) < pt.sizek : r < pt.maxstacksize)) return 0; break; } return 1; } private static Instruction SymbExec (Proto pt, int lastpc, int reg) { int pc; int last; /* stores position of last instruction that changed `reg' */ int dest; last = pt.sizecode-1; /* points to final return (a `neutral' instruction) */ if (PreCheck(pt)==0) return 0; for (pc = 0; pc < lastpc; pc++) { Instruction i = pt.code[pc]; OpCode op = GET_OPCODE(i); int a = GETARG_A(i); int b = 0; int c = 0; if (!((int)op < NUM_OPCODES)) return 0; CheckReg(pt, a); switch (getOpMode(op)) { case OpMode.iABC: { b = GETARG_B(i); c = GETARG_C(i); if (CheckArgMode(pt, b, getBMode(op))==0) return 0; if (CheckArgMode(pt, c, getCMode(op))==0) return 0; break; } case OpMode.iABx: { b = GETARG_Bx(i); if (getBMode(op) == OpArgMask.OpArgK) if (!(b < pt.sizek)) return 0; break; } case OpMode.iAsBx: { b = GETARG_sBx(i); if (getBMode(op) == OpArgMask.OpArgR) { dest = pc+1+b; if (!((0 <= dest && dest < pt.sizecode))) return 0; if (dest > 0) { int j; /* check that it does not jump to a setlist count; this is tricky, because the count from a previous setlist may have the same value of an invalid setlist; so, we must go all the way back to the first of them (if any) */ for (j = 0; j < dest; j++) { Instruction d = pt.code[dest-1-j]; if (!(GET_OPCODE(d) == OpCode.OP_SETLIST && GETARG_C(d) == 0)) break; } /* if 'j' is even, previous value is not a setlist (even if it looks like one) */ if ((j&1)!=0) return 0; } } break; } } if (testAMode(op) != 0) { if (a == reg) last = pc; /* change register `a' */ } if (testTMode(op) != 0) { if (!(pc+2 < pt.sizecode)) return 0; /* check skip */ if (!(GET_OPCODE(pt.code[pc + 1]) == OpCode.OP_JMP)) return 0; } switch (op) { case OpCode.OP_LOADBOOL: { if (c == 1) { /* does it jump? */ if (!(pc+2 < pt.sizecode)) return 0; /* check its jump */ if (!(GET_OPCODE(pt.code[pc + 1]) != OpCode.OP_SETLIST || GETARG_C(pt.code[pc + 1]) != 0)) return 0; } break; } case OpCode.OP_LOADNIL: { if (a <= reg && reg <= b) last = pc; /* set registers from `a' to `b' */ break; } case OpCode.OP_GETUPVAL: case OpCode.OP_SETUPVAL: { if (!(b < pt.nups)) return 0; break; } case OpCode.OP_GETGLOBAL: case OpCode.OP_SETGLOBAL: { if (!(TTIsString(pt.k[b]))) return 0; break; } case OpCode.OP_SELF: { CheckReg(pt, a+1); if (reg == a+1) last = pc; break; } case OpCode.OP_CONCAT: { if (!(b < c)) return 0; /* at least two operands */ break; } case OpCode.OP_TFORLOOP: { if (!(c >= 1)) return 0; /* at least one result (control variable) */ CheckReg(pt, a+2+c); /* space for results */ if (reg >= a+2) last = pc; /* affect all regs above its base */ break; } case OpCode.OP_FORLOOP: case OpCode.OP_FORPREP: CheckReg(pt, a+3); /* go through ...no, on second thoughts don't, because this is C# */ dest = pc + 1 + b; /* not full check and jump is forward and do not skip `lastpc'? */ if (reg != NO_REG && pc < dest && dest <= lastpc) pc += b; /* do the jump */ break; case OpCode.OP_JMP: { dest = pc+1+b; /* not full check and jump is forward and do not skip `lastpc'? */ if (reg != NO_REG && pc < dest && dest <= lastpc) pc += b; /* do the jump */ break; } case OpCode.OP_CALL: case OpCode.OP_TAILCALL: { if (b != 0) { CheckReg(pt, a+b-1); } c--; /* c = num. returns */ if (c == LUA_MULTRET) { if (CheckOpenOp(pt, pc)==0) return 0; } else if (c != 0) CheckReg(pt, a+c-1); if (reg >= a) last = pc; /* affect all registers above base */ break; } case OpCode.OP_RETURN: { b--; /* b = num. returns */ if (b > 0) CheckReg(pt, a+b-1); break; } case OpCode.OP_SETLIST: { if (b > 0) CheckReg(pt, a + b); if (c == 0) { pc++; if (!(pc < pt.sizecode - 1)) return 0; } break; } case OpCode.OP_CLOSURE: { int nup, j; if (!(b < pt.sizep)) return 0; nup = pt.p[b].nups; if (!(pc + nup < pt.sizecode)) return 0; for (j = 1; j <= nup; j++) { OpCode op1 = GET_OPCODE(pt.code[pc + j]); if (!(op1 == OpCode.OP_GETUPVAL || op1 == OpCode.OP_MOVE)) return 0; } if (reg != NO_REG) /* tracing? */ pc += nup; /* do not 'execute' these pseudo-instructions */ break; } case OpCode.OP_VARARG: { if (!( (pt.is_vararg & VARARG_ISVARARG)!=0 && (pt.is_vararg & VARARG_NEEDSARG)==0 )) return 0; b--; if (b == LUA_MULTRET) if (CheckOpenOp(pt, pc)==0) return 0; CheckReg(pt, a+b-1); break; } default: break; } } return pt.code[last]; } //#undef check //#undef checkjump //#undef checkreg /* }====================================================== */ public static int LuaGCheckCode (Proto pt) { return (SymbExec(pt, pt.sizecode, NO_REG) != 0) ? 1 : 0; } private static CharPtr KName (Proto p, int c) { if (ISK(c)!=0 && TTIsString(p.k[INDEXK(c)])) return SValue(p.k[INDEXK(c)]); else return "?"; } private static CharPtr GetObjName (LuaState L, CallInfo ci, int stackpos, ref CharPtr name) { if (IsLua(ci)) { /* a Lua function? */ Proto p = CIFunc(ci).l.p; int pc = CurrentPC(L, ci); Instruction i; name = LuaFGetLocalName(p, stackpos+1, pc); if (name!=null) /* is a local? */ return "local"; i = SymbExec(p, pc, stackpos); /* try symbolic execution */ LuaAssert(pc != -1); switch (GET_OPCODE(i)) { case OpCode.OP_GETGLOBAL: { int g = GETARG_Bx(i); /* global index */ LuaAssert(TTIsString(p.k[g])); name = SValue(p.k[g]); return "global"; } case OpCode.OP_MOVE: { int a = GETARG_A(i); int b = GETARG_B(i); /* move from `b' to `a' */ if (b < a) return GetObjName(L, ci, b, ref name); /* get name for `b' */ break; } case OpCode.OP_GETTABLE: { int k = GETARG_C(i); /* key index */ name = KName(p, k); return "field"; } case OpCode.OP_GETUPVAL: { int u = GETARG_B(i); /* upvalue index */ name = (p.upvalues!=null) ? GetStr(p.upvalues[u]) : "?"; return "upvalue"; } case OpCode.OP_SELF: { int k = GETARG_C(i); /* key index */ name = KName(p, k); return "method"; } default: break; } } return null; /* no useful name found */ } private static CharPtr GetFuncName (LuaState L, CallInfo ci, ref CharPtr name) { Instruction i; if ((IsLua(ci) && ci.tailcalls > 0) || !IsLua(ci - 1)) return null; /* calling function is not Lua (or is unknown) */ CallInfo.Dec(ref ci); /* calling function */ i = CIFunc(ci).l.p.code[CurrentPC(L, ci)]; if (GET_OPCODE(i) == OpCode.OP_CALL || GET_OPCODE(i) == OpCode.OP_TAILCALL || GET_OPCODE(i) == OpCode.OP_TFORLOOP) return GetObjName(L, ci, GETARG_A(i), ref name); else return null; /* no useful name can be found */ } /* only ANSI way to check whether a pointer points to an array */ private static int IsInStack (CallInfo ci, TValue o) { StkId p; for (p = ci.base_; p < ci.top; StkId.Inc(ref p)) if (o == p) return 1; return 0; } public static void LuaGTypeError (LuaState L, TValue o, CharPtr op) { CharPtr name = null; CharPtr t = luaT_typenames[TType(o)]; CharPtr kind = (IsInStack(L.ci, o)) != 0 ? GetObjName(L, L.ci, CastInt(o - L.base_), ref name) : null; if (kind != null) LuaGRunError(L, "attempt to %s %s " + LUA_QS + " (a %s value)", op, kind, name, t); else LuaGRunError(L, "attempt to %s a %s value", op, t); } public static void LuaGConcatError (LuaState L, StkId p1, StkId p2) { if (TTIsString(p1) || TTIsNumber(p1)) p1 = p2; LuaAssert(!TTIsString(p1) && !TTIsNumber(p1)); LuaGTypeError(L, p1, "concatenate"); } public static void LuaGArithError (LuaState L, TValue p1, TValue p2) { TValue temp = new LuaTypeValue(); if (luaV_tonumber(p1, temp) == null) p2 = p1; /* first operand is wrong */ LuaGTypeError(L, p2, "perform arithmetic on"); } public static int LuaGOrderError (LuaState L, TValue p1, TValue p2) { CharPtr t1 = luaT_typenames[TType(p1)]; CharPtr t2 = luaT_typenames[TType(p2)]; if (t1[2] == t2[2]) LuaGRunError(L, "attempt to compare two %s values", t1); else LuaGRunError(L, "attempt to compare %s with %s", t1, t2); return 0; } private static void AddInfo (LuaState L, CharPtr msg) { CallInfo ci = L.ci; if (IsLua(ci)) { /* is Lua code? */ CharPtr buff = new CharPtr(new char[LUA_IDSIZE]); /* add file:line information */ int line = CurrentLine(L, ci); LuaOChunkID(buff, GetStr(GetLuaProto(ci).source), LUA_IDSIZE); LuaOPushFString(L, "%s:%d: %s", buff, line, msg); } } public static void LuaGErrorMsg (LuaState L) { if (L.errfunc != 0) { /* is there an error handling function? */ StkId errfunc = RestoreStack(L, L.errfunc); if (!TTIsFunction(errfunc)) LuaDThrow(L, LUA_ERRERR); SetObj2S(L, L.top, L.top - 1); /* move argument */ SetObj2S(L, L.top - 1, errfunc); /* push function */ IncrTop(L); LuaDCall(L, L.top - 2, 1); /* call it */ } LuaDThrow(L, LUA_ERRRUN); } public static void LuaGRunError(LuaState L, CharPtr fmt, params object[] argp) { AddInfo(L, LuaOPushVFString(L, fmt, argp)); LuaGErrorMsg(L); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.Configuration; using System.IO; using System.ComponentModel; using Csla.Validation; namespace Northwind.CSLA.Library { /// <summary> /// ShipperOrder Generated by MyGeneration using the CSLA Object Mapping template /// </summary> [Serializable()] [TypeConverter(typeof(ShipperOrderConverter))] public partial class ShipperOrder : BusinessBase<ShipperOrder>, IVEHasBrokenRules { #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } private int _OrderID; [System.ComponentModel.DataObjectField(true, true)] public int OrderID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyOrder != null) _OrderID = _MyOrder.OrderID; return _OrderID; } } private Order _MyOrder; [System.ComponentModel.DataObjectField(true, true)] public Order MyOrder { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyOrder == null && _OrderID != 0) _MyOrder = Order.Get(_OrderID); return _MyOrder; } } private string _CustomerID = string.Empty; public string CustomerID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyCustomer != null) _CustomerID = _MyCustomer.CustomerID; return _CustomerID; } } private Customer _MyCustomer; public Customer MyCustomer { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyCustomer == null && _CustomerID != null) _MyCustomer = Customer.Get((string)_CustomerID); return _MyCustomer; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_MyCustomer != value) { _MyCustomer = value; _CustomerID = (value == null ? null : (string) value.CustomerID); PropertyHasChanged(); } } } private int? _EmployeeID; public int? EmployeeID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyEmployee != null) _EmployeeID = _MyEmployee.EmployeeID; return _EmployeeID; } } private Employee _MyEmployee; public Employee MyEmployee { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyEmployee == null && _EmployeeID != null) _MyEmployee = Employee.Get((int)_EmployeeID); return _MyEmployee; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_MyEmployee != value) { _MyEmployee = value; _EmployeeID = (value == null ? null : (int?) value.EmployeeID); PropertyHasChanged(); } } } private string _OrderDate = string.Empty; public string OrderDate { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _OrderDate; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; _OrderDate = value; try { SmartDate tmp = new SmartDate(value); if (_OrderDate != tmp.ToString()) { _OrderDate = tmp.ToString(); // TODO: Any Cross Property Validation } } catch { } PropertyHasChanged(); } } private string _RequiredDate = string.Empty; public string RequiredDate { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _RequiredDate; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; _RequiredDate = value; try { SmartDate tmp = new SmartDate(value); if (_RequiredDate != tmp.ToString()) { _RequiredDate = tmp.ToString(); // TODO: Any Cross Property Validation } } catch { } PropertyHasChanged(); } } private string _ShippedDate = string.Empty; public string ShippedDate { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShippedDate; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; _ShippedDate = value; try { SmartDate tmp = new SmartDate(value); if (_ShippedDate != tmp.ToString()) { _ShippedDate = tmp.ToString(); // TODO: Any Cross Property Validation } } catch { } PropertyHasChanged(); } } private decimal? _Freight; public decimal? Freight { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Freight; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_Freight != value) { _Freight = value; PropertyHasChanged(); } } } private string _ShipName = string.Empty; public string ShipName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShipName; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ShipName != value) { _ShipName = value; PropertyHasChanged(); } } } private string _ShipAddress = string.Empty; public string ShipAddress { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShipAddress; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ShipAddress != value) { _ShipAddress = value; PropertyHasChanged(); } } } private string _ShipCity = string.Empty; public string ShipCity { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShipCity; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ShipCity != value) { _ShipCity = value; PropertyHasChanged(); } } } private string _ShipRegion = string.Empty; public string ShipRegion { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShipRegion; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ShipRegion != value) { _ShipRegion = value; PropertyHasChanged(); } } } private string _ShipPostalCode = string.Empty; public string ShipPostalCode { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShipPostalCode; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ShipPostalCode != value) { _ShipPostalCode = value; PropertyHasChanged(); } } } private string _ShipCountry = string.Empty; public string ShipCountry { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ShipCountry; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ShipCountry != value) { _ShipCountry = value; PropertyHasChanged(); } } } // TODO: Check ShipperOrder.GetIdValue to assure that the ID returned is unique /// <summary> /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// </summary> /// <returns>A Unique ID for the current ShipperOrder</returns> protected override object GetIdValue() { return _OrderID; } // TODO: Replace base ShipperOrder.ToString function as necessary /// <summary> /// Overrides Base ToString /// </summary> /// <returns>A string representation of current ShipperOrder</returns> //public override string ToString() //{ // return base.ToString(); //} #endregion #region ValidationRules [NonSerialized] private bool _CheckingBrokenRules=false; public IVEHasBrokenRules HasBrokenRules { get { if(_CheckingBrokenRules)return null; if (BrokenRulesCollection.Count > 0) return this; try { _CheckingBrokenRules=true; IVEHasBrokenRules hasBrokenRules = null; if (_MyCustomer != null && (hasBrokenRules = _MyCustomer.HasBrokenRules) != null) return hasBrokenRules; if (_MyEmployee != null && (hasBrokenRules = _MyEmployee.HasBrokenRules) != null) return hasBrokenRules; return hasBrokenRules; } finally { _CheckingBrokenRules=false; } } } public BrokenRulesCollection BrokenRules { get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); } } protected override void AddBusinessRules() { ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("CustomerID", 5)); ValidationRules.AddRule<ShipperOrder>(OrderDateValid, "OrderDate"); ValidationRules.AddRule<ShipperOrder>(RequiredDateValid, "RequiredDate"); ValidationRules.AddRule<ShipperOrder>(ShippedDateValid, "ShippedDate"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipName", 40)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipAddress", 60)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipCity", 15)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipRegion", 15)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipPostalCode", 10)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ShipCountry", 15)); // TODO: Add other validation rules } private static bool OrderDateValid(ShipperOrder target, Csla.Validation.RuleArgs e) { try { DateTime tmp = SmartDate.StringToDate(target._OrderDate); } catch { e.Description = "Invalid Date"; return false; } return true; } private static bool RequiredDateValid(ShipperOrder target, Csla.Validation.RuleArgs e) { try { DateTime tmp = SmartDate.StringToDate(target._RequiredDate); } catch { e.Description = "Invalid Date"; return false; } return true; } private static bool ShippedDateValid(ShipperOrder target, Csla.Validation.RuleArgs e) { try { DateTime tmp = SmartDate.StringToDate(target._ShippedDate); } catch { e.Description = "Invalid Date"; return false; } return true; } // Sample data comparison validation rule //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) //{ // if (_started > _ended) // { // e.Description = "Start date can't be after end date"; // return false; // } // else // return true; //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //TODO: Who can read/write which fields //AuthorizationRules.AllowRead(OrderID, "<Role(s)>"); //AuthorizationRules.AllowRead(CustomerID, "<Role(s)>"); //AuthorizationRules.AllowWrite(CustomerID, "<Role(s)>"); //AuthorizationRules.AllowRead(EmployeeID, "<Role(s)>"); //AuthorizationRules.AllowWrite(EmployeeID, "<Role(s)>"); //AuthorizationRules.AllowRead(OrderDate, "<Role(s)>"); //AuthorizationRules.AllowWrite(OrderDate, "<Role(s)>"); //AuthorizationRules.AllowRead(RequiredDate, "<Role(s)>"); //AuthorizationRules.AllowWrite(RequiredDate, "<Role(s)>"); //AuthorizationRules.AllowRead(ShippedDate, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShippedDate, "<Role(s)>"); //AuthorizationRules.AllowRead(Freight, "<Role(s)>"); //AuthorizationRules.AllowWrite(Freight, "<Role(s)>"); //AuthorizationRules.AllowRead(ShipName, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShipName, "<Role(s)>"); //AuthorizationRules.AllowRead(ShipAddress, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShipAddress, "<Role(s)>"); //AuthorizationRules.AllowRead(ShipCity, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShipCity, "<Role(s)>"); //AuthorizationRules.AllowRead(ShipRegion, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShipRegion, "<Role(s)>"); //AuthorizationRules.AllowRead(ShipPostalCode, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShipPostalCode, "<Role(s)>"); //AuthorizationRules.AllowRead(ShipCountry, "<Role(s)>"); //AuthorizationRules.AllowWrite(ShipCountry, "<Role(s)>"); } public static bool CanAddObject() { // TODO: Can Add Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } public static bool CanGetObject() { // TODO: CanGet Authorization return true; } public static bool CanDeleteObject() { // TODO: CanDelete Authorization //bool result = false; //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; //return result; return true; } public static bool CanEditObject() { // TODO: CanEdit Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } #endregion #region Factory Methods public int CurrentEditLevel { get { return EditLevel; } } internal static ShipperOrder New() { return new ShipperOrder(); } internal static ShipperOrder Get(SafeDataReader dr) { return new ShipperOrder(dr); } public ShipperOrder() { MarkAsChild(); _OrderID = Order.NextOrderID; _Freight = _ShipperOrderExtension.DefaultFreight; ValidationRules.CheckRules(); } internal ShipperOrder(SafeDataReader dr) { MarkAsChild(); Fetch(dr); } #endregion #region Data Access Portal private void Fetch(SafeDataReader dr) { Database.LogInfo("ShipperOrder.FetchDR", GetHashCode()); try { _OrderID = dr.GetInt32("OrderID"); _CustomerID = dr.GetString("CustomerID"); _EmployeeID = (int?)dr.GetValue("EmployeeID"); _OrderDate = dr.GetSmartDate("OrderDate").Text; _RequiredDate = dr.GetSmartDate("RequiredDate").Text; _ShippedDate = dr.GetSmartDate("ShippedDate").Text; _Freight = (decimal?)dr.GetValue("Freight"); _ShipName = dr.GetString("ShipName"); _ShipAddress = dr.GetString("ShipAddress"); _ShipCity = dr.GetString("ShipCity"); _ShipRegion = dr.GetString("ShipRegion"); _ShipPostalCode = dr.GetString("ShipPostalCode"); _ShipCountry = dr.GetString("ShipCountry"); } catch (Exception ex) // FKItem Fetch { Database.LogException("ShipperOrder.FetchDR", ex); throw new DbCslaException("ShipperOrder.Fetch", ex); } MarkOld(); } internal void Insert(Shipper myShipper) { // if we're not dirty then don't update the database if (!this.IsDirty) return; SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; Order.Add(cn, ref _OrderID, _MyCustomer, _MyEmployee, new SmartDate(_OrderDate), new SmartDate(_RequiredDate), new SmartDate(_ShippedDate), myShipper, _Freight, _ShipName, _ShipAddress, _ShipCity, _ShipRegion, _ShipPostalCode, _ShipCountry); MarkOld(); } internal void Update(Shipper myShipper) { // if we're not dirty then don't update the database if (!this.IsDirty) return; SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; Order.Update(cn, ref _OrderID, _MyCustomer, _MyEmployee, new SmartDate(_OrderDate), new SmartDate(_RequiredDate), new SmartDate(_ShippedDate), myShipper, _Freight, _ShipName, _ShipAddress, _ShipCity, _ShipRegion, _ShipPostalCode, _ShipCountry); MarkOld(); } internal void DeleteSelf(Shipper myShipper) { // if we're not dirty then don't update the database if (!this.IsDirty) return; // if we're new then don't update the database if (this.IsNew) return; SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; Order.Remove(cn, _OrderID); MarkNew(); } #endregion // Standard Default Code #region extension ShipperOrderExtension _ShipperOrderExtension = new ShipperOrderExtension(); [Serializable()] partial class ShipperOrderExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual decimal? DefaultFreight { get { return 0; } } // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } // Instance Authorization Rules public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } // Validation Rules public virtual void AddValidationRules(Csla.Validation.ValidationRules rules) { // Needs to be overriden to add new validation rules } // InstanceValidation Rules public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) { // Needs to be overriden to add new validation rules } } #endregion } // Class #region Converter internal class ShipperOrderConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is ShipperOrder) { // Return the ToString value return ((ShipperOrder)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create ShipperOrderExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace Northwind.CSLA.Library //{ // public partial class ShipperOrder // { // partial class ShipperOrderExtension : extensionBase // { // // TODO: Override automatic defaults // public virtual decimal? DefaultFreight // { // get { return 0; } // } // public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) // { // //rules.AllowRead(Dbid, "<Role(s)>"); // } // public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) // { // //rules.AllowInstanceRead(Dbid, "<Role(s)>"); // } // public new void AddValidationRules(Csla.Validation.ValidationRules rules) // { // rules.AddRule( // Csla.Validation.CommonRules.StringMaxLength, // new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); // } // public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) // { // rules.AddInstanceRule(/* Instance Validation Rule */); // } // } // } //}
// 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.Xml.Schema; using System.Diagnostics; namespace System.Xml { // Represents an attribute of the XMLElement object. Valid and default // values for the attribute are defined in a DTD or schema. public class XmlAttribute : XmlNode { XmlName name; XmlLinkedNode lastChild; internal XmlAttribute(XmlName name, XmlDocument doc) : base(doc) { Debug.Assert(name != null); Debug.Assert(doc != null); this.parentNode = null; if (!doc.IsLoading) { XmlDocument.CheckName(name.Prefix); XmlDocument.CheckName(name.LocalName); } if (name.LocalName.Length == 0) throw new ArgumentException(SR.Xdom_Attr_Name); this.name = name; } internal int LocalNameHash { get { return name.HashCode; } } protected internal XmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc) : this(doc.AddAttrXmlName(prefix, localName, namespaceURI), doc) { } internal XmlName XmlName { get { return name; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { // CloneNode for attributes is deep irrespective of parameter 'deep' value Debug.Assert(OwnerDocument != null); XmlDocument doc = OwnerDocument; XmlAttribute attr = doc.CreateAttribute(Prefix, LocalName, NamespaceURI); attr.CopyChildren(doc, this, true); return attr; } // Gets the parent of this node (for nodes that can have parents). public override XmlNode ParentNode { get { return null; } } // Gets the name of the node. public override String Name { get { return name.Name; } } // Gets the name of the node without the namespace prefix. public override String LocalName { get { return name.LocalName; } } // Gets the namespace URI of this node. public override String NamespaceURI { get { return name.NamespaceURI; } } // Gets or sets the namespace prefix of this node. public override String Prefix { get { return name.Prefix; } set { name = name.OwnerDocument.AddAttrXmlName(value, LocalName, NamespaceURI); } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Attribute; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return name.OwnerDocument; } } // Gets or sets the value of the node. public override String Value { get { return InnerText; } set { InnerText = value; } //use InnerText which has perf optimization } public override String InnerText { set { if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = base.InnerText; base.InnerText = value; ResetOwnerElementInElementIdAttrMap(innerText); } else { base.InnerText = value; } } } // This function returns false because it is implication of removing schema. // If removed more methods would have to be removed as well and it would make adding schema back much harder. internal bool PrepareOwnerElementInElementIdAttrMap() { return false; } internal void ResetOwnerElementInElementIdAttrMap(string oldInnerText) { XmlElement ownerElement = OwnerElement; if (ownerElement != null) { ownerElement.Attributes.ResetParentInElementIdAttrMap(oldInnerText, InnerText); } } internal override bool IsContainer { get { return true; } } //the function is provided only at Load time to speed up Load process internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(newChild, this); if (args != null) doc.BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (lastChild == null) { // if LastNode == null newNode.next = newNode; lastChild = newNode; newNode.SetParentForLoad(this); } else { XmlLinkedNode refNode = lastChild; // refNode = LastNode; newNode.next = refNode.next; refNode.next = newNode; lastChild = newNode; // LastNode = newNode; if (refNode.IsText && newNode.IsText) { NestTextNodes(refNode, newNode); } else { newNode.SetParentForLoad(this); } } if (args != null) doc.AfterEvent(args); return newNode; } internal override XmlLinkedNode LastNode { get { return lastChild; } set { lastChild = value; } } internal override bool IsValidChildType(XmlNodeType type) { return (type == XmlNodeType.Text) || (type == XmlNodeType.EntityReference); } // Gets a value indicating whether the value was explicitly set. public virtual bool Specified { get { return true; } } public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.InsertBefore(newChild, refChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.InsertBefore(newChild, refChild); } return node; } public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.InsertAfter(newChild, refChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.InsertAfter(newChild, refChild); } return node; } public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.ReplaceChild(newChild, oldChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.ReplaceChild(newChild, oldChild); } return node; } public override XmlNode RemoveChild(XmlNode oldChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.RemoveChild(oldChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.RemoveChild(oldChild); } return node; } public override XmlNode PrependChild(XmlNode newChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.PrependChild(newChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.PrependChild(newChild); } return node; } public override XmlNode AppendChild(XmlNode newChild) { XmlNode node; if (PrepareOwnerElementInElementIdAttrMap()) { string innerText = InnerText; node = base.AppendChild(newChild); ResetOwnerElementInElementIdAttrMap(innerText); } else { node = base.AppendChild(newChild); } return node; } // DOM Level 2 // Gets the XmlElement node that contains this attribute. public virtual XmlElement OwnerElement { get { return parentNode as XmlElement; } } // Gets or sets the markup representing just the children of this node. public override string InnerXml { set { RemoveAll(); XmlLoader loader = new XmlLoader(); loader.LoadInnerXmlAttribute(this, value); } } // Saves the node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteStartAttribute(Prefix, LocalName, NamespaceURI); WriteContentTo(w); w.WriteEndAttribute(); } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { for (XmlNode node = FirstChild; node != null; node = node.NextSibling) { node.WriteTo(w); } } public override String BaseURI { get { if (OwnerElement != null) return OwnerElement.BaseURI; return String.Empty; } } internal override void SetParent(XmlNode node) { this.parentNode = node; } internal override XmlSpace XmlSpace { get { if (OwnerElement != null) return OwnerElement.XmlSpace; return XmlSpace.None; } } internal override String XmlLang { get { if (OwnerElement != null) return OwnerElement.XmlLang; return String.Empty; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using OutOfMemory.Areas.HelpPage.ModelDescriptions; using OutOfMemory.Areas.HelpPage.Models; namespace OutOfMemory.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright 2014 Adrian Chlubek. This file is part of GTA Multiplayer IV project. // Use of this source code is governed by a MIT license that can be // found in the LICENSE file. namespace MIVClientGUI { partial class ServerBrowser { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServerBrowser)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.clientToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.runGameWithoutClientToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.conectManuallyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.remoteConsoleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.serverMonitorToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.resolutionSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearServerListToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openTutorialToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutMIVToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.listView1 = new System.Windows.Forms.ListView(); this.nameColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.ipColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.portsColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.playerCountColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.button4 = new System.Windows.Forms.Button(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.clientToolStripMenuItem, this.toolsToolStripMenuItem, this.optionsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.Flow; this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.menuStrip1.Size = new System.Drawing.Size(519, 25); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // clientToolStripMenuItem // this.clientToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.runGameWithoutClientToolStripMenuItem, this.conectManuallyToolStripMenuItem, this.exitToolStripMenuItem}); this.clientToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.clientToolStripMenuItem.Name = "clientToolStripMenuItem"; this.clientToolStripMenuItem.Size = new System.Drawing.Size(52, 21); this.clientToolStripMenuItem.Text = "Client"; // // runGameWithoutClientToolStripMenuItem // this.runGameWithoutClientToolStripMenuItem.Name = "runGameWithoutClientToolStripMenuItem"; this.runGameWithoutClientToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.runGameWithoutClientToolStripMenuItem.Text = "Run game without client"; this.runGameWithoutClientToolStripMenuItem.Click += new System.EventHandler(this.runGameWithoutClientToolStripMenuItem_Click); // // conectManuallyToolStripMenuItem // this.conectManuallyToolStripMenuItem.Name = "conectManuallyToolStripMenuItem"; this.conectManuallyToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.conectManuallyToolStripMenuItem.Text = "Connect manually"; // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(215, 22); this.exitToolStripMenuItem.Text = "Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.remoteConsoleToolStripMenuItem, this.serverMonitorToolStripMenuItem}); this.toolsToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(52, 21); this.toolsToolStripMenuItem.Text = "Tools"; // // remoteConsoleToolStripMenuItem // this.remoteConsoleToolStripMenuItem.Name = "remoteConsoleToolStripMenuItem"; this.remoteConsoleToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.remoteConsoleToolStripMenuItem.Text = "Remote console"; // // serverMonitorToolStripMenuItem // this.serverMonitorToolStripMenuItem.Name = "serverMonitorToolStripMenuItem"; this.serverMonitorToolStripMenuItem.Size = new System.Drawing.Size(170, 22); this.serverMonitorToolStripMenuItem.Text = "Server monitor"; // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.resolutionSettingsToolStripMenuItem, this.clearServerListToolStripMenuItem}); this.optionsToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(66, 21); this.optionsToolStripMenuItem.Text = "Options"; // // resolutionSettingsToolStripMenuItem // this.resolutionSettingsToolStripMenuItem.Name = "resolutionSettingsToolStripMenuItem"; this.resolutionSettingsToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.resolutionSettingsToolStripMenuItem.Text = "Resolution settings"; // // clearServerListToolStripMenuItem // this.clearServerListToolStripMenuItem.Name = "clearServerListToolStripMenuItem"; this.clearServerListToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.clearServerListToolStripMenuItem.Text = "Clear server list"; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openTutorialToolStripMenuItem, this.aboutMIVToolStripMenuItem}); this.helpToolStripMenuItem.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(47, 21); this.helpToolStripMenuItem.Text = "Help"; // // openTutorialToolStripMenuItem // this.openTutorialToolStripMenuItem.Name = "openTutorialToolStripMenuItem"; this.openTutorialToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.openTutorialToolStripMenuItem.Text = "Open tutorial"; // // aboutMIVToolStripMenuItem // this.aboutMIVToolStripMenuItem.Name = "aboutMIVToolStripMenuItem"; this.aboutMIVToolStripMenuItem.Size = new System.Drawing.Size(153, 22); this.aboutMIVToolStripMenuItem.Text = "About MIV"; // // listView1 // this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView1.AutoArrange = false; this.listView1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.listView1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.nameColumn, this.ipColumn, this.portsColumn, this.playerCountColumn}); this.listView1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.listView1.FullRowSelect = true; this.listView1.GridLines = true; this.listView1.HideSelection = false; this.listView1.Location = new System.Drawing.Point(12, 64); this.listView1.MultiSelect = false; this.listView1.Name = "listView1"; this.listView1.ShowGroups = false; this.listView1.Size = new System.Drawing.Size(495, 482); this.listView1.TabIndex = 2; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.Click += new System.EventHandler(this.listView1_Click); this.listView1.Leave += new System.EventHandler(this.listView1_Leave); // // nameColumn // this.nameColumn.Text = "Name"; this.nameColumn.Width = 232; // // ipColumn // this.ipColumn.Text = "IP Address"; this.ipColumn.Width = 97; // // portsColumn // this.portsColumn.Text = "Ports"; this.portsColumn.Width = 80; // // playerCountColumn // this.playerCountColumn.Text = "Player count"; this.playerCountColumn.Width = 85; // // button1 // this.button1.Enabled = false; this.button1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.button1.Location = new System.Drawing.Point(13, 31); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 27); this.button1.TabIndex = 3; this.button1.Text = "Connect"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.button2.Location = new System.Drawing.Point(94, 31); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 27); this.button2.TabIndex = 4; this.button2.Text = "Add"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.Enabled = false; this.button3.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.button3.Location = new System.Drawing.Point(175, 31); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(75, 27); this.button3.TabIndex = 5; this.button3.Text = "Remove"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.label1.ForeColor = System.Drawing.Color.Black; this.label1.Location = new System.Drawing.Point(341, 36); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(68, 17); this.label1.TabIndex = 6; this.label1.Text = "Nickname:"; // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.textBox1.Location = new System.Drawing.Point(415, 33); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(92, 25); this.textBox1.TabIndex = 7; this.textBox1.Text = "Player"; this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave); // // button4 // this.button4.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.button4.Location = new System.Drawing.Point(256, 30); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 28); this.button4.TabIndex = 8; this.button4.Text = "Refresh"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // ServerBrowser // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(230)))), ((int)(((byte)(230))))); this.ClientSize = new System.Drawing.Size(519, 558); this.Controls.Add(this.button4); this.Controls.Add(this.textBox1); this.Controls.Add(this.label1); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.listView1); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "ServerBrowser"; this.Text = "MIV Server Browser"; this.Load += new System.EventHandler(this.ServerBrowser_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem clientToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem runGameWithoutClientToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem remoteConsoleToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem serverMonitorToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem resolutionSettingsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearServerListToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openTutorialToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutMIVToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem conectManuallyToolStripMenuItem; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button4; private System.Windows.Forms.ColumnHeader nameColumn; private System.Windows.Forms.ColumnHeader ipColumn; private System.Windows.Forms.ColumnHeader portsColumn; private System.Windows.Forms.ColumnHeader playerCountColumn; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// JobOperations operations. /// </summary> internal partial class JobOperations : IServiceOperations<DataLakeAnalyticsJobManagementClient>, IJobOperations { /// <summary> /// Initializes a new instance of the JobOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal JobOperations(DataLakeAnalyticsJobManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeAnalyticsJobManagementClient /// </summary> public DataLakeAnalyticsJobManagementClient Client { get; private set; } /// <summary> /// Gets statistics of the specified job. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// Job Information ID. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobStatistics>> GetStatisticsWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("jobIdentity", jobIdentity); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetStatistics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}/GetStatistics"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); _url = _url.Replace("{jobIdentity}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobIdentity, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobStatistics>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobStatistics>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the job debug data information specified by the job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobDataPath>> GetDebugDataPathWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("jobIdentity", jobIdentity); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetDebugDataPath", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}/GetDebugDataPath"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); _url = _url.Replace("{jobIdentity}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobIdentity, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobDataPath>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobDataPath>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Builds (compiles) the specified job in the specified Data Lake Analytics /// account for job correctness and validation. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='parameters'> /// The parameters to build a job. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobInformation>> BuildWithHttpMessagesAsync(string accountName, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Build", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "BuildJob"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobInformation>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobInformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Cancels the running job specified by the job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID to cancel. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> CancelWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("jobIdentity", jobIdentity); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}/CancelJob"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); _url = _url.Replace("{jobIdentity}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobIdentity, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the job information for the specified job ID. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// JobInfo ID. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobInformation>> GetWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("jobIdentity", jobIdentity); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); _url = _url.Replace("{jobIdentity}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobIdentity, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobInformation>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobInformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Submits a job to the specified Data Lake Analytics account. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='jobIdentity'> /// The job ID (a GUID) for the job being submitted. /// </param> /// <param name='parameters'> /// The parameters to submit a job. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<JobInformation>> CreateWithHttpMessagesAsync(string accountName, System.Guid jobIdentity, JobInformation parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("accountName", accountName); tracingParameters.Add("jobIdentity", jobIdentity); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs/{jobIdentity}"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); _url = _url.Replace("{jobIdentity}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(jobIdentity, Client.SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<JobInformation>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobInformation>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the jobs, if any, associated with the specified Data Lake Analytics /// account. The response includes a link to the next page of results, if any. /// </summary> /// <param name='accountName'> /// The Azure Data Lake Analytics account to execute job operations on. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='select'> /// OData Select statement. Limits the properties on each entry to just those /// requested, e.g. Categories?$select=CategoryName,Description. Optional. /// </param> /// <param name='count'> /// The Boolean value of true or false to request a count of the matching /// resources included with the resources in the response, e.g. /// Categories?$count=true. Optional. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobInformation>>> ListWithHttpMessagesAsync(string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.AdlaJobDnsSuffix == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.AdlaJobDnsSuffix"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("accountName", accountName); tracingParameters.Add("select", select); tracingParameters.Add("count", count); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "Jobs"; _url = _url.Replace("{accountName}", accountName); _url = _url.Replace("{adlaJobDnsSuffix}", Client.AdlaJobDnsSuffix); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(select))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobInformation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobInformation>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the jobs, if any, associated with the specified Data Lake Analytics /// account. The response includes a link to the next page of results, if any. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<JobInformation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<JobInformation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<JobInformation>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; namespace SchoolBusAPI.Models { /// <summary> /// /// </summary> public partial class Inspection : IEquatable<Inspection> { /// <summary> /// Default constructor, required by entity framework /// </summary> public Inspection() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="Inspection" /> class. /// </summary> /// <param name="Id">Primary Key make this match the Inspection Details page (required).</param> /// <param name="SchoolBus">SchoolBus.</param> /// <param name="Inspector">Defaults for a new inspection to the current user, but can be changed as needed..</param> /// <param name="InspectionDate">The date the inspection was conducted..</param> /// <param name="InspectionType">The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created.</param> /// <param name="InspectionResult">The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here..</param> /// <param name="Notes">A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application..</param> /// <param name="Restrictions">The \&quot;Restrictions\&quot; text from the School Bus record. This is visible on the Inspections screen as a convenience for adjusting it prior to printing the Permit Page..</param> /// <param name="RIPInspectionId">The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details..</param> public Inspection(int Id, SchoolBus SchoolBus = null, User Inspector = null, DateTime? InspectionDate = null, string InspectionType = null, string InspectionResult = null, string Notes = null, string Restrictions = null, string RIPInspectionId = null) { this.Id = Id; this.SchoolBus = SchoolBus; this.Inspector = Inspector; this.InspectionDate = InspectionDate; this.InspectionType = InspectionType; this.InspectionResult = InspectionResult; this.Notes = Notes; this.Restrictions = Restrictions; this.RIPInspectionId = RIPInspectionId; } /// <summary> /// Primary Key make this match the Inspection Details page /// </summary> /// <value>Primary Key make this match the Inspection Details page</value> [MetaDataExtension (Description = "Primary Key make this match the Inspection Details page")] public int Id { get; set; } /// <summary> /// Gets or Sets SchoolBus /// </summary> public SchoolBus SchoolBus { get; set; } [ForeignKey("SchoolBus")] public int? SchoolBusRefId { get; set; } /// <summary> /// Defaults for a new inspection to the current user, but can be changed as needed. /// </summary> /// <value>Defaults for a new inspection to the current user, but can be changed as needed.</value> [MetaDataExtension (Description = "Defaults for a new inspection to the current user, but can be changed as needed.")] public User Inspector { get; set; } [ForeignKey("Inspector")] public int? InspectorRefId { get; set; } /// <summary> /// The date the inspection was conducted. /// </summary> /// <value>The date the inspection was conducted.</value> [MetaDataExtension (Description = "The date the inspection was conducted.")] public DateTime? InspectionDate { get; set; } /// <summary> /// The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created /// </summary> /// <value>The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created</value> [MetaDataExtension (Description = "The type of the inspection - enumerated type of Annual or Re-inspection, pulled from the School Bus record at the time the inspection record is created")] public string InspectionType { get; set; } /// <summary> /// The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here. /// </summary> /// <value>The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here.</value> [MetaDataExtension (Description = "The result of the inspection - enumerated type of Passed or Failed. The detailed results of the inspection are in RIP and not duplicated here.")] public string InspectionResult { get; set; } /// <summary> /// A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application. /// </summary> /// <value>A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application.</value> [MetaDataExtension (Description = "A note about the inspection independent of what goes into the RIP inspection - this is just for the School Bus application.")] public string Notes { get; set; } /// <summary> /// The \"Restrictions\" text from the School Bus record. This is visible on the Inspections screen as a convenience for adjusting it prior to printing the Permit Page. /// </summary> /// <value>The \"Restrictions\" text from the School Bus record. This is visible on the Inspections screen as a convenience for adjusting it prior to printing the Permit Page.</value> [MetaDataExtension (Description = "The &quot;Restrictions&quot; text from the School Bus record. This is visible on the Inspections screen as a convenience for adjusting it prior to printing the Permit Page.")] public string Restrictions { get; set; } /// <summary> /// The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details. /// </summary> /// <value>The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details.</value> [MetaDataExtension (Description = "The ID of the RIP inspection. The expectation is that the user will manually enter a RIP ID such that an external URL can be formed to allow the user to open the RIP inspection and see the inspection details.")] public string RIPInspectionId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Inspection {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" SchoolBus: ").Append(SchoolBus).Append("\n"); sb.Append(" Inspector: ").Append(Inspector).Append("\n"); sb.Append(" InspectionDate: ").Append(InspectionDate).Append("\n"); sb.Append(" InspectionType: ").Append(InspectionType).Append("\n"); sb.Append(" InspectionResult: ").Append(InspectionResult).Append("\n"); sb.Append(" Notes: ").Append(Notes).Append("\n"); sb.Append(" Restrictions: ").Append(Restrictions).Append("\n"); sb.Append(" RIPInspectionId: ").Append(RIPInspectionId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((Inspection)obj); } /// <summary> /// Returns true if Inspection instances are equal /// </summary> /// <param name="other">Instance of Inspection to be compared</param> /// <returns>Boolean</returns> public bool Equals(Inspection other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.SchoolBus == other.SchoolBus || this.SchoolBus != null && this.SchoolBus.Equals(other.SchoolBus) ) && ( this.Inspector == other.Inspector || this.Inspector != null && this.Inspector.Equals(other.Inspector) ) && ( this.InspectionDate == other.InspectionDate || this.InspectionDate != null && this.InspectionDate.Equals(other.InspectionDate) ) && ( this.InspectionType == other.InspectionType || this.InspectionType != null && this.InspectionType.Equals(other.InspectionType) ) && ( this.InspectionResult == other.InspectionResult || this.InspectionResult != null && this.InspectionResult.Equals(other.InspectionResult) ) && ( this.Notes == other.Notes || this.Notes != null && this.Notes.Equals(other.Notes) ) && ( this.Restrictions == other.Restrictions || this.Restrictions != null && this.Restrictions.Equals(other.Restrictions) ) && ( this.RIPInspectionId == other.RIPInspectionId || this.RIPInspectionId != null && this.RIPInspectionId.Equals(other.RIPInspectionId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.SchoolBus != null) { hash = hash * 59 + this.SchoolBus.GetHashCode(); } if (this.Inspector != null) { hash = hash * 59 + this.Inspector.GetHashCode(); } if (this.InspectionDate != null) { hash = hash * 59 + this.InspectionDate.GetHashCode(); } if (this.InspectionType != null) { hash = hash * 59 + this.InspectionType.GetHashCode(); } if (this.InspectionResult != null) { hash = hash * 59 + this.InspectionResult.GetHashCode(); } if (this.Notes != null) { hash = hash * 59 + this.Notes.GetHashCode(); } if (this.Restrictions != null) { hash = hash * 59 + this.Restrictions.GetHashCode(); } if (this.RIPInspectionId != null) { hash = hash * 59 + this.RIPInspectionId.GetHashCode(); } return hash; } } #region Operators public static bool operator ==(Inspection left, Inspection right) { return Equals(left, right); } public static bool operator !=(Inspection left, Inspection right) { return !Equals(left, right); } #endregion Operators } }
//<-- To access the definition of the deleagte RowDelegate using System; using System.Collections; using System.Threading; using IBatisNet.Common; using IBatisNet.Common.Utilities; using IBatisNet.DataMapper.Configuration.Cache; using IBatisNet.DataMapper.MappedStatements; using IBatisNet.DataMapper.Test.Domain; using NUnit.Framework; namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests { /// <summary> /// Summary description for ParameterMapTest. /// </summary> [TestFixture] public class CacheTest : BaseTest { #region SetUp & TearDown /// <summary> /// SetUp /// </summary> [SetUp] public void Init() { InitScript( sqlMap.DataSource, ScriptDirectory + "account-init.sql" ); InitScript( sqlMap.DataSource, ScriptDirectory + "account-procedure.sql", false ); } /// <summary> /// TearDown /// </summary> [TearDown] public void Dispose() { /* ... */ } #endregion #region Test cache /// <summary> /// Test for JIRA 29 /// </summary> [Test] public void TestJIRA28() { Account account = sqlMap.QueryForObject("GetNoAccountWithCache",-99) as Account; Assert.IsNull(account); } /// <summary> /// Test Cache query /// </summary> [Test] public void TestQueryWithCache() { IList list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); int firstId = HashCodeProvider.GetIdentityHashCode(list); //System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(list); list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); //Console.WriteLine(sqlMap.GetDataCacheStats()); int secondId = HashCodeProvider.GetIdentityHashCode(list); //System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(list); Assert.AreEqual(firstId, secondId); Account account = (Account) list[1]; account.EmailAddress = "[email protected]"; sqlMap.Update("UpdateAccountViaInlineParameters", account); list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); int thirdId = HashCodeProvider.GetIdentityHashCode(list); Assert.IsTrue(firstId != thirdId); //Console.WriteLine(sqlMap.GetDataCacheStats()); } /// <summary> /// Test flush Cache /// </summary> [Test] public void TestFlushDataCache() { IList list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); int firstId = HashCodeProvider.GetIdentityHashCode(list); list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); int secondId = HashCodeProvider.GetIdentityHashCode(list); Assert.AreEqual(firstId, secondId); sqlMap.FlushCaches(); list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); int thirdId = HashCodeProvider.GetIdentityHashCode(list); Assert.IsTrue(firstId != thirdId); } /// <summary> /// Test MappedStatement Query With Threaded Cache /// </summary> [Test] public void TestMappedStatementQueryWithThreadedCache() { Hashtable results1 = new Hashtable(); Hashtable results2 = new Hashtable(); TestCacheThread.StartThread(sqlMap, results1, "GetCachedAccountsViaResultMap"); int firstId = (int) results1["id"]; TestCacheThread.StartThread(sqlMap, results2, "GetCachedAccountsViaResultMap"); int secondId = (int) results2["id"]; Assert.AreEqual(firstId, secondId); IList list = (IList) results1["list"]; Account account = (Account) list[1]; account.EmailAddress = "[email protected]"; sqlMap.Update("UpdateAccountViaInlineParameters", account); list = sqlMap.QueryForList("GetCachedAccountsViaResultMap", null); int thirdId = HashCodeProvider.GetIdentityHashCode(list); Assert.IsTrue(firstId != thirdId); } /// <summary> /// Test Cache Null Object /// </summary> [Test] public void TestCacheNullObject() { CacheModel cache = GetCacheModel(); cache["testKey"] = null; object returnedObject = cache["testKey"]; Assert.AreEqual(CacheModel.NULL_OBJECT, returnedObject); Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(CacheModel.NULL_OBJECT), HashCodeProvider.GetIdentityHashCode(returnedObject)); Assert.AreEqual(1, cache.HitRatio); } /// <summary> /// Test CacheHit /// </summary> [Test] public void TestCacheHit() { CacheModel cache = GetCacheModel(); string value = "testValue"; cache["testKey"] = value; object returnedObject = cache["testKey"]; Assert.AreEqual(value, returnedObject); Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(value), HashCodeProvider.GetIdentityHashCode(returnedObject)); Assert.AreEqual(1, cache.HitRatio); } /// <summary> /// Test CacheMiss /// </summary> [Test] public void TestCacheMiss() { CacheModel cache = GetCacheModel(); string value = "testValue"; cache["testKey"] = value; object returnedObject = cache["wrongKey"]; Assert.IsTrue(!value.Equals(returnedObject)); Assert.IsNull(returnedObject) ; Assert.AreEqual(0, cache.HitRatio); } /// <summary> /// Test CacheHitMiss /// </summary> [Test] public void TestCacheHitMiss() { CacheModel cache = GetCacheModel(); string value = "testValue"; cache["testKey"] = value; object returnedObject = cache["testKey"]; Assert.AreEqual(value, returnedObject); Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(value), HashCodeProvider.GetIdentityHashCode(returnedObject)); returnedObject = cache["wrongKey"]; Assert.IsTrue(!value.Equals(returnedObject)); Assert.IsNull(returnedObject) ; Assert.AreEqual(0.5, cache.HitRatio); } private CacheModel GetCacheModel() { CacheModel cache = new CacheModel(); cache.FlushInterval = new FlushInterval(); cache.FlushInterval.Minutes = 5; cache.Implementation = "IBatisNet.DataMapper.Configuration.Cache.Lru.LruCacheController, IBatisNet.DataMapper"; cache.Initialize(); return cache; } #endregion private class TestCacheThread { private SqlMapper _sqlMap = null; private Hashtable _results = null; private string _statementName = string.Empty; public TestCacheThread(SqlMapper sqlMap, Hashtable results, string statementName) { _sqlMap = sqlMap; _results = results; _statementName = statementName; } public void Run() { try { IMappedStatement statement = _sqlMap.GetMappedStatement( _statementName ); IDalSession session = new SqlMapSession(sqlMap.DataSource); session.OpenConnection(); IList list = statement.ExecuteQueryForList(session, null); //int firstId = HashCodeProvider.GetIdentityHashCode(list); list = statement.ExecuteQueryForList(session, null); int secondId = HashCodeProvider.GetIdentityHashCode(list); _results.Add("id", secondId ); _results.Add("list", list); session.CloseConnection(); } catch (Exception e) { throw e; } } public static void StartThread(SqlMapper sqlMap, Hashtable results, string statementName) { TestCacheThread tct = new TestCacheThread(sqlMap, results, statementName); Thread thread = new Thread( new ThreadStart(tct.Run) ); thread.Start(); try { thread.Join(); } catch (Exception e) { throw e; } } } } }
using Microsoft.Xna.Framework.Graphics; using System.Runtime.InteropServices; using System; namespace CocosSharp { #region Structs #if IOS [StructLayout(LayoutKind.Sequential, Pack=1)] #endif internal struct CCV3F_T2F : IVertexType { internal CCVertex3F Vertices; // 12 bytes internal CCTex2F TexCoords; // 8 byts internal static readonly VertexDeclaration VertexDeclaration; VertexDeclaration IVertexType.VertexDeclaration { get { return VertexDeclaration; } } static CCV3F_T2F() { var elements = new[] { new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement(12, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0) }; VertexDeclaration = new VertexDeclaration(elements); } } #endregion Structs // CCGrid3D is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z public class CCGrid3D : CCGridBase { bool dirty; CCIndexBuffer<ushort> indexBuffer; CCVertexBuffer<CCV3F_T2F> vertexBuffer; #region Properties protected ushort[] Indices { get; private set; } protected CCVertex3F[] OriginalVertices { get; private set; } internal CCV3F_T2F[] Vertices { get; private set; } #endregion Properties #region Constructors public CCGrid3D(CCGridSize gridSize, CCTexture2D texture, bool flipped=false) : base(gridSize, texture, flipped) { } #endregion Constructors #region Cleaning up protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { Indices = null; OriginalVertices = null; Vertices = null; indexBuffer = null; vertexBuffer = null; } } #endregion #region Vertex Indexers public CCVertex3F this[CCGridSize pos] { get { return this[pos.X, pos.Y]; } set { this[pos.X, pos.Y] = value; } } public CCVertex3F this[int x, int y] { get { return Vertices[x * (GridSize.Y + 1) + y].Vertices; } set { Vertices[x * (GridSize.Y + 1) + y].Vertices = value; dirty = true; } } // returns the original (non-transformed) vertex at a given position public CCVertex3F OriginalVertex(CCGridSize pos) { return OriginalVertices[pos.X * (GridSize.Y + 1) + pos.Y]; } // returns the original (non-transformed) vertex at a given position public CCVertex3F OriginalVertex(int x, int y) { return OriginalVertices[x * (GridSize.Y + 1) + y]; } #endregion Vertex Indexers public override void Blit() { if (dirty) { vertexBuffer.UpdateBuffer(); } base.Blit(); CCDrawManager drawManager = Scene.Window.DrawManager; bool save = drawManager.VertexColorEnabled; drawManager.VertexColorEnabled = false; drawManager.DrawBuffer(vertexBuffer, indexBuffer, 0, Indices.Length / 3); drawManager.VertexColorEnabled = save; } public override void Reuse() { if (ReuseGrid > 0) { for (int i = 0, count = (GridSize.X + 1) * (GridSize.Y + 1); i < count; i++) { OriginalVertices[i] = Vertices[i].Vertices; } --ReuseGrid; } } public override void CalculateVertexPoints() { float width = Texture.PixelsWide; float height = Texture.PixelsHigh; float imageH = Texture.ContentSizeInPixels.Height; int numOfPoints = (GridSize.X + 1) * (GridSize.Y + 1); vertexBuffer = new CCVertexBuffer<CCV3F_T2F>(numOfPoints, CCBufferUsage.WriteOnly); vertexBuffer.Count = numOfPoints; indexBuffer = new CCIndexBuffer<ushort>(GridSize.X * GridSize.Y * 6, BufferUsage.WriteOnly); indexBuffer.Count = GridSize.X * GridSize.Y * 6; Vertices = vertexBuffer.Data.Elements; Indices = indexBuffer.Data.Elements; OriginalVertices = new CCVertex3F[numOfPoints]; CCV3F_T2F[] vertArray = Vertices; ushort[] idxArray = Indices; var l1 = new int[4]; var l2 = new CCVertex3F[4]; var tex1 = new int[4]; var tex2 = new CCPoint[4]; //int idx = -1; for (int x = 0; x < GridSize.X; ++x) { for (int y = 0; y < GridSize.Y; ++y) { float x1 = x * Step.X; float x2 = x1 + Step.X; float y1 = y * Step.Y; float y2 = y1 + Step.Y; var a = (short) (x * (GridSize.Y + 1) + y); var b = (short) ((x + 1) * (GridSize.Y + 1) + y); var c = (short) ((x + 1) * (GridSize.Y + 1) + (y + 1)); var d = (short) (x * (GridSize.Y + 1) + (y + 1)); int idx = ((y * GridSize.X) + x) * 6; idxArray[idx + 0] = (ushort) a; idxArray[idx + 1] = (ushort) b; idxArray[idx + 2] = (ushort) d; idxArray[idx + 3] = (ushort) b; idxArray[idx + 4] = (ushort) c; idxArray[idx + 5] = (ushort) d; //var tempidx = new short[6] {a, d, b, b, d, c}; //Array.Copy(tempidx, 0, idxArray, 6 * idx, tempidx.Length); l1[0] = a; l1[1] = b; l1[2] = c; l1[3] = d; //var e = new Vector3(x1, y1, 0); //var f = new Vector3(x2, y1, 0); //var g = new Vector3(x2, y2, 0); //var h = new Vector3(x1, y2, 0); l2[0] = new CCVertex3F(x1, y1, 0); l2[1] = new CCVertex3F(x2, y1, 0); l2[2] = new CCVertex3F(x2, y2, 0); l2[3] = new CCVertex3F(x1, y2, 0); tex1[0] = a; tex1[1] = b; tex1[2] = c; tex1[3] = d; tex2[0] = new CCPoint(x1, y1); tex2[1] = new CCPoint(x2, y1); tex2[2] = new CCPoint(x2, y2); tex2[3] = new CCPoint(x1, y2); for (int i = 0; i < 4; ++i) { vertArray[l1[i]].Vertices = l2[i]; vertArray[tex1[i]].TexCoords.U = tex2[i].X / width; if (TextureFlipped) { vertArray[tex1[i]].TexCoords.V = tex2[i].Y / height; } else { vertArray[tex1[i]].TexCoords.V = (imageH - tex2[i].Y) / height; } } } } int n = (GridSize.X + 1) * (GridSize.Y + 1); for (int i = 0; i < n; i++) { OriginalVertices[i] = Vertices[i].Vertices; } indexBuffer.UpdateBuffer(); dirty = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ---------------------------------------------------------------------------------- // Interop library code // // Marshalling helpers used by MCG // // NOTE: // These source code are being published to InternalAPIs and consumed by RH builds // Use PublishInteropAPI.bat to keep the InternalAPI copies in sync // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Threading; using System.Text; using System.Runtime; using System.Runtime.CompilerServices; using Internal.NativeFormat; #if !CORECLR using Internal.Runtime.Augments; #endif #if RHTESTCL using OutputClass = System.Console; #else using OutputClass = System.Diagnostics.Debug; #endif namespace System.Runtime.InteropServices { /// <summary> /// Expose functionality from System.Private.CoreLib and forwards calls to InteropExtensions in System.Private.CoreLib /// </summary> [CLSCompliant(false)] public static partial class McgMarshal { public static void SaveLastWin32Error() { PInvokeMarshal.SaveLastWin32Error(); } public static void ClearLastWin32Error() { PInvokeMarshal.ClearLastWin32Error(); } public static bool GuidEquals(ref Guid left, ref Guid right) { return InteropExtensions.GuidEquals(ref left, ref right); } public static bool ComparerEquals<T>(T left, T right) { return InteropExtensions.ComparerEquals<T>(left, right); } public static T CreateClass<T>() where T : class { return InteropExtensions.UncheckedCast<T>(InteropExtensions.RuntimeNewObject(typeof(T).TypeHandle)); } public static bool IsEnum(object obj) { #if RHTESTCL return false; #else return InteropExtensions.IsEnum(obj.GetTypeHandle()); #endif } public static bool IsCOMObject(Type type) { #if RHTESTCL return false; #else return type.GetTypeInfo().IsSubclassOf(typeof(__ComObject)); #endif } public static T FastCast<T>(object value) where T : class { // We have an assert here, to verify that a "real" cast would have succeeded. // However, casting on weakly-typed RCWs modifies their state, by doing a QI and caching // the result. This often makes things work which otherwise wouldn't work (especially variance). Debug.Assert(value == null || value is T); return InteropExtensions.UncheckedCast<T>(value); } /// <summary> /// Converts a managed DateTime to native OLE datetime /// Used by MCG marshalling code /// </summary> public static double ToNativeOleDate(DateTime dateTime) { return InteropExtensions.ToNativeOleDate(dateTime); } /// <summary> /// Converts native OLE datetime to managed DateTime /// Used by MCG marshalling code /// </summary> public static DateTime FromNativeOleDate(double nativeOleDate) { return InteropExtensions.FromNativeOleDate(nativeOleDate); } /// <summary> /// Used in Marshalling code /// Call safeHandle.InitializeHandle to set the internal _handle field /// </summary> public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle) { InteropExtensions.InitializeHandle(safeHandle, win32Handle); } /// <summary> /// Check if obj's type is the same as represented by normalized handle /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static bool IsOfType(object obj, RuntimeTypeHandle handle) { return obj.IsOfType(handle); } #if ENABLE_MIN_WINRT public static unsafe void SetExceptionErrorCode(Exception exception, int errorCode) { InteropExtensions.SetExceptionErrorCode(exception, errorCode); } /// <summary> /// Used in Marshalling code /// Gets the handle of the CriticalHandle /// </summary> public static IntPtr GetHandle(CriticalHandle criticalHandle) { return InteropExtensions.GetCriticalHandle(criticalHandle); } /// <summary> /// Used in Marshalling code /// Sets the handle of the CriticalHandle /// </summary> public static void SetHandle(CriticalHandle criticalHandle, IntPtr handle) { InteropExtensions.SetCriticalHandle(criticalHandle, handle); } #endif } /// <summary> /// McgMarshal helpers exposed to be used by MCG /// </summary> public static partial class McgMarshal { #region Type marshalling public static Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind) { #if ENABLE_WINRT return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind); #else throw new NotSupportedException("TypeNameToType"); #endif } internal static Type TypeNameToType(string nativeTypeName, int nativeTypeKind) { #if ENABLE_WINRT return McgTypeHelpers.TypeNameToType(nativeTypeName, nativeTypeKind, checkTypeKind: false); #else throw new NotSupportedException("TypeNameToType"); #endif } public static unsafe void TypeToTypeName( Type type, out HSTRING nativeTypeName, out int nativeTypeKind) { #if ENABLE_WINRT McgTypeHelpers.TypeToTypeName(type, out nativeTypeName, out nativeTypeKind); #else throw new NotSupportedException("TypeToTypeName"); #endif } /// <summary> /// Fetch type name /// </summary> /// <param name="typeHandle">type</param> /// <returns>type name</returns> internal static string TypeToTypeName(RuntimeTypeHandle typeHandle, out int nativeTypeKind) { #if ENABLE_WINRT TypeKind typekind; string typeName; McgTypeHelpers.TypeToTypeName(typeHandle, out typeName, out typekind); nativeTypeKind = (int)typekind; return typeName; #else throw new NotSupportedException("TypeToTypeName"); #endif } #endregion #region String marshalling [CLSCompliant(false)] public static unsafe void StringBuilderToUnicodeString(System.Text.StringBuilder stringBuilder, ushort* destination) { PInvokeMarshal.StringBuilderToUnicodeString(stringBuilder, destination); } [CLSCompliant(false)] public static unsafe void UnicodeStringToStringBuilder(ushort* newBuffer, System.Text.StringBuilder stringBuilder) { PInvokeMarshal.UnicodeStringToStringBuilder(newBuffer, stringBuilder); } #if !RHTESTCL [CLSCompliant(false)] public static unsafe void StringBuilderToAnsiString(System.Text.StringBuilder stringBuilder, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.StringBuilderToAnsiString(stringBuilder, pNative, bestFit, throwOnUnmappableChar); } [CLSCompliant(false)] public static unsafe void AnsiStringToStringBuilder(byte* newBuffer, System.Text.StringBuilder stringBuilder) { PInvokeMarshal.AnsiStringToStringBuilder(newBuffer, stringBuilder); } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> [CLSCompliant(false)] public static unsafe string AnsiStringToString(byte* pchBuffer) { return PInvokeMarshal.AnsiStringToString(pchBuffer); } /// <summary> /// Convert UNICODE string to ANSI string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> [CLSCompliant(false)] public static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert UNICODE wide char array to ANSI ByVal byte array. /// </summary> /// <remarks> /// * This version works with array instead string, it means that there will be NO NULL to terminate the array. /// * The buffer to store the byte array must be allocated by the caller and must fit managedArray.Length. /// </remarks> /// <param name="managedArray">UNICODE wide char array</param> /// <param name="pNative">Allocated buffer where the ansi characters must be placed. Could NOT be null. Buffer size must fit char[].Length.</param> [CLSCompliant(false)] public static unsafe void ByValWideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, int expectedCharCount, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.ByValWideCharArrayToAnsiCharArray(managedArray, pNative, expectedCharCount, bestFit, throwOnUnmappableChar); } [CLSCompliant(false)] public static unsafe void ByValAnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { PInvokeMarshal.ByValAnsiCharArrayToWideCharArray(pNative, managedArray); } [CLSCompliant(false)] public static unsafe void WideCharArrayToAnsiCharArray(char[] managedArray, byte* pNative, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.WideCharArrayToAnsiCharArray(managedArray, pNative, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert ANSI ByVal byte array to UNICODE wide char array, best fit /// </summary> /// <remarks> /// * This version works with array instead to string, it means that the len must be provided and there will be NO NULL to /// terminate the array. /// * The buffer to the UNICODE wide char array must be allocated by the caller. /// </remarks> /// <param name="pNative">Pointer to the ANSI byte array. Could NOT be null.</param> /// <param name="lenInBytes">Maximum buffer size.</param> /// <param name="managedArray">Wide char array that has already been allocated.</param> [CLSCompliant(false)] public static unsafe void AnsiCharArrayToWideCharArray(byte* pNative, char[] managedArray) { PInvokeMarshal.AnsiCharArrayToWideCharArray(pNative, managedArray); } /// <summary> /// Convert a single UNICODE wide char to a single ANSI byte. /// </summary> /// <param name="managedArray">single UNICODE wide char value</param> public static unsafe byte WideCharToAnsiChar(char managedValue, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.WideCharToAnsiChar(managedValue, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert a single ANSI byte value to a single UNICODE wide char value, best fit. /// </summary> /// <param name="nativeValue">Single ANSI byte value.</param> public static unsafe char AnsiCharToWideChar(byte nativeValue) { return PInvokeMarshal.AnsiCharToWideChar(nativeValue); } /// <summary> /// Convert UNICODE string to ANSI ByVal string. /// </summary> /// <remarks>This version is more efficient than StringToHGlobalAnsi in Interop\System\Runtime\InteropServices\Marshal.cs in that /// it could allocate single byte per character, instead of SystemMaxDBCSCharSize per char, and it can skip calling WideCharToMultiByte for ASCII string</remarks> /// <param name="str">Unicode string.</param> /// <param name="pNative"> Allocated buffer where the ansi string must be placed. Could NOT be null. Buffer size must fit str.Length.</param> [CLSCompliant(false)] public static unsafe void StringToByValAnsiString(string str, byte* pNative, int charCount, bool bestFit, bool throwOnUnmappableChar) { PInvokeMarshal.StringToByValAnsiString(str, pNative, charCount, bestFit, throwOnUnmappableChar); } /// <summary> /// Convert ANSI string to unicode string, with option to free native memory. Calls generated by MCG /// </summary> /// <remarks>Input assumed to be zero terminated. Generates String.Empty for zero length string. /// This version is more efficient than ConvertToUnicode in src\Interop\System\Runtime\InteropServices\Marshal.cs in that it can skip calling /// MultiByteToWideChar for ASCII string, and it does not need another char[] buffer</remarks> [CLSCompliant(false)] public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCount) { return PInvokeMarshal.ByValAnsiStringToString(pchBuffer, charCount); } #endif #if ENABLE_WINRT [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe HSTRING StringToHString(string sourceString) { if (sourceString == null) throw new ArgumentNullException(nameof(sourceString), SR.Null_HString); return StringToHStringInternal(sourceString); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static unsafe HSTRING StringToHStringForField(string sourceString) { #if !RHTESTCL if (sourceString == null) throw new MarshalDirectiveException(SR.BadMarshalField_Null_HString); #endif return StringToHStringInternal(sourceString); } private static unsafe HSTRING StringToHStringInternal(string sourceString) { HSTRING ret; int hr = StringToHStringNoNullCheck(sourceString, &ret); if (hr < 0) throw Marshal.GetExceptionForHR(hr); return ret; } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static unsafe int StringToHStringNoNullCheck(string sourceString, HSTRING* hstring) { fixed (char* pChars = sourceString) { int hr = ExternalInterop.WindowsCreateString(pChars, (uint)sourceString.Length, (void*)hstring); return hr; } } #endif //ENABLE_WINRT #endregion #region COM marshalling /// <summary> /// Explicit AddRef for RCWs /// You can't call IFoo.AddRef anymore as IFoo no longer derive from IUnknown /// You need to call McgMarshal.AddRef(); /// </summary> /// <remarks> /// Used by prefast MCG plugin (mcgimportpft) only /// </remarks> [CLSCompliant(false)] public static int AddRef(__ComObject obj) { return obj.AddRef(); } /// <summary> /// Explicit Release for RCWs /// You can't call IFoo.Release anymore as IFoo no longer derive from IUnknown /// You need to call McgMarshal.Release(); /// </summary> /// <remarks> /// Used by prefast MCG plugin (mcgimportpft) only /// </remarks> [CLSCompliant(false)] public static int Release(__ComObject obj) { return obj.Release(); } [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int ComAddRef(IntPtr pComItf) { return CalliIntrinsics.StdCall__AddRef(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnAddRef, pComItf); } [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe int ComRelease_StdCall(IntPtr pComItf) { return CalliIntrinsics.StdCall__Release(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnRelease, pComItf); } /// <summary> /// Inline version of ComRelease /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] //reduces MCG-generated code size public static unsafe int ComRelease(IntPtr pComItf) { IntPtr pRelease = ((__com_IUnknown*)(void*)pComItf)->pVtable->pfnRelease; // Check if the COM object is implemented by PN Interop code, for which we can call directly if (pRelease == AddrOfIntrinsics.AddrOf<AddrOfRelease>(__vtable_IUnknown.Release)) { return __interface_ccw.DirectRelease(pComItf); } // Normal slow path, do not inline return ComRelease_StdCall(pComItf); } [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe int ComSafeRelease(IntPtr pComItf) { if (pComItf != default(IntPtr)) { return ComRelease(pComItf); } return 0; } public static int FinalReleaseComObject(object o) { if (o == null) throw new ArgumentNullException(nameof(o)); __ComObject co = null; // Make sure the obj is an __ComObject. try { co = (__ComObject)o; } catch (InvalidCastException) { throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o)); } co.FinalReleaseSelf(); return 0; } /// <summary> /// Returns the cached WinRT factory RCW under the current context /// </summary> [CLSCompliant(false)] public static unsafe __ComObject GetActivationFactory(string className, RuntimeTypeHandle factoryIntf) { #if ENABLE_MIN_WINRT return FactoryCache.Get().GetActivationFactory(className, factoryIntf); #else throw new PlatformNotSupportedException("GetActivationFactory"); #endif } /// <summary> /// Used by CCW infrastructure code to return the target object from this pointer /// </summary> /// <returns>The target object pointed by this pointer</returns> public static object ThisPointerToTargetObject(IntPtr pUnk) { return ComCallableObject.GetTarget(pUnk); } [CLSCompliant(false)] public static object ComInterfaceToObject_NoUnboxing( IntPtr pComItf, RuntimeTypeHandle interfaceType) { return McgComHelpers.ComInterfaceToObjectInternal( pComItf, interfaceType, default(RuntimeTypeHandle), McgComHelpers.CreateComObjectFlags.SkipTypeResolutionAndUnboxing ); } /// <summary> /// Shared CCW Interface To Object /// </summary> /// <param name="pComItf"></param> /// <param name="interfaceType"></param> /// <param name="classTypeInSignature"></param> /// <returns></returns> [CLSCompliant(false)] public static object ComInterfaceToObject( System.IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature) { #if ENABLE_MIN_WINRT if (interfaceType.Equals(typeof(object).TypeHandle)) { return McgMarshal.IInspectableToObject(pComItf); } if (interfaceType.Equals(typeof(System.String).TypeHandle)) { return McgMarshal.HStringToString(pComItf); } if (interfaceType.IsComClass()) { RuntimeTypeHandle defaultInterface = interfaceType.GetDefaultInterface(); Debug.Assert(!defaultInterface.IsNull()); return ComInterfaceToObjectInternal(pComItf, defaultInterface, interfaceType); } #endif return ComInterfaceToObjectInternal( pComItf, interfaceType, classTypeInSignature ); } [CLSCompliant(false)] public static object ComInterfaceToObject( IntPtr pComItf, RuntimeTypeHandle interfaceType) { return ComInterfaceToObject(pComItf, interfaceType, default(RuntimeTypeHandle)); } private static object ComInterfaceToObjectInternal( IntPtr pComItf, RuntimeTypeHandle interfaceType, RuntimeTypeHandle classTypeInSignature) { object result = McgComHelpers.ComInterfaceToObjectInternal(pComItf, interfaceType, classTypeInSignature, McgComHelpers.CreateComObjectFlags.None); // // Make sure the type we returned is actually of the right type // NOTE: Don't pass null to IsInstanceOfClass as it'll return false // if (!classTypeInSignature.IsNull() && result != null) { if (!InteropExtensions.IsInstanceOfClass(result, classTypeInSignature)) throw new InvalidCastException(); } return result; } public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid) { int hr = 0; return ComQueryInterfaceNoThrow(pComItf, ref iid, out hr); } public static unsafe IntPtr ComQueryInterfaceNoThrow(IntPtr pComItf, ref Guid iid, out int hr) { IntPtr pComIUnk; hr = ComQueryInterfaceWithHR(pComItf, ref iid, out pComIUnk); return pComIUnk; } internal static unsafe int ComQueryInterfaceWithHR(IntPtr pComItf, ref Guid iid, out IntPtr ppv) { IntPtr pComIUnk; int hr; fixed (Guid* unsafe_iid = &iid) { hr = CalliIntrinsics.StdCall__QueryInterface(((__com_IUnknown*)(void*)pComItf)->pVtable-> pfnQueryInterface, pComItf, new IntPtr(unsafe_iid), new IntPtr(&pComIUnk)); } if (hr != 0) { ppv = default(IntPtr); } else { ppv = pComIUnk; } return hr; } /// <summary> /// Helper function to copy vTable to native heap on CoreCLR. /// </summary> /// <typeparam name="T">Vtbl type</typeparam> /// <param name="pVtbl">static v-table field , always a valid pointer</param> /// <param name="pNativeVtbl">Pointer to Vtable on native heap on CoreCLR , on N it's an alias for pVtbl</param> public static unsafe IntPtr GetCCWVTableCopy(void* pVtbl, ref IntPtr pNativeVtbl, int size) { if (pNativeVtbl == default(IntPtr)) { #if CORECLR // On CoreCLR copy vTable to native heap , on N VTable is frozen. IntPtr pv = Marshal.AllocHGlobal(size); int* pSrc = (int*)pVtbl; int* pDest = (int*)pv.ToPointer(); int pSize = sizeof(int); // this should never happen , if a CCW is discarded we never get here. Debug.Assert(size >= pSize); for (int i = 0; i < size; i += pSize) { *pDest++ = *pSrc++; } if (Interlocked.CompareExchange(ref pNativeVtbl, pv, default(IntPtr)) != default(IntPtr)) { // Another thread sneaked-in and updated pNativeVtbl , just use the update from other thread Marshal.FreeHGlobal(pv); } #else // .NET NATIVE // Wrap it in an IntPtr pNativeVtbl = (IntPtr)pVtbl; #endif // CORECLR } return pNativeVtbl; } [CLSCompliant(false)] public static IntPtr ObjectToComInterface( object obj, RuntimeTypeHandle typeHnd) { #if ENABLE_MIN_WINRT if (typeHnd.Equals(typeof(object).TypeHandle)) { return McgMarshal.ObjectToIInspectable(obj); } if (typeHnd.Equals(typeof(System.String).TypeHandle)) { return McgMarshal.StringToHString((string)obj).handle; } if (typeHnd.IsComClass()) { // This code path should be executed only for WinRT classes typeHnd = typeHnd.GetDefaultInterface(); Debug.Assert(!typeHnd.IsNull()); } #endif return McgComHelpers.ObjectToComInterfaceInternal( obj, typeHnd ); } public static IntPtr ObjectToIInspectable(Object obj) { #if ENABLE_MIN_WINRT return ObjectToComInterface(obj, InternalTypes.IInspectable); #else throw new PlatformNotSupportedException("ObjectToIInspectable"); #endif } // This is not a safe function to use for any funtion pointers that do not point // at a static function. This is due to the behavior of shared generics, // where instance function entry points may share the exact same address // but static functions are always represented in delegates with customized // stubs. private static bool DelegateTargetMethodEquals(Delegate del, IntPtr pfn) { RuntimeTypeHandle thDummy; return del.GetFunctionPointer(out thDummy) == pfn; } [MethodImpl(MethodImplOptions.NoInlining)] public static IntPtr DelegateToComInterface(Delegate del, RuntimeTypeHandle typeHnd) { if (del == null) return default(IntPtr); IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub(); object targetObj; // // If the delegate points to the forward stub for the native delegate, // then we want the RCW associated with the native interface. Otherwise, // this is a managed delegate, and we want the CCW associated with it. // if (DelegateTargetMethodEquals(del, stubFunctionAddr)) targetObj = del.Target; else targetObj = del; return McgMarshal.ObjectToComInterface(targetObj, typeHnd); } [MethodImpl(MethodImplOptions.NoInlining)] public static Delegate ComInterfaceToDelegate(IntPtr pComItf, RuntimeTypeHandle typeHnd) { if (pComItf == default(IntPtr)) return null; object obj = ComInterfaceToObject(pComItf, typeHnd, /* classIndexInSignature */ default(RuntimeTypeHandle)); // // If the object we got back was a managed delegate, then we're good. Otherwise, // the object is an RCW for a native delegate, so we need to wrap it with a managed // delegate that invokes the correct stub. // Delegate del = obj as Delegate; if (del == null) { Debug.Assert(obj is __ComObject); IntPtr stubFunctionAddr = typeHnd.GetDelegateInvokeStub(); del = InteropExtensions.CreateDelegate( typeHnd, stubFunctionAddr, obj, /*isStatic:*/ true, /*isVirtual:*/ false, /*isOpen:*/ false); } return del; } /// <summary> /// Marshal array of objects /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] unsafe public static void ObjectArrayToComInterfaceArray(uint len, System.IntPtr* dst, object[] src, RuntimeTypeHandle typeHnd) { for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd); } } /// <summary> /// Allocate native memory, and then marshal array of objects /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] unsafe public static System.IntPtr* ObjectArrayToComInterfaceArrayAlloc(object[] src, RuntimeTypeHandle typeHnd, out uint len) { System.IntPtr* dst = null; len = 0; if (src != null) { len = (uint)src.Length; dst = (System.IntPtr*)PInvokeMarshal.CoTaskMemAlloc((System.UIntPtr)(len * (sizeof(System.IntPtr)))); for (uint i = 0; i < len; i++) { dst[i] = McgMarshal.ObjectToComInterface(src[i], typeHnd); } } return dst; } /// <summary> /// Get outer IInspectable for managed object deriving from native scenario /// At this point the inner is not created yet - you need the outer first and pass it to the factory /// to create the inner /// </summary> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static IntPtr GetOuterIInspectableForManagedObject(__ComObject managedObject) { ComCallableObject ccw = null; try { // // Create the CCW over the RCW // Note that they are actually both the same object // Base class = inner // Derived class = outer // ccw = new ComCallableObject( managedObject, // The target object = managedObject managedObject // The inner RCW (as __ComObject) = managedObject ); // // Retrieve the outer IInspectable // Pass skipInterfaceCheck = true to avoid redundant checks // return ccw.GetComInterfaceForType_NoCheck(InternalTypes.IInspectable, ref Interop.COM.IID_IInspectable); } finally { // // Free the extra ref count initialized by __native_ccw.Init (to protect the CCW from being collected) // if (ccw != null) ccw.Release(); } } [CLSCompliant(false)] public static unsafe IntPtr ManagedObjectToComInterface(Object obj, RuntimeTypeHandle interfaceType) { return McgComHelpers.ManagedObjectToComInterface(obj, interfaceType); } public static unsafe object IInspectableToObject(IntPtr pComItf) { #if ENABLE_WINRT return ComInterfaceToObject(pComItf, InternalTypes.IInspectable); #else throw new PlatformNotSupportedException("IInspectableToObject"); #endif } public static unsafe IntPtr CoCreateInstanceEx(Guid clsid, string server) { #if ENABLE_WINRT Interop.COM.MULTI_QI results; IntPtr pResults = new IntPtr(&results); fixed (Guid* pIID = &Interop.COM.IID_IUnknown) { Guid* pClsid = &clsid; results.pIID = new IntPtr(pIID); results.pItf = IntPtr.Zero; results.hr = 0; int hr; // if server name is specified, do remote server activation if (!String.IsNullOrEmpty(server)) { Interop.COM.COSERVERINFO serverInfo; fixed (char* pName = server) { serverInfo.Name = new IntPtr(pName); IntPtr pServerInfo = new IntPtr(&serverInfo); hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_REMOTE_SERVER, pServerInfo, 1, pResults); } } else { hr = ExternalInterop.CoCreateInstanceFromApp(pClsid, IntPtr.Zero, (int)Interop.COM.CLSCTX.CLSCTX_SERVER, IntPtr.Zero, 1, pResults); } if (hr < 0) { throw McgMarshal.GetExceptionForHR(hr, /*isWinRTScenario = */ false); } if (results.hr < 0) { throw McgMarshal.GetExceptionForHR(results.hr, /* isWinRTScenario = */ false); } return results.pItf; } #else throw new PlatformNotSupportedException("CoCreateInstanceEx"); #endif } public static unsafe IntPtr CoCreateInstanceEx(Guid clsid) { return CoCreateInstanceEx(clsid, string.Empty); } #endregion #region Testing /// <summary> /// Internal-only method to allow testing of apartment teardown code /// </summary> public static void ReleaseRCWsInCurrentApartment() { ContextEntry.RemoveCurrentContext(); } /// <summary> /// Used by detecting leaks /// Used in prefast MCG only /// </summary> public static int GetTotalComObjectCount() { return ComObjectCache.s_comObjectMap.Count; } /// <summary> /// Used by detecting and dumping leaks /// Used in prefast MCG only /// </summary> public static IEnumerable<__ComObject> GetAllComObjects() { List<__ComObject> list = new List<__ComObject>(); for (int i = 0; i < ComObjectCache.s_comObjectMap.GetMaxCount(); ++i) { IntPtr pHandle = default(IntPtr); if (ComObjectCache.s_comObjectMap.GetValue(i, ref pHandle) && (pHandle != default(IntPtr))) { GCHandle handle = GCHandle.FromIntPtr(pHandle); list.Add(InteropExtensions.UncheckedCast<__ComObject>(handle.Target)); } } return list; } #endregion /// <summary> /// This method returns HR for the exception being thrown. /// 1. On Windows8+, WinRT scenarios we do the following. /// a. Check whether the exception has any IRestrictedErrorInfo associated with it. /// If so, it means that this exception was actually caused by a native exception in which case we do simply use the same /// message and stacktrace. /// b. If not, this is actually a managed exception and in this case we RoOriginateLanguageException with the msg, hresult and the IErrorInfo /// associated with the managed exception. This helps us to retrieve the same exception in case it comes back to native. /// 2. On win8 and for classic COM scenarios. /// a. We create IErrorInfo for the given Exception object and SetErrorInfo with the given IErrorInfo. /// </summary> /// <param name="ex"></param> [MethodImpl(MethodImplOptions.NoInlining)] public static int GetHRForExceptionWinRT(Exception ex) { #if ENABLE_WINRT return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, true); #else // TODO : ExceptionHelpers should be platform specific , move it to // seperate source files return 0; //return Marshal.GetHRForException(ex); #endif } [MethodImpl(MethodImplOptions.NoInlining)] public static int GetHRForException(Exception ex) { #if ENABLE_WINRT return ExceptionHelpers.GetHRForExceptionWithErrorPropogationNoThrow(ex, false); #else return ex.HResult; #endif } [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowOnExternalCallFailed(int hr, System.RuntimeTypeHandle typeHnd) { bool isWinRTScenario #if ENABLE_WINRT = typeHnd.IsSupportIInspectable(); #else = false; #endif throw McgMarshal.GetExceptionForHR(hr, isWinRTScenario); } /// <summary> /// This method returns a new Exception object given the HR value. /// </summary> /// <param name="hr"></param> /// <param name="isWinRTScenario"></param> public static Exception GetExceptionForHR(int hr, bool isWinRTScenario) { #if ENABLE_WINRT return ExceptionHelpers.GetExceptionForHRInternalNoThrow(hr, isWinRTScenario, !isWinRTScenario); #elif CORECLR return Marshal.GetExceptionForHR(hr); #else return new COMException(hr.ToString(), hr); #endif } #region Shared templates #if ENABLE_MIN_WINRT public static void CleanupNative<T>(IntPtr pObject) { if (typeof(T) == typeof(string)) { global::System.Runtime.InteropServices.McgMarshal.FreeHString(pObject); } else { global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(pObject); } } #endif #endregion #if ENABLE_MIN_WINRT [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe IntPtr ActivateInstance(string typeName) { __ComObject target = McgMarshal.GetActivationFactory( typeName, InternalTypes.IActivationFactoryInternal ); IntPtr pIActivationFactoryInternalItf = target.QueryInterface_NoAddRef_Internal( InternalTypes.IActivationFactoryInternal, /* cacheOnly= */ false, /* throwOnQueryInterfaceFailure= */ true ); __com_IActivationFactoryInternal* pIActivationFactoryInternal = (__com_IActivationFactoryInternal*)pIActivationFactoryInternalItf; IntPtr pResult = default(IntPtr); int hr = CalliIntrinsics.StdCall<int>( pIActivationFactoryInternal->pVtable->pfnActivateInstance, pIActivationFactoryInternal, &pResult ); GC.KeepAlive(target); if (hr < 0) { throw McgMarshal.GetExceptionForHR(hr, /* isWinRTScenario = */ true); } return pResult; } #endif [MethodImpl(MethodImplOptions.NoInlining)] public static IntPtr GetInterface( __ComObject obj, RuntimeTypeHandle typeHnd) { return obj.QueryInterface_NoAddRef_Internal( typeHnd); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType, RuntimeTypeHandle existingType) { return obj.GetDynamicAdapter(requestedType, existingType); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static object GetDynamicAdapter(__ComObject obj, RuntimeTypeHandle requestedType) { return obj.GetDynamicAdapter(requestedType, default(RuntimeTypeHandle)); } #region "PInvoke Delegate" public static IntPtr GetStubForPInvokeDelegate(RuntimeTypeHandle delegateType, Delegate dele) { #if CORECLR throw new NotSupportedException(); #else return PInvokeMarshal.GetStubForPInvokeDelegate(dele); #endif } /// <summary> /// Retrieve the corresponding P/invoke instance from the stub /// </summary> public static Delegate GetPInvokeDelegateForStub(IntPtr pStub, RuntimeTypeHandle delegateType) { #if CORECLR if (pStub == IntPtr.Zero) return null; McgPInvokeDelegateData pInvokeDelegateData; if (!McgModuleManager.GetPInvokeDelegateData(delegateType, out pInvokeDelegateData)) { return null; } return CalliIntrinsics.Call__Delegate( pInvokeDelegateData.ForwardDelegateCreationStub, pStub ); #else return PInvokeMarshal.GetPInvokeDelegateForStub(pStub, delegateType); #endif } /// <summary> /// Retrieves the function pointer for the current open static delegate that is being called /// </summary> public static IntPtr GetCurrentCalleeOpenStaticDelegateFunctionPointer() { #if RHTESTCL || CORECLR || CORERT throw new NotSupportedException(); #else return PInvokeMarshal.GetCurrentCalleeOpenStaticDelegateFunctionPointer(); #endif } /// <summary> /// Retrieves the current delegate that is being called /// </summary> public static T GetCurrentCalleeDelegate<T>() where T : class // constraint can't be System.Delegate { #if RHTESTCL || CORECLR || CORERT throw new NotSupportedException(); #else return PInvokeMarshal.GetCurrentCalleeDelegate<T>(); #endif } #endregion } /// <summary> /// McgMarshal helpers exposed to be used by MCG /// </summary> public static partial class McgMarshal { public static object UnboxIfBoxed(object target) { return UnboxIfBoxed(target, null); } public static object UnboxIfBoxed(object target, string className) { // // If it is a managed wrapper, unbox it // object unboxedObj = McgComHelpers.UnboxManagedWrapperIfBoxed(target); if (unboxedObj != target) return unboxedObj; if (className == null) className = System.Runtime.InteropServices.McgComHelpers.GetRuntimeClassName(target); if (!String.IsNullOrEmpty(className)) { IntPtr unboxingStub; if (McgModuleManager.TryGetUnboxingStub(className, out unboxingStub)) { object ret = CalliIntrinsics.Call<object>(unboxingStub, target); if (ret != null) return ret; } #if ENABLE_WINRT else if(McgModuleManager.UseDynamicInterop) { BoxingInterfaceKind boxingInterfaceKind; RuntimeTypeHandle[] genericTypeArgument; if (DynamicInteropBoxingHelpers.TryGetBoxingArgumentTypeHandleFromString(className, out boxingInterfaceKind, out genericTypeArgument)) { Debug.Assert(target is __ComObject); return DynamicInteropBoxingHelpers.Unboxing(boxingInterfaceKind, genericTypeArgument, target); } } #endif } return null; } internal static object BoxIfBoxable(object target) { return BoxIfBoxable(target, default(RuntimeTypeHandle)); } /// <summary> /// Given a boxed value type, return a wrapper supports the IReference interface /// </summary> /// <param name="typeHandleOverride"> /// You might want to specify how to box this. For example, any object[] derived array could /// potentially boxed as object[] if everything else fails /// </param> internal static object BoxIfBoxable(object target, RuntimeTypeHandle typeHandleOverride) { RuntimeTypeHandle expectedTypeHandle = typeHandleOverride; if (expectedTypeHandle.Equals(default(RuntimeTypeHandle))) expectedTypeHandle = target.GetTypeHandle(); RuntimeTypeHandle boxingWrapperType; IntPtr boxingStub; int boxingPropertyType; if (McgModuleManager.TryGetBoxingWrapperType(expectedTypeHandle, target, out boxingWrapperType, out boxingPropertyType, out boxingStub)) { if (!boxingWrapperType.IsInvalid()) { // // IReference<T> / IReferenceArray<T> / IKeyValuePair<K, V> // All these scenarios require a managed wrapper // // Allocate the object object refImplType = InteropExtensions.RuntimeNewObject(boxingWrapperType); if (boxingPropertyType >= 0) { Debug.Assert(refImplType is BoxedValue); BoxedValue boxed = InteropExtensions.UncheckedCast<BoxedValue>(refImplType); // Call ReferenceImpl<T>.Initialize(obj, type); boxed.Initialize(target, boxingPropertyType); } else { Debug.Assert(refImplType is BoxedKeyValuePair); BoxedKeyValuePair boxed = InteropExtensions.UncheckedCast<BoxedKeyValuePair>(refImplType); // IKeyValuePair<,>, call CLRIKeyValuePairImpl<K,V>.Initialize(object obj); // IKeyValuePair<,>[], call CLRIKeyValuePairArrayImpl<K,V>.Initialize(object obj); refImplType = boxed.Initialize(target); } return refImplType; } else { // // General boxing for projected types, such as System.Uri // return CalliIntrinsics.Call<object>(boxingStub, target); } } return null; } } }
// // ContentType.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2012 Jeffrey Stedfast // // 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.Text; using MimeKit.Utils; namespace MimeKit { /// <summary> /// A class representing a Content-Type header value. /// </summary> public sealed class ContentType { ParameterList parameters; string type, subtype; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <param name="mediaType">Media type.</param> /// <param name="mediaSubtype">Media subtype.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mediaType"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="mediaSubtype"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="mediaType"/> is empty or contains invalid characters.</para> /// <para>-or-</para> /// <para><paramref name="mediaSubtype"/> is empty or contains invalid characters.</para> /// </exception> public ContentType (string mediaType, string mediaSubtype) { if (mediaType == null) throw new ArgumentNullException ("mediaType"); if (mediaType.Length == 0) throw new ArgumentException ("The type is not allowed to be empty.", "mediaType"); for (int i = 0; i < mediaType.Length; i++) { if (mediaType[i] >= 127 || !IsAtom ((byte) mediaType[i])) throw new ArgumentException ("Illegal characters in type.", "mediaType"); } if (mediaSubtype == null) throw new ArgumentNullException ("mediaSubtype"); if (mediaSubtype.Length == 0) throw new ArgumentException ("The subtype is not allowed to be empty.", "mediaSubtype"); for (int i = 0; i < mediaSubtype.Length; i++) { if (mediaSubtype[i] >= 127 || !IsToken ((byte) mediaSubtype[i])) throw new ArgumentException ("Illegal characters in subtype.", "mediaSubtype"); } Parameters = new ParameterList (); subtype = mediaSubtype; type = mediaType; } static bool IsToken (byte c) { return c.IsToken (); } static bool IsAtom (byte c) { return c.IsAtom (); } /// <summary> /// Gets or sets the type of the media. /// </summary> /// <value>The type of the media.</value> /// <exception cref="System.ArgumentNullException"> /// <paramref name="value"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="value"/> is empty or contains invalid characters. /// </exception> public string MediaType { get { return type; } set { if (value == null) throw new ArgumentNullException ("value"); if (value.Length == 0) throw new ArgumentException ("MediaType is not allowed to be empty.", "value"); for (int i = 0; i < value.Length; i++) { if (value[i] > 127 || !IsAtom ((byte) value[i])) throw new ArgumentException ("Illegal characters in media type.", "value"); } if (type == value) return; type = value; OnChanged (); } } /// <summary> /// Gets or sets the media subtype. /// </summary> /// <value>The media subtype.</value> /// <exception cref="System.ArgumentNullException"> /// <paramref name="value"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="value"/> is empty or contains invalid characters. /// </exception> public string MediaSubtype { get { return subtype; } set { if (value == null) throw new ArgumentNullException ("value"); if (value.Length == 0) throw new ArgumentException ("MediaSubtype is not allowed to be empty.", "value"); for (int i = 0; i < value.Length; i++) { if (value[i] > 127 || !IsToken ((byte) value[i])) throw new ArgumentException ("Illegal characters in media subtype.", "value"); } if (subtype == value) return; subtype = value; OnChanged (); } } /// <summary> /// Gets the parameters. /// </summary> /// <value>The parameters.</value> public ParameterList Parameters { get { return parameters; } private set { if (parameters != null) parameters.Changed -= OnParametersChanged; value.Changed += OnParametersChanged; parameters = value; } } /// <summary> /// Gets or sets the boundary parameter. /// </summary> /// <value>The boundary.</value> public string Boundary { get { return Parameters["boundary"]; } set { if (value != null) Parameters["boundary"] = value; else Parameters.Remove ("boundary"); } } /// <summary> /// Gets or sets the charset parameter. /// </summary> /// <value>The charset.</value> public string Charset { get { return Parameters["charset"]; } set { if (value != null) Parameters["charset"] = value; else Parameters.Remove ("charset"); } } /// <summary> /// Gets or sets the name parameter. /// </summary> /// <value>The name.</value> public string Name { get { return Parameters["name"]; } set { if (value != null) Parameters["name"] = value; else Parameters.Remove ("name"); } } /// <summary> /// Checks if the this instance of <see cref="MimeKit.ContentType"/> matches /// the specified mediaType and mediaSubtype. /// /// Note: If the specified mediaType or mediaSubtype are "*", they match anything. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="mediaSubtype">The media subtype.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mediaType"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="mediaSubtype"/> is <c>null</c>.</para> /// </exception> public bool Matches (string mediaType, string mediaSubtype) { if (mediaType == null) throw new ArgumentNullException ("mediaType"); if (mediaSubtype == null) throw new ArgumentNullException ("mediaSubtype"); var stricase = StringComparer.OrdinalIgnoreCase; if (mediaType == "*" || stricase.Compare (mediaType, type) == 0) return mediaSubtype == "*" || stricase.Compare (mediaSubtype, subtype) == 0; return false; } internal string Encode (FormatOptions options, Encoding charset) { int lineLength = "Content-Type: ".Length; var value = new StringBuilder (" "); value.Append (MediaType); value.Append ('/'); value.Append (MediaSubtype); Parameters.Encode (options, value, ref lineLength, charset); value.Append (options.NewLine); return value.ToString (); } /// <summary> /// Serializes the <see cref="MimeKit.ContentType"/> to a string, /// optionally encoding the parameters. /// </summary> /// <returns>The serialized string.</returns> /// <param name="charset">The charset to be used when encoding the parameter values.</param> /// <param name="encode">If set to <c>true</c>, the parameter values will be encoded.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="charset"/> is <c>null</c>. /// </exception> public string ToString (Encoding charset, bool encode) { if (charset == null) throw new ArgumentNullException ("charset"); var value = new StringBuilder ("Content-Type: "); value.Append (MediaType); value.Append ('/'); value.Append (MediaSubtype); if (encode) { int lineLength = value.Length; Parameters.Encode (FormatOptions.Default, value, ref lineLength, charset); } else { value.Append (Parameters.ToString ()); } return value.ToString (); } /// <summary> /// Returns a <see cref="System.String"/> that represents the current /// <see cref="MimeKit.ContentType"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current /// <see cref="MimeKit.ContentType"/>.</returns> public override string ToString () { return ToString (Encoding.UTF8, false); } internal event EventHandler Changed; void OnParametersChanged (object sender, EventArgs e) { OnChanged (); } void OnChanged () { if (Changed != null) Changed (this, EventArgs.Empty); } static bool SkipType (byte[] text, ref int index, int endIndex) { int startIndex = index; while (index < endIndex && text[index].IsAtom () && text[index] != (byte) '/') index++; return index > startIndex; } internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ContentType contentType) { string type, subtype; int start; contentType = null; if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError)) return false; start = index; if (!SkipType (text, ref index, endIndex)) { if (throwOnError) throw new ParseException (string.Format ("Invalid type token at position {0}", start), start, index); return false; } type = Encoding.ASCII.GetString (text, start, index - start); if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError)) return false; if (index >= endIndex || text[index] != (byte) '/') { if (throwOnError) throw new ParseException (string.Format ("Expected '/' at position {0}", index), index, index); return false; } // skip over the '/' index++; if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError)) return false; start = index; if (!ParseUtils.SkipToken (text, ref index, endIndex)) { if (throwOnError) throw new ParseException (string.Format ("Invalid atom token at position {0}", start), start, index); return false; } subtype = Encoding.ASCII.GetString (text, start, index - start); if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError)) return false; contentType = new ContentType (type, subtype); if (index >= endIndex) return true; if (text[index] != (byte) ';') { if (throwOnError) throw new ParseException (string.Format ("Expected ';' at position {0}", index), index, index); return false; } index++; if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError)) return false; if (index >= endIndex) return true; ParameterList parameters; if (!ParameterList.TryParse (options, text, ref index, endIndex, throwOnError, out parameters)) return false; contentType.Parameters = parameters; return true; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out ContentType type) { if (options == null) throw new ArgumentNullException ("options"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (startIndex < 0 || startIndex >= buffer.Length) throw new ArgumentOutOfRangeException ("startIndex"); if (length < 0 || startIndex + length >= buffer.Length) throw new ArgumentOutOfRangeException ("length"); int index = startIndex; return TryParse (options, buffer, ref index, startIndex + length, false, out type); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, int length, out ContentType type) { return TryParse (ParserOptions.Default, buffer, startIndex, length, out type); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out ContentType type) { if (options == null) throw new ArgumentNullException ("options"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (startIndex < 0 || startIndex >= buffer.Length) throw new ArgumentOutOfRangeException ("startIndex"); int index = startIndex; return TryParse (options, buffer, ref index, buffer.Length, false, out type); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, out ContentType type) { return TryParse (ParserOptions.Default, buffer, startIndex, out type); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options.</param> /// <param name="buffer">The input buffer.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, out ContentType type) { if (options == null) throw new ArgumentNullException ("options"); if (buffer == null) throw new ArgumentNullException ("buffer"); int index = 0; return TryParse (options, buffer, ref index, buffer.Length, false, out type); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> public static bool TryParse (byte[] buffer, out ContentType type) { return TryParse (ParserOptions.Default, buffer, out type); } /// <summary> /// Tries to parse the given text into a new <see cref="MimeKit.ContentType"/> instance. /// </summary> /// <returns><c>true</c>, if the content type was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="text">The text to parse.</param> /// <param name="type">The parsed content type.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (string text, out ContentType type) { if (text == null) throw new ArgumentNullException ("text"); var buffer = Encoding.UTF8.GetBytes (text); int index = 0; return TryParse (ParserOptions.Default, buffer, ref index, buffer.Length, false, out type); } /// <summary> /// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="options">The parser options.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The start index of the buffer.</param> /// <param name="length">The length of the buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="buffer"/> could not be parsed. /// </exception> public static ContentType Parse (ParserOptions options, byte[] buffer, int startIndex, int length) { if (options == null) throw new ArgumentNullException ("options"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (startIndex < 0 || startIndex > buffer.Length) throw new ArgumentOutOfRangeException ("startIndex"); if (length < 0 || startIndex + length > buffer.Length) throw new ArgumentOutOfRangeException ("length"); int index = startIndex; ContentType type; TryParse (options, buffer, ref index, startIndex + length, true, out type); return type; } /// <summary> /// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The start index of the buffer.</param> /// <param name="length">The length of the buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="buffer"/> could not be parsed. /// </exception> public static ContentType Parse (byte[] buffer, int startIndex, int length) { return Parse (ParserOptions.Default, buffer, startIndex, length); } /// <summary> /// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="options">The parser options.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The start index of the buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="buffer"/> could not be parsed. /// </exception> public static ContentType Parse (ParserOptions options, byte[] buffer, int startIndex) { if (options == null) throw new ArgumentNullException ("options"); if (buffer == null) throw new ArgumentNullException ("buffer"); if (startIndex < 0 || startIndex > buffer.Length) throw new ArgumentOutOfRangeException ("startIndex"); int index = startIndex; ContentType type; TryParse (options, buffer, ref index, buffer.Length, true, out type); return type; } /// <summary> /// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The start index of the buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="buffer"/> could not be parsed. /// </exception> public static ContentType Parse (byte[] buffer, int startIndex) { return Parse (ParserOptions.Default, buffer, startIndex); } /// <summary> /// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="options">The parser options.</param> /// <param name="buffer">The input buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="buffer"/> could not be parsed. /// </exception> public static ContentType Parse (ParserOptions options, byte[] buffer) { if (options == null) throw new ArgumentNullException ("options"); if (buffer == null) throw new ArgumentNullException ("buffer"); ContentType type; int index = 0; TryParse (options, buffer, ref index, buffer.Length, true, out type); return type; } /// <summary> /// Parse the specified input buffer into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="buffer">The input buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="buffer"/> could not be parsed. /// </exception> public static ContentType Parse (byte[] buffer) { return Parse (ParserOptions.Default, buffer); } /// <summary> /// Parse the specified text into a new instance of the <see cref="MimeKit.ContentType"/> class. /// </summary> /// <returns>The parsed <see cref="MimeKit.ContentType"/>.</returns> /// <param name="text">The text.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> /// <exception cref="MimeKit.ParseException"> /// The <paramref name="text"/> could not be parsed. /// </exception> public static ContentType Parse (string text) { if (text == null) throw new ArgumentNullException ("text"); var buffer = Encoding.UTF8.GetBytes (text); ContentType type; int index = 0; TryParse (ParserOptions.Default, buffer, ref index, buffer.Length, true, out type); return type; } } }
namespace AngleSharp.Core.Tests.Html { using AngleSharp.Html.Dom; using NUnit.Framework; /// <summary> /// Tests generated according to the W3C-Test.org page: /// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-patternMismatch.html /// </summary> [TestFixture] public class ValidityPatternMismatchTests { [Test] public void TestPatternmismatchInputText1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputText2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = ""; Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputText3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]{1}"); element.Value = "A"; Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputText4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = "ABC"; Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputText5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[a-z]{3,}"); element.Value = "ABCD"; Assert.AreEqual("text", element.Type); Assert.AreEqual(true, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputSearch1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputSearch2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = ""; Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputSearch3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]{1}"); element.Value = "A"; Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputSearch4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = "ABC"; Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputSearch5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[a-z]{3,}"); element.Value = "ABCD"; Assert.AreEqual("search", element.Type); Assert.AreEqual(true, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputTel1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputTel2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = ""; Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputTel3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]{1}"); element.Value = "A"; Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputTel4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = "ABC"; Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputTel5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[a-z]{3,}"); element.Value = "ABCD"; Assert.AreEqual("tel", element.Type); Assert.AreEqual(true, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputUrl1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputUrl2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = ""; Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputUrl3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]{1}"); element.Value = "A"; Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputUrl4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = "ABC"; Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputUrl5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[a-z]{3,}"); element.Value = "ABCD"; Assert.AreEqual("url", element.Type); Assert.AreEqual(true, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputEmail1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputEmail2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = ""; Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputEmail3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]{1}"); element.Value = "A"; Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputEmail4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = "ABC"; Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputEmail5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[a-z]{3,}"); element.Value = "ABCD"; Assert.AreEqual("email", element.Type); Assert.AreEqual(true, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputPassword1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputPassword2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = ""; Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputPassword3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]{1}"); element.Value = "A"; Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputPassword4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]+"); element.Value = "ABC"; Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.Validity.IsPatternMismatch); } [Test] public void TestPatternmismatchInputPassword5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[a-z]{3,}"); element.Value = "ABCD"; Assert.AreEqual("password", element.Type); Assert.AreEqual(true, element.Validity.IsPatternMismatch); } } }
namespace Nine.Animations { using System; using System.ComponentModel; /// <summary> /// Defines the behavior of the last ending keyframe. /// </summary> /// <remarks> /// The difference between these behaviors won't be noticeable /// unless the KeyframeAnimation is really slow. /// </remarks> public enum KeyframeEnding { /// <summary> /// The animation will wait for the last frame to finish /// but won't blend the last frame with the first frame. /// Specify this when your animation isn't looped. /// </summary> Clamp, /// <summary> /// The animation will blend between the last keyframe /// and the first keyframe. /// Specify this when the animation is looped and the first /// frame doesn't equal to the last frame. /// </summary> Wrap, /// <summary> /// The animation will stop immediately when it reaches /// the last frame, so the ending frame has no duration. /// Specify this when the animation is looped and the first /// frame is identical to the last frame. /// </summary> Discard, } /// <summary> /// Event args used by KeyframeAnimation events. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public class KeyframeEventArgs : EventArgs { /// <summary> /// Gets the index of the frame. /// </summary> public int Frame { get; internal set; } } /// <summary> /// Basic class for all keyframed animations. /// </summary> public abstract class KeyframeAnimation : TimelineAnimation { /// <summary> /// Gets or sets the inclusive frame at which this <see cref="KeyframeAnimation"/> should begin. /// </summary> public int? BeginFrame { get { return beginFrame; } set { beginFrame = value; UpdateBeginEndTime(); } } private int? beginFrame; /// <summary> /// Gets or sets the exclusive frame at which this <see cref="KeyframeAnimation"/> should end. /// </summary> public int? EndFrame { get { return endFrame; } set { endFrame = value; UpdateBeginEndTime(); } } private int? endFrame; /// <summary> /// Gets or sets number of frames to be played per second. /// The default value is 24. /// </summary> public double FramesPerSecond { get { return framesPerSecond; } set { framesPerSecond = value; UpdateDuration(); } } private double framesPerSecond = 24; /// <summary> /// Gets the current frame index been played. /// </summary> public int CurrentFrame { get; private set; } /// <summary> /// Gets the total number of frames. /// </summary> public int TotalFrames { get { return totalFrames; } protected set { totalFrames = value; UpdateDuration(); UpdateBeginEndTime(); } } private int totalFrames; /// <summary> /// Gets or sets the behavior of the ending keyframe. /// The default value is KeyframeEnding.Clamp. /// </summary> public KeyframeEnding Ending { get { return ending; } set { ending = value; UpdateDuration(); } } private KeyframeEnding ending = KeyframeEnding.Clamp; /// <summary> /// Occurs when this animation has just entered the current frame. /// </summary> public event EventHandler<KeyframeEventArgs> EnterFrame; /// <summary> /// Occurs when this animation is about to exit the current frame. /// </summary> public event EventHandler<KeyframeEventArgs> ExitFrame; /// <summary> /// Creates a new instance of <c>KeyframeAnimation</c>. /// </summary> protected KeyframeAnimation() { CurrentFrame = 0; Repeat = double.MaxValue; } /// <summary> /// Gets the index of the frame at the specified position. /// </summary> private void GetFrame(TimeSpan position, out int frame, out double percentage) { if (position < TimeSpan.Zero || position > TotalDuration) throw new ArgumentOutOfRangeException("position"); frame = (int)(position.TotalSeconds * framesPerSecond); percentage = (double)(position.TotalSeconds * framesPerSecond - frame); if (frame >= totalFrames) { frame = 0; percentage = 0; } } /// <summary> /// Positions the animation at the specified frame. /// </summary> public void Seek(int frame) { if (frame < 0 || frame >= TotalFrames) throw new ArgumentOutOfRangeException("frame"); Seek(TimeSpan.FromSeconds(1.0 * frame / FramesPerSecond)); } // Use to prevent from allways calling exit frame before enter frame // even for the first frame. bool hasPlayed = false; /// <summary> /// Stops the animation. /// </summary> protected override void OnStopped() { hasPlayed = false; base.OnStopped(); } /// <summary> /// Plays the animation from start. /// </summary> protected override void OnStarted() { // Override BeginTime & EndTime with BeginFrame & EndFrame. UpdateBeginEndTime(); hasPlayed = false; base.OnStarted(); } /// <summary> /// Called when the animation is completed. /// </summary> protected override void OnCompleted() { hasPlayed = false; base.OnCompleted(); } /// <summary> /// When overridden, positions the animation at the specified location. /// </summary> protected override sealed void OnSeek(TimeSpan position, TimeSpan previousPosition) { double percentage; int current, previous; GetFrame(previousPosition, out previous, out percentage); GetFrame(position, out current, out percentage); if (Ending == KeyframeEnding.Wrap) OnSeek(current, (current + 1) % TotalFrames, percentage); else if (Ending == KeyframeEnding.Clamp || Ending == KeyframeEnding.Discard) OnSeek(current, Math.Min(current + 1, TotalFrames - 1), percentage); if (current != previous || !hasPlayed) { if (hasPlayed) { OnExitFrame(previous); } hasPlayed = true; CurrentFrame = current; OnEnterFrame(current); } } private void UpdateDuration() { int realFrames = Math.Max(0, (ending == KeyframeEnding.Discard ? (totalFrames - 1) : totalFrames)); TotalDuration = TimeSpan.FromSeconds(realFrames / FramesPerSecond); } private void UpdateBeginEndTime() { if (beginFrame.HasValue && totalFrames > 0) BeginTime = TimeSpan.FromSeconds(beginFrame.Value * TotalDuration.TotalSeconds / totalFrames); else BeginTime = null; if (endFrame.HasValue && totalFrames > 0) EndTime = TimeSpan.FromSeconds(endFrame.Value * TotalDuration.TotalSeconds / totalFrames); else EndTime = null; } /// <summary> /// Moves the animation at the position between start frame and end frame /// specified by percentage. /// </summary> protected virtual void OnSeek(int startFrame, int endFrame, double percentage) { } /// <summary> /// Called when the specified frame is entered. /// </summary> protected virtual void OnEnterFrame(int frame) { if (EnterFrame != null) EnterFrame(this, new KeyframeEventArgs() { Frame = frame }); } /// <summary> /// Called when the specified frame is exit. /// </summary> protected virtual void OnExitFrame(int frame) { if (ExitFrame != null) ExitFrame(this, new KeyframeEventArgs() { Frame = frame }); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; using System.Reflection; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Services.MessagingService.MessagingModules.GridWideMessage { public class GridWideMessageModule : IService, IGridWideMessageModule { #region Declares protected IRegistryCore m_registry; #endregion #region IGridWideMessageModule Members public void KickUser(UUID avatarID, string message) { //Get required interfaces IAsyncMessagePostService messagePost = m_registry.RequestModuleInterface<IAsyncMessagePostService>(); ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); IClientCapsService client = capsService.GetClientCapsService(avatarID); if (client != null) { IRegionClientCapsService regionClient = client.GetRootCapsService(); if (regionClient != null) { //Send the message to the client messagePost.Post(regionClient.RegionHandle, BuildRequest("KickUserMessage", message, regionClient.AgentID.ToString())); IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>(); if (agentProcessor != null) agentProcessor.LogoutAgent(regionClient, true); MainConsole.Instance.Info("User will be kicked in less than 30 seconds."); return; } } MainConsole.Instance.Info("Could not find user to send message to."); } public void MessageUser(UUID avatarID, string message) { //Get required interfaces IAsyncMessagePostService messagePost = m_registry.RequestModuleInterface<IAsyncMessagePostService>(); ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); IClientCapsService client = capsService.GetClientCapsService(avatarID); if (client != null) { IRegionClientCapsService regionClient = client.GetRootCapsService(); if (regionClient != null) { //Send the message to the client messagePost.Post(regionClient.RegionHandle, BuildRequest("GridWideMessage", message, regionClient.AgentID.ToString())); MainConsole.Instance.Info("Message sent, will be delievered in the next 30 seconds to the user."); return; } } MainConsole.Instance.Info("Could not find user to send message to."); } public void SendAlert(string message) { //Get required interfaces IAsyncMessagePostService messagePost = m_registry.RequestModuleInterface<IAsyncMessagePostService>(); ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>(); List<IClientCapsService> clients = capsService.GetClientsCapsServices(); //Go through all clients, and send the message asyncly to all agents that are root foreach (IRegionClientCapsService regionClient in from client in clients from regionClient in client.GetCapsServices() where regionClient.RootAgent select regionClient) { MainConsole.Instance.Debug("[GridWideMessageModule]: Informed " + regionClient.ClientCaps.AccountInfo.Name); //Send the message to the client messagePost.Post(regionClient.RegionHandle, BuildRequest("GridWideMessage", message, regionClient.AgentID.ToString())); } MainConsole.Instance.Info("[GridWideMessageModule]: Sent alert, will be delievered across the grid in the next 3 minutes."); } #endregion #region IService Members public void Initialize(IConfigSource config, IRegistryCore registry) { } public void Start(IConfigSource config, IRegistryCore registry) { m_registry = registry; registry.RegisterModuleInterface<IGridWideMessageModule>(this); IConfig handlersConfig = config.Configs["Handlers"]; if (MainConsole.Instance != null && handlersConfig != null && handlersConfig.GetString("GridWideMessage", "") == "GridWideMessageModule") { MainConsole.Instance.Commands.AddCommand("grid send alert", "grid send alert <message>", "Sends a message to all users in the grid", SendGridAlert); MainConsole.Instance.Commands.AddCommand("grid send message", "grid send message <first> <last> <message>", "Sends a message to a user in the grid", SendGridMessage); MainConsole.Instance.Commands.AddCommand("grid kick user", "grid kick user <first> <last> <message>", "Kicks a user from the grid", KickUserMessage); } } public void FinishedStartup() { //Also look for incoming messages to display m_registry.RequestModuleInterface<IAsyncMessageRecievedService>().OnMessageReceived += OnMessageReceived; } #endregion #region Commands protected void SendGridAlert(string[] cmd) { //Combine the params and figure out the message string message = CombineParams(cmd, 3); SendAlert(message); } protected void SendGridMessage(string[] cmd) { //Combine the params and figure out the message string user = CombineParams(cmd, 3, 5); string message = CombineParams(cmd, 5); IUserAccountService userService = m_registry.RequestModuleInterface<IUserAccountService>(); UserAccount account = userService.GetUserAccount(UUID.Zero, user.Split(' ')[0], user.Split(' ')[1]); if (account == null) { MainConsole.Instance.Info("User does not exist."); return; } MessageUser(account.PrincipalID, message); } protected void KickUserMessage(string[] cmd) { //Combine the params and figure out the message string user = CombineParams(cmd, 3, 5); if (user.EndsWith(" ")) user = user.Remove(user.Length - 1); string message = CombineParams(cmd, 5); IUserAccountService userService = m_registry.RequestModuleInterface<IUserAccountService>(); UserAccount account = userService.GetUserAccount(UUID.Zero, user); if (account == null) { MainConsole.Instance.Info("User does not exist."); return; } KickUser(account.PrincipalID, message); } private string CombineParams(string[] commandParams, int pos) { string result = string.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } return result; } private string CombineParams(string[] commandParams, int pos, int end) { string result = string.Empty; for (int i = pos; i < commandParams.Length && i < end; i++) { result += commandParams[i] + " "; } return result; } private OSDMap BuildRequest(string name, string value, string user) { OSDMap map = new OSDMap(); map["Method"] = name; map["Value"] = value; map["User"] = user; return map; } #endregion #region Message Received protected OSDMap OnMessageReceived(OSDMap message) { if (message.ContainsKey("Method") && message["Method"] == "GridWideMessage") { //We got a message, now display it string user = message["User"].AsString(); string value = message["Value"].AsString(); //Get the Scene registry since IDialogModule is a region module, and isn't in the ISimulationBase registry SceneManager manager = m_registry.RequestModuleInterface<SceneManager>(); if (manager != null && manager.Scenes.Count > 0) { foreach (IScene scene in manager.Scenes) { IScenePresence sp = null; if (scene.TryGetScenePresence(UUID.Parse(user), out sp) && !sp.IsChildAgent) { IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>(); if (dialogModule != null) { //Send the message to the user now dialogModule.SendAlertToUser(UUID.Parse(user), value); } } } } } else if (message.ContainsKey("Method") && message["Method"] == "KickUserMessage") { //We got a message, now display it string user = message["User"].AsString(); string value = message["Value"].AsString(); //Get the Scene registry since IDialogModule is a region module, and isn't in the ISimulationBase registry SceneManager manager = m_registry.RequestModuleInterface<SceneManager>(); if (manager != null && manager.Scenes.Count > 0) { foreach (IScene scene in manager.Scenes) { IScenePresence sp = null; if (scene.TryGetScenePresence(UUID.Parse(user), out sp)) { sp.ControllingClient.Kick(value == "" ? "The Aurora Grid Manager kicked you out." : value); IEntityTransferModule transferModule = scene.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) transferModule.IncomingCloseAgent(scene, sp.UUID); } } } } return null; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using StructureMap.Configuration; using StructureMap.Configuration.DSL; using StructureMap.Construction; using StructureMap.Diagnostics; using StructureMap.Interceptors; using StructureMap.Pipeline; using StructureMap.Util; using StructureMap; namespace StructureMap.Graph { // TODO -- might eliminate the cache and use a dictionary directly // TODO -- go to reader writer locks /// <summary> /// Models the runtime configuration of a StructureMap Container /// </summary> [Serializable] public class PluginGraph : IPluginGraph, IDisposable { private readonly Cache<Type, PluginFamily> _families; private readonly IList<IFamilyPolicy> _policies = new List<IFamilyPolicy>(); private readonly InterceptorLibrary _interceptorLibrary = new InterceptorLibrary(); private readonly List<Registry> _registries = new List<Registry>(); private GraphLog _log = new GraphLog(); private readonly LifecycleObjectCache _singletonCache = new LifecycleObjectCache(); private readonly LightweightCache<string, PluginGraph> _profiles; private readonly SetterRules _setterRules; private readonly Cache<Type, IInstanceBuilder> _builders; public PluginGraph() { _profiles = new LightweightCache<string, PluginGraph>(name => new PluginGraph {ProfileName = name, Parent = this}); ProfileName = "DEFAULT"; _families = new Cache<Type, PluginFamily>(type => { return _policies.FirstValue(x => x.Build(type)) ?? new PluginFamily(type); }); _families.OnAddition = family => family.Owner = this; _setterRules = new SetterRules(); _builders = new Cache<Type, IInstanceBuilder>(type => { var plugin = new Plugin(type); _setterRules.Configure(plugin); return plugin.CreateBuilder(); }); } public IInstanceBuilder BuilderFor(Type pluggedType) { return _builders[pluggedType]; } public SetterRules SetterRules { get { return _setterRules; } } public PluginGraph Parent { get; set; } public PluginGraph(string profileName) : this() { ProfileName = profileName; } public string ProfileName { get; private set; } public LifecycleObjectCache SingletonCache { get { return _singletonCache; } } public static PluginGraph Empty() { return new PluginGraphBuilder().Build(); } public PluginGraph Profile(string name) { return _profiles[name]; } public IEnumerable<PluginGraph> Profiles { get { return _profiles; } } public void AddFamilyPolicy(IFamilyPolicy policy) { _policies.Add(policy); } public List<Registry> Registries { get { return _registries; } } public GraphLog Log { get { return _log; } set { _log = value; } } public Cache<Type, PluginFamily> Families { get { return _families; } } public InterceptorLibrary InterceptorLibrary { get { return _interceptorLibrary; } } /// <summary> /// Adds the concreteType as an Instance of the pluginType /// </summary> /// <param name = "pluginType"></param> /// <param name = "concreteType"></param> public virtual void AddType(Type pluginType, Type concreteType) { _families[pluginType].AddType(concreteType); } /// <summary> /// Adds the concreteType as an Instance of the pluginType with a name /// </summary> /// <param name = "pluginType"></param> /// <param name = "concreteType"></param> /// <param name = "name"></param> public virtual void AddType(Type pluginType, Type concreteType, string name) { _families[pluginType].AddType(concreteType, name); } /// <summary> /// Add configuration to a PluginGraph with the Registry DSL /// </summary> /// <param name = "action"></param> public void Configure(Action<Registry> action) { var registry = new Registry(); action(registry); registry.As<IPluginGraphConfiguration>().Configure(this); } public void ImportRegistry(Type type) { if (Registries.Any(x => x.GetType() == type)) return; var registry = (Registry) Activator.CreateInstance(type); registry.As<IPluginGraphConfiguration>().Configure(this); } public static PluginGraph BuildGraphFromAssembly(Assembly assembly) { var builder = new PluginGraphBuilder(); var scanner = new AssemblyScanner(); scanner.Assembly(assembly); builder.AddScanner(scanner); return builder.Build(); } public void AddFamily(PluginFamily family) { _families[family.PluginType] = family; } public void RemoveFamily(Type pluginType) { _families.Remove(pluginType); } public bool HasInstance(Type pluginType, string name) { if (!HasFamily(pluginType)) { return false; } return _families[pluginType].GetInstance(name) != null; } public bool HasFamily(Type pluginType) { if (_families.Has(pluginType)) return true; // TODO -- this needs better locking mechanics var newFamily = _policies.Where(x => x.AppliesToHasFamilyChecks).FirstValue(x => x.Build(pluginType)); if (newFamily != null) { _families[pluginType] = newFamily; return true; } return false; } public bool HasDefaultForPluginType(Type pluginType) { if (!HasFamily(pluginType)) { return false; } return Families[pluginType].GetDefaultInstance() != null; } public void EjectFamily(Type pluginType) { if (_families.Has(pluginType)) { var family = _families[pluginType]; family.SafeDispose(); _families.Remove(pluginType); } } public void EachInstance(Action<Type, Instance> action) { _families.Each(family => { family.Instances.Each(i => action(family.PluginType, i)); }); } public Instance FindInstance(Type pluginType, string name) { if (!HasFamily(pluginType)) return null; return _families[pluginType].GetInstance(name) ?? _families[pluginType].MissingInstance; } public IEnumerable<Instance> AllInstances(Type pluginType) { if (HasFamily(pluginType)) { return _families[pluginType].Instances; } else { return Enumerable.Empty<Instance>(); } } void IDisposable.Dispose() { _singletonCache.DisposeAndClear(); _profiles.Each(x => x.SafeDispose()); _profiles.Clear(); var containerFamily = _families[typeof (IContainer)]; _families.Remove(typeof(IContainer)); containerFamily.RemoveAll(); _families.Each(x => x.SafeDispose()); _families.ClearAll(); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation { /// <summary> /// Defines a PowerShell command / script object which can be used with /// <see cref="PowerShell"/> object. /// </summary> public sealed class PSCommand { #region Private Fields private PowerShell _owner; private CommandCollection _commands; private Command _currentCommand; #endregion #region Constructor /// <summary> /// Creates an empty PSCommand; a command or script must be added to this PSCommand before it can be executed. /// </summary> public PSCommand() { Initialize(null, false, null); } /// <summary> /// Internal copy constructor /// </summary> /// <param name="commandToClone"></param> internal PSCommand(PSCommand commandToClone) { _commands = new CommandCollection(); foreach (Command command in commandToClone.Commands) { Command clone = command.Clone(); // Attach the cloned Command to this instance. _commands.Add(clone); _currentCommand = clone; } } /// <summary> /// Creates a PSCommand from the specified command /// </summary> /// <param name="command">Command object to use</param> internal PSCommand(Command command) { _currentCommand = command; _commands = new CommandCollection(); _commands.Add(_currentCommand); } #endregion #region Command / Parameter Construction /// <summary> /// Add a command to construct a command pipeline. /// For example, to construct a command string "get-process | sort-object", /// <code> /// PSCommand command = new PSCommand("get-process").AddCommand("sort-object"); /// </code> /// </summary> /// <param name="command"> /// A string representing the command. /// </param> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> /// <returns> /// A PSCommand instance with <paramref name="cmdlet"/> added. /// </returns> /// <remarks> /// This method is not thread safe. /// </remarks> /// <exception cref="ArgumentNullException"> /// cmdlet is null. /// </exception> public PSCommand AddCommand(string command) { if (null == command) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand = new Command(command, false); _commands.Add(_currentCommand); return this; } /// <summary> /// Add a cmdlet to construct a command pipeline. /// For example, to construct a command string "get-process | sort-object", /// <code> /// PSCommand command = new PSCommand("get-process").AddCommand("sort-object"); /// </code> /// </summary> /// <param name="cmdlet"> /// A string representing cmdlet. /// </param> /// <param name="useLocalScope"> /// if true local scope is used to run the script command. /// </param> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> /// <returns> /// A PSCommand instance with <paramref name="cmdlet"/> added. /// </returns> /// <remarks> /// This method is not thread safe. /// </remarks> /// <exception cref="ArgumentNullException"> /// cmdlet is null. /// </exception> public PSCommand AddCommand(string cmdlet, bool useLocalScope) { if (null == cmdlet) { throw PSTraceSource.NewArgumentNullException("cmdlet"); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand = new Command(cmdlet, false, useLocalScope); _commands.Add(_currentCommand); return this; } /// <summary> /// Add a piece of script to construct a command pipeline. /// For example, to construct a command string "get-process | foreach { $_.Name }" /// <code> /// PSCommand command = new PSCommand("get-process"). /// AddCommand("foreach { $_.Name }", true); /// </code> /// </summary> /// <param name="script"> /// A string representing the script. /// </param> /// <returns> /// A PSCommand instance with <paramref name="command"/> added. /// </returns> /// <remarks> /// This method is not thread-safe. /// </remarks> /// <exception cref="ArgumentNullException"> /// command is null. /// </exception> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> public PSCommand AddScript(string script) { if (null == script) { throw PSTraceSource.NewArgumentNullException("script"); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand = new Command(script, true); _commands.Add(_currentCommand); return this; } /// <summary> /// Add a piece of script to construct a command pipeline. /// For example, to construct a command string "get-process | foreach { $_.Name }" /// <code> /// PSCommand command = new PSCommand("get-process"). /// AddCommand("foreach { $_.Name }", true); /// </code> /// </summary> /// <param name="script"> /// A string representing the script. /// </param> /// <param name="useLocalScope"> /// if true local scope is used to run the script command. /// </param> /// <returns> /// A PSCommand instance with <paramref name="command"/> added. /// </returns> /// <remarks> /// This method is not thread-safe. /// </remarks> /// <exception cref="ArgumentNullException"> /// command is null. /// </exception> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> public PSCommand AddScript(string script, bool useLocalScope) { if (null == script) { throw PSTraceSource.NewArgumentNullException("script"); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand = new Command(script, true, useLocalScope); _commands.Add(_currentCommand); return this; } /// <summary> /// Add a <see cref="Command"/> element to the current command /// pipeline. /// </summary> /// <param name="command"> /// Command to add. /// </param> /// <returns> /// A PSCommand instance with <paramref name="command"/> added. /// </returns> /// <remarks> /// This method is not thread-safe. /// </remarks> /// <exception cref="ArgumentNullException"> /// command is null. /// </exception> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> public PSCommand AddCommand(Command command) { if (null == command) { throw PSTraceSource.NewArgumentNullException("command"); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand = command; _commands.Add(_currentCommand); return this; } /// <summary> /// Add a parameter to the last added command. /// For example, to construct a command string "get-process | select-object -property name" /// <code> /// PSCommand command = new PSCommand("get-process"). /// AddCommand("select-object").AddParameter("property","name"); /// </code> /// </summary> /// <param name="parameterName"> /// Name of the parameter. /// </param> /// <param name="value"> /// Value for the parameter. /// </param> /// <returns> /// A PSCommand instance with <paramref name="parameterName"/> added /// to the parameter list of the last command. /// </returns> /// <remarks> /// This method is not thread safe. /// </remarks> /// <exception cref="ArgumentException"> /// Name is non null and name length is zero after trimming whitespace. /// </exception> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> public PSCommand AddParameter(string parameterName, object value) { if (null == _currentCommand) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand.Parameters.Add(parameterName, value); return this; } /// <summary> /// Adds a switch parameter to the last added command. /// For example, to construct a command string "get-process | sort-object -descending" /// <code> /// PSCommand command = new PSCommand("get-process"). /// AddCommand("sort-object").AddParameter("descending"); /// </code> /// </summary> /// <param name="parameterName"> /// Name of the parameter. /// </param> /// <returns> /// A PSCommand instance with <paramref name="parameterName"/> added /// to the parameter list of the last command. /// </returns> /// <remarks> /// This method is not thread safe. /// </remarks> /// <exception cref="ArgumentException"> /// Name is non null and name length is zero after trimming whitespace. /// </exception> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> public PSCommand AddParameter(string parameterName) { if (null == _currentCommand) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand.Parameters.Add(parameterName, true); return this; } /// <summary> /// Adds an argument to the last added command. /// For example, to construct a command string "get-process | select-object name" /// <code> /// PSCommand command = new PSCommand("get-process"). /// AddCommand("select-object").AddParameter("name"); /// </code> /// /// This will add the value "name" to the positional parameter list of "select-object" /// cmdlet. When the command is invoked, this value will get bound to positional parameter 0 /// of the "select-object" cmdlet which is "Property". /// </summary> /// <param name="value"> /// Value for the parameter. /// </param> /// <returns> /// A PSCommand instance parameter value <paramref name="value"/> added /// to the parameter list of the last command. /// </returns> /// <exception cref="InvalidPowerShellStateException"> /// Powershell instance cannot be changed in its /// current state. /// </exception> /// <remarks> /// This method is not thread safe. /// </remarks> public PSCommand AddArgument(object value) { if (null == _currentCommand) { throw PSTraceSource.NewInvalidOperationException(PSCommandStrings.ParameterRequiresCommand, new object[] { "PSCommand" }); } if (_owner != null) { _owner.AssertChangesAreAccepted(); } _currentCommand.Parameters.Add(null, value); return this; } /// <summary> /// Adds an additional statement for execution /// /// For example, /// <code> /// Runspace rs = RunspaceFactory.CreateRunspace(); /// PowerShell ps = PowerShell.Create(); /// /// ps.Runspace = rs; /// ps.AddCommand("Get-Process").AddArgument("idle"); /// ps.AddStatement().AddCommand("Get-Service").AddArgument("audiosrv"); /// ps.Invoke(); /// </code> /// </summary> /// <returns> /// A PowerShell instance with the items in <paramref name="parameters"/> added /// to the parameter list of the last command. /// </returns> public PSCommand AddStatement() { if (_commands.Count == 0) { return this; } _commands[_commands.Count - 1].IsEndOfStatement = true; return this; } #endregion #region Properties and Methods /// <summary> /// Gets the collection of commands from this PSCommand /// instance. /// </summary> public CommandCollection Commands { get { return _commands; } } /// <summary> /// The PowerShell instance this PSCommand is associated to, or null if it is an standalone command /// </summary> internal PowerShell Owner { get { return _owner; } set { _owner = value; } } /// <summary> /// Clears the command(s). /// </summary> public void Clear() { _commands.Clear(); _currentCommand = null; } /// <summary> /// Creates a shallow copy of the current PSCommand. /// </summary> /// <returns> /// A shallow copy of the current PSCommand /// </returns> public PSCommand Clone() { return new PSCommand(this); } #endregion #region Private Methods /// <summary> /// Initializes the instance. Called from the constructor. /// </summary> /// <param name="command"> /// Command to initialize the instance with. /// </param> /// <param name="isScript"> /// true if the <paramref name="command"/> is script, /// false otherwise. /// </param> /// <param name="useLocalScope"> /// if true local scope is used to run the script command. /// </param> /// <remarks> /// Caller should check the input. /// </remarks> /// <exception cref="ArgumentNullException"> /// command is null /// </exception> private void Initialize(string command, bool isScript, bool? useLocalScope) { _commands = new CommandCollection(); if (command != null) { _currentCommand = new Command(command, isScript, useLocalScope); _commands.Add(_currentCommand); } } #endregion } }
/** * $Id: IrcClient.cs 77 2004-09-19 13:31:53Z meebey $ * $URL: svn://svn.qnetp.net/smartirc/SmartIrc4net/tags/0.2.0/src/IrcClient.cs $ * $Rev: 77 $ * $Author: meebey $ * $Date: 2004-09-19 15:31:53 +0200 (Sun, 19 Sep 2004) $ * * Copyright (c) 2003-2004 Mirco 'meebey' Bauer <[email protected]> <http://www.meebey.net> * * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Collections.Specialized; using System.Text.RegularExpressions; using Meebey.SmartIrc4net.Delegates; namespace Meebey.SmartIrc4net { /// <summary> /// /// </summary> public class IrcClient: IrcCommands { private string _Nickname = ""; private string _Realname = ""; private string _Usermode = ""; private int _IUsermode = 0; private string _Username = ""; private string _Password = ""; private string _CtcpVersion; private bool _ChannelSyncing = false; private bool _AutoRejoin = false; private Array _ReplyCodes = Enum.GetValues(typeof(ReplyCode)); private StringCollection _JoinedChannels = new StringCollection(); private Hashtable _Channels = Hashtable.Synchronized(new Hashtable()); private Hashtable _IrcUsers = Hashtable.Synchronized(new Hashtable()); public event SimpleEventHandler OnRegistered; public event PingEventHandler OnPing; public event MessageEventHandler OnRawMessage; public event ErrorEventHandler OnError; public event JoinEventHandler OnJoin; public event NameReplyEventHandler OnNameReply; public event PartEventHandler OnPart; public event QuitEventHandler OnQuit; public event KickEventHandler OnKick; public event InviteEventHandler OnInvite; public event BanEventHandler OnBan; public event UnbanEventHandler OnUnban; public event OpEventHandler OnOp; public event DeopEventHandler OnDeop; public event VoiceEventHandler OnVoice; public event DevoiceEventHandler OnDevoice; public event WhoEventHandler OnWho; public event TopicEventHandler OnTopic; public event TopicChangeEventHandler OnTopicChange; public event NickChangeEventHandler OnNickChange; public event MessageEventHandler OnModeChange; public event MessageEventHandler OnUserModeChange; public event MessageEventHandler OnChannelModeChange; public event MessageEventHandler OnChannelMessage; public event ActionEventHandler OnChannelAction; public event MessageEventHandler OnChannelNotice; public event MessageEventHandler OnQueryMessage; public event ActionEventHandler OnQueryAction; public event MessageEventHandler OnQueryNotice; public event MessageEventHandler OnCtcpRequest; public event MessageEventHandler OnCtcpReply; /// <summary> /// /// </summary> /// <value> </value> public bool ChannelSyncing { get { return _ChannelSyncing; } set { #if LOG4NET if (value == true) { Logger.ChannelSyncing.Info("Channel syncing enabled"); } else { Logger.ChannelSyncing.Info("Channel syncing disabled"); } #endif _ChannelSyncing = value; } } /// <summary> /// /// </summary> /// <value> </value> public string CtcpVersion { get { return _CtcpVersion; } set { _CtcpVersion = value; } } /// <summary> /// /// </summary> /// <value> </value> public bool AutoRejoin { get { return _AutoRejoin; } set { #if LOG4NET if (value == true) { Logger.ChannelSyncing.Info("AutoRejoin enabled"); } else { Logger.ChannelSyncing.Info("AutoRejoin disabled"); } #endif _AutoRejoin = value; } } /// <summary> /// /// </summary> /// <value> </value> public string Nickname { get { return _Nickname; } } /// <summary> /// /// </summary> /// <value> </value> public string Realname { get { return _Realname; } } /// <summary> /// /// </summary> /// <value> </value> public string Username { get { return _Username; } } /// <summary> /// /// </summary> /// <value> </value> public string Usermode { get { return _Usermode; } } /// <summary> /// /// </summary> /// <value> </value> public int IUsermode { get { return _IUsermode; } } /// <summary> /// /// </summary> /// <value> </value> public string Password { get { return _Password; } } /// <summary> /// /// </summary> /// <value> </value> public string[] JoinedChannels { get { string[] result; result = new string[_JoinedChannels.Count]; _JoinedChannels.CopyTo(result, 0); return result; } } /// <summary> /// /// </summary> public IrcClient() { #if LOG4NET Logger.Main.Debug("IrcClient created"); #endif OnReadLine += new ReadLineEventHandler(_Worker); } ~IrcClient() { #if LOG4NET Logger.Main.Debug("IrcClient destroyed"); log4net.LogManager.Shutdown(); #endif } /// <summary> /// /// </summary> /// <param name="login"> </param> public override bool Reconnect(bool login) { if(base.Reconnect(true) == true) { if (login) { Login(Nickname, Realname, IUsermode, Username, Password); } #if LOG4NET Logger.Connection.Info("Rejoining channels..."); #endif foreach(string channel in _JoinedChannels) { Join(channel, Priority.High); } return true; } return false; } /// <summary> /// /// </summary> /// <param name="nick"> </param> /// <param name="usermode"> </param> /// <param name="username"> </param> /// <param name="password"> </param> public void Login(string nick, string realname, int usermode, string username, string password) { #if LOG4NET Logger.Connection.Info("logging in"); #endif _Nickname = nick.Replace(" ", ""); _Realname = realname; _IUsermode = usermode; if (username != String.Empty) { _Username = username.Replace(" ", ""); } else { _Username = Environment.UserName.Replace(" ", ""); } if (password != String.Empty) { _Password = password; Pass(Password, Priority.Critical); } Nick(Nickname, Priority.Critical); User(Username, IUsermode, Realname, Priority.Critical); } /// <summary> /// /// </summary> /// <param name="nick"> </param> /// <param name="realname"> </param> /// <param name="usermode"> </param> /// <param name="username"> </param> public void Login(string nick, string realname, int usermode, string username) { Login(nick, realname, usermode, username, ""); } public void Login(string nick, string realname, int usermode) { Login(nick, realname, usermode, "", ""); } public void Login(string nick, string realname) { Login(nick, realname, 0, "", ""); } public bool IsMe(string nickname) { return (Nickname == nickname); } public bool IsJoined(string channelname) { return IsJoined(channelname, Nickname); } public bool IsJoined(string channelname, string nickname) { if (channelname == null) { throw new System.ArgumentNullException("channelname"); } if (nickname == null) { throw new System.ArgumentNullException("nickname"); } Channel channel = GetChannel(channelname); if (channel != null && channel.UnsafeUsers != null && channel.UnsafeUsers.ContainsKey(nickname.ToLower())) { return true; } return false; } public IrcUser GetIrcUser(string nickname) { if (nickname == null) { throw new System.ArgumentNullException("nickname"); } return (IrcUser)_IrcUsers[nickname.ToLower()]; } public ChannelUser GetChannelUser(string channel, string nickname) { if (channel == null) { throw new System.ArgumentNullException("channel"); } if (nickname == null) { throw new System.ArgumentNullException("nickname"); } Channel ircchannel = GetChannel(channel); if (ircchannel != null) { return (ChannelUser)ircchannel.UnsafeUsers[nickname.ToLower()]; } else { return null; } } public Channel GetChannel(string channel) { if (channel == null) { throw new System.ArgumentNullException("channel"); } return (Channel)_Channels[channel.ToLower()]; } public string[] GetChannels() { string[] channels = new string[_Channels.Values.Count]; int i = 0; foreach (Channel channel in _Channels.Values) { channels[i++] = channel.Name; } return channels; } public Data MessageParser(string rawline) { Data ircdata; string line; string[] lineex; string[] rawlineex; string messagecode; string from; int exclamationpos; int atpos; int colonpos; rawlineex = rawline.Split(new Char[] {' '}); ircdata = new Data(); ircdata.Irc = this; ircdata.RawMessage = rawline; ircdata.RawMessageEx = rawlineex; if (rawline.Substring(0, 1) == ":") { line = rawline.Substring(1); } else { line = rawline; } lineex = line.Split(new char[] {' '}); // conform to RFC 2812 from = lineex[0]; messagecode = lineex[1]; exclamationpos = from.IndexOf("!"); atpos = from.IndexOf("@"); colonpos = line.IndexOf(" :"); if (colonpos != -1) { // we want the exact position of ":" not beginning from the space colonpos += 1; } if (exclamationpos != -1) { ircdata.Nick = from.Substring(0, exclamationpos); } if ((atpos != -1) && (exclamationpos != -1)) { ircdata.Ident = from.Substring(exclamationpos+1, (atpos - exclamationpos)-1); } if (atpos != -1) { ircdata.Host = from.Substring(atpos+1); } try { ircdata.ReplyCode = (ReplyCode)int.Parse(messagecode); } catch (FormatException) { ircdata.ReplyCode = ReplyCode.NULL; } ircdata.Type = _GetMessageType(rawline); ircdata.From = from; if (colonpos != -1) { ircdata.Message = line.Substring(colonpos+1); ircdata.MessageEx = ircdata.Message.Split(new char[] {' '}); } switch(ircdata.Type) { case ReceiveType.Join: case ReceiveType.Kick: case ReceiveType.Part: case ReceiveType.TopicChange: case ReceiveType.ChannelModeChange: case ReceiveType.ChannelMessage: case ReceiveType.ChannelAction: case ReceiveType.ChannelNotice: ircdata.Channel = lineex[2]; break; case ReceiveType.Who: case ReceiveType.Topic: case ReceiveType.BanList: case ReceiveType.ChannelMode: ircdata.Channel = lineex[3]; break; case ReceiveType.Name: ircdata.Channel = lineex[4]; break; } if (ircdata.Channel != null) { if (ircdata.Channel.Substring(0, 1) == ":") { ircdata.Channel = ircdata.Channel.Substring(1); } } #if LOG4NET Logger.MessageParser.Debug("ircdata "+ "nick: '"+ircdata.Nick+"' "+ "ident: '"+ircdata.Ident+"' "+ "host: '"+ircdata.Host+"' "+ "type: '"+ircdata.Type.ToString()+"' "+ "from: '"+ircdata.From+"' "+ "channel: '"+ircdata.Channel+"' "+ "message: '"+ircdata.Message+"' " ); #endif return ircdata; } private void _Worker(string rawline) { // lets see if we have events or internal messagehandler for it _HandleEvents(MessageParser(rawline)); } private ReceiveType _GetMessageType(string rawline) { Match found; found = new Regex("^:[^ ]+? ([0-9]{3}) .+$").Match(rawline); if (found.Success) { string code = found.Groups[1].Value; ReplyCode replycode = (ReplyCode)int.Parse(code); // check if this replycode is known in the RFC if (Array.IndexOf(_ReplyCodes, replycode) == -1) { #if LOG4NET Logger.MessageTypes.Warn("This IRC server ("+Address+") doesn't conform to the RFC 2812! ignoring unrecongzied replycode '"+replycode+"'"); #endif return ReceiveType.Unknown; } switch (replycode) { case ReplyCode.RPL_WELCOME: case ReplyCode.RPL_YOURHOST: case ReplyCode.RPL_CREATED: case ReplyCode.RPL_MYINFO: case ReplyCode.RPL_BOUNCE: return ReceiveType.Login; case ReplyCode.RPL_LUSERCLIENT: case ReplyCode.RPL_LUSEROP: case ReplyCode.RPL_LUSERUNKNOWN: case ReplyCode.RPL_LUSERME: case ReplyCode.RPL_LUSERCHANNELS: return ReceiveType.Info; case ReplyCode.RPL_MOTDSTART: case ReplyCode.RPL_MOTD: case ReplyCode.RPL_ENDOFMOTD: return ReceiveType.Motd; case ReplyCode.RPL_NAMREPLY: case ReplyCode.RPL_ENDOFNAMES: return ReceiveType.Name; case ReplyCode.RPL_WHOREPLY: case ReplyCode.RPL_ENDOFWHO: return ReceiveType.Who; case ReplyCode.RPL_LISTSTART: case ReplyCode.RPL_LIST: case ReplyCode.RPL_LISTEND: return ReceiveType.List; case ReplyCode.RPL_BANLIST: case ReplyCode.RPL_ENDOFBANLIST: return ReceiveType.BanList; case ReplyCode.RPL_TOPIC: case ReplyCode.RPL_NOTOPIC: return ReceiveType.Topic; case ReplyCode.RPL_WHOISUSER: case ReplyCode.RPL_WHOISSERVER: case ReplyCode.RPL_WHOISOPERATOR: case ReplyCode.RPL_WHOISIDLE: case ReplyCode.RPL_ENDOFWHOIS: case ReplyCode.RPL_WHOISCHANNELS: return ReceiveType.Whois; case ReplyCode.RPL_WHOWASUSER: case ReplyCode.RPL_ENDOFWHOWAS: return ReceiveType.Whowas; case ReplyCode.RPL_UMODEIS: return ReceiveType.UserMode; case ReplyCode.RPL_CHANNELMODEIS: return ReceiveType.ChannelMode; case ReplyCode.ERR_NICKNAMEINUSE: case ReplyCode.ERR_NOTREGISTERED: return ReceiveType.Error; default: #if LOG4NET Logger.MessageTypes.Warn("replycode unknown ("+code+"): \""+rawline+"\""); #endif return ReceiveType.Unknown; } } found = new Regex("^PING :.*").Match(rawline); if (found.Success) { return ReceiveType.Unknown; } found = new Regex("^ERROR :.*").Match(rawline); if (found.Success) { return ReceiveType.Error; } found = new Regex("^:.*? PRIVMSG (.).* :"+(char)1+"ACTION .*"+(char)1+"$").Match(rawline); if (found.Success) { switch (found.Groups[1].Value) { case "#": case "!": case "&": case "+": return ReceiveType.ChannelAction; default: return ReceiveType.QueryAction; } } found = new Regex("^:.*? PRIVMSG .* :"+(char)1+".*"+(char)1+"$").Match(rawline); if (found.Success) { return ReceiveType.CtcpRequest; } found = new Regex("^:.*? PRIVMSG (.).* :.*$").Match(rawline); if (found.Success) { switch (found.Groups[1].Value) { case "#": case "!": case "&": case "+": return ReceiveType.ChannelMessage; default: return ReceiveType.QueryMessage; } } found = new Regex("^:.*? NOTICE .* :"+(char)1+".*"+(char)1+"$").Match(rawline); if (found.Success) { return ReceiveType.CtcpReply; } found = new Regex("^:.*? NOTICE (.).* :.*$").Match(rawline); if (found.Success) { switch (found.Groups[1].Value) { case "#": case "!": case "&": case "+": return ReceiveType.ChannelNotice; default: return ReceiveType.QueryNotice; } } found = new Regex("^:.*? INVITE .* .*$").Match(rawline); if (found.Success) { return ReceiveType.Invite; } found = new Regex("^:.*? JOIN .*$").Match(rawline); if (found.Success) { return ReceiveType.Join; } found = new Regex("^:.*? TOPIC .* :.*$").Match(rawline); if (found.Success) { return ReceiveType.TopicChange; } found = new Regex("^:.*? NICK .*$").Match(rawline); if (found.Success) { return ReceiveType.NickChange; } found = new Regex("^:.*? KICK .* .*$").Match(rawline); if (found.Success) { return ReceiveType.Kick; } found = new Regex("^:.*? PART .*$").Match(rawline); if (found.Success) { return ReceiveType.Part; } found = new Regex("^:.*? MODE (.*) .*$").Match(rawline); if (found.Success) { if (found.Groups[1].Value == _Nickname) { return ReceiveType.UserModeChange; } else { return ReceiveType.ChannelModeChange; } } found = new Regex("^:.*? QUIT :.*$").Match(rawline); if (found.Success) { return ReceiveType.Quit; } #if LOG4NET Logger.MessageTypes.Warn("messagetype unknown: \""+rawline+"\""); #endif return ReceiveType.Unknown; } private void _HandleEvents(Data ircdata) { string code; if (OnRawMessage != null) { OnRawMessage(ircdata); } // special IRC messages code = ircdata.RawMessageEx[0]; switch (code) { case "PING": _Event_PING(ircdata); break; case "ERROR": _Event_ERROR(ircdata); break; } code = ircdata.RawMessageEx[1]; switch (code) { case "PRIVMSG": _Event_PRIVMSG(ircdata); break; case "NOTICE": _Event_NOTICE(ircdata); break; case "JOIN": _Event_JOIN(ircdata); break; case "PART": _Event_PART(ircdata); break; case "KICK": _Event_KICK(ircdata); break; case "QUIT": _Event_QUIT(ircdata); break; case "TOPIC": _Event_TOPIC(ircdata); break; case "NICK": _Event_NICK(ircdata); break; case "INVITE": _Event_INVITE(ircdata); break; case "MODE": _Event_MODE(ircdata); break; } bool validreplycode = false; ReplyCode replycode = ReplyCode.NULL; try { replycode = (ReplyCode)int.Parse(code); validreplycode = true; } catch (FormatException) { // nothing, if it's not a number then just skip it } if (validreplycode) { switch (replycode) { case ReplyCode.RPL_WELCOME: _Event_RPL_WELCOME(ircdata); break; case ReplyCode.RPL_TOPIC: _Event_RPL_TOPIC(ircdata); break; case ReplyCode.RPL_NOTOPIC: _Event_RPL_NOTOPIC(ircdata); break; case ReplyCode.RPL_NAMREPLY: _Event_RPL_NAMREPLY(ircdata); break; case ReplyCode.RPL_WHOREPLY: _Event_RPL_WHOREPLY(ircdata); break; case ReplyCode.RPL_CHANNELMODEIS: _Event_RPL_CHANNELMODEIS(ircdata); break; case ReplyCode.ERR_NICKNAMEINUSE: _Event_ERR_NICKNAMEINUSE(ircdata); break; } } } private bool _RemoveIrcUser(string nickname) { if (GetIrcUser(nickname).JoinedChannels.Length == 0) { // he is nowhere else, lets kill him _IrcUsers.Remove(nickname.ToLower()); return true; } return false; } // <internal messagehandler> private void _Event_PING(Data ircdata) { string pongdata = ircdata.RawMessageEx[1].Substring(1); #if LOG4NET Logger.Connection.Debug("Ping? Pong!"); #endif Pong(pongdata); if (OnPing != null) { OnPing(pongdata); } } private void _Event_ERROR(Data ircdata) { string message = ircdata.Message; #if LOG4NET Logger.Connection.Info("received ERROR from IRC server"); #endif if (OnError != null) { OnError(message, ircdata); } } private void _Event_JOIN(Data ircdata) { string who = ircdata.Nick; string channelname = ircdata.Channel; if (IsMe(who)) { _JoinedChannels.Add(channelname); } if (ChannelSyncing) { Channel channel; if (IsMe(who)) { // we joined the channel #if LOG4NET Logger.ChannelSyncing.Debug("joining channel: "+channelname); #endif channel = new Channel(channelname); _Channels.Add(channelname.ToLower(), channel); Mode(channelname); Who(channelname); Ban(channelname); } else { // someone else did Who(who); } #if LOG4NET Logger.ChannelSyncing.Debug(who+" joins channel: "+channelname); #endif channel = GetChannel(channelname); IrcUser ircuser = GetIrcUser(who); if (ircuser == null) { ircuser = new IrcUser(who, this); ircuser.Ident = ircdata.Ident; ircuser.Host = ircdata.Host; _IrcUsers.Add(who.ToLower(), ircuser); } ChannelUser channeluser = new ChannelUser(channelname, ircuser); channel.UnsafeUsers.Add(who.ToLower(), channeluser); } if (OnJoin != null) { OnJoin(channelname, who, ircdata); } } private void _Event_PART(Data ircdata) { string who = ircdata.Nick; string channel = ircdata.Channel; string partmessage = ircdata.Message; if (IsMe(who)) { _JoinedChannels.Remove(channel); } if (ChannelSyncing) { if (IsMe(who)) { #if LOG4NET Logger.ChannelSyncing.Debug("parting channel: "+channel); #endif _Channels.Remove(channel.ToLower()); } else { #if LOG4NET Logger.ChannelSyncing.Debug(who+" parts channel: "+channel); #endif GetChannel(channel).UnsafeUsers.Remove(who.ToLower()); _RemoveIrcUser(who); } } if (OnPart != null) { OnPart(channel, who, partmessage, ircdata); } } private void _Event_KICK(Data ircdata) { string channel = ircdata.Channel; string victim = ircdata.RawMessageEx[3]; string who = ircdata.Nick; string reason = ircdata.Message; if (IsMe(victim)) { _JoinedChannels.Remove(channel); } if (ChannelSyncing) { if (IsMe(victim)) { _Channels.Remove(channel.ToLower()); } else { GetChannel(channel).UnsafeUsers.Remove(victim.ToLower()); _RemoveIrcUser(who); } } if (OnKick != null) { OnKick(channel, victim, who, reason, ircdata); } } private void _Event_QUIT(Data ircdata) { string who = ircdata.Nick; string reason = ircdata.Message; if (IsMe(ircdata.Nick)) { foreach (string channel in _JoinedChannels) { _JoinedChannels.Remove(channel); } } if (ChannelSyncing) { foreach (string channel in GetIrcUser(who).JoinedChannels) { GetChannel(channel).UnsafeUsers.Remove(who.ToLower()); } _RemoveIrcUser(who); } if (OnQuit != null) { OnQuit(who, reason, ircdata); } } private void _Event_PRIVMSG(Data ircdata) { if (ircdata.Type == ReceiveType.CtcpRequest) { // Substring must be 1,4 because of \001 in CTCP messages if (ircdata.Message.Substring(1, 4) == "PING") { Message(SendType.CtcpReply, ircdata.Nick, "PING "+ircdata.Message.Substring(6, (ircdata.Message.Length-7))); } else if (ircdata.Message.Substring(1, 7) == "VERSION") { string versionstring; if (_CtcpVersion == null) { versionstring = VersionString; } else { versionstring = _CtcpVersion+" | using "+VersionString; } Message(SendType.CtcpReply, ircdata.Nick, "VERSION "+versionstring); } else if (ircdata.Message.Substring(1, 10) == "CLIENTINFO") { Message(SendType.CtcpReply, ircdata.Nick, "CLIENTINFO PING VERSION CLIENTINFO"); } } switch (ircdata.Type) { case ReceiveType.ChannelMessage: if (OnChannelMessage != null) { OnChannelMessage(ircdata); } break; case ReceiveType.ChannelAction: if (OnChannelAction != null) { string action = ircdata.Message.Substring(7, ircdata.Message.Length-8); OnChannelAction(action, ircdata); } break; case ReceiveType.QueryMessage: if (OnQueryMessage != null) { OnQueryMessage(ircdata); } break; case ReceiveType.QueryAction: if (OnQueryAction != null) { string action = ircdata.Message.Substring(7, ircdata.Message.Length-8); OnQueryAction(action, ircdata); } break; case ReceiveType.CtcpRequest: if (OnCtcpRequest != null) { OnCtcpRequest(ircdata); } break; } } private void _Event_NOTICE(Data ircdata) { switch (ircdata.Type) { case ReceiveType.ChannelNotice: if (OnChannelNotice != null) { OnChannelNotice(ircdata); } break; case ReceiveType.QueryNotice: if (OnQueryNotice != null) { OnQueryNotice(ircdata); } break; case ReceiveType.CtcpReply: if (OnCtcpReply != null) { OnCtcpReply(ircdata); } break; } } private void _Event_TOPIC(Data ircdata) { string who = ircdata.Nick; string channel = ircdata.Channel; string newtopic = ircdata.Message; if (ChannelSyncing && IsJoined(channel)) { GetChannel(channel).Topic = newtopic; #if LOG4NET Logger.ChannelSyncing.Debug("stored topic for channel: "+channel); #endif } if (OnTopicChange != null) { OnTopicChange(channel, who, newtopic, ircdata); } } private void _Event_NICK(Data ircdata) { string oldnickname = ircdata.Nick; string newnickname = ircdata.Message; if (IsMe(ircdata.Nick)) { _Nickname = newnickname; } if (ChannelSyncing) { IrcUser ircuser = GetIrcUser(oldnickname); // if we don't have any info about him, don't update him! // (only queries or ourself in no channels) if (ircuser != null) { string[] joinedchannels = ircuser.JoinedChannels; // update his nickname ircuser.Nick = newnickname; // remove the old entry // remove first to avoid duplication, Foo -> foo _IrcUsers.Remove(oldnickname.ToLower()); // add him as new entry and new nickname as key _IrcUsers.Add(newnickname.ToLower(), ircuser); #if LOG4NET Logger.ChannelSyncing.Debug("updated nickname of: "+oldnickname+" to: "+newnickname); #endif // now the same for all channels he is joined Channel channel; ChannelUser channeluser; foreach (string channelname in joinedchannels) { channel = GetChannel(channelname); channeluser = GetChannelUser(channelname, oldnickname); // remove first to avoid duplication, Foo -> foo channel.UnsafeUsers.Remove(oldnickname.ToLower()); channel.UnsafeUsers.Add(newnickname.ToLower(), channeluser); } } } if (OnNickChange != null) { OnNickChange(oldnickname, newnickname, ircdata); } } private void _Event_INVITE(Data ircdata) { string channel = ircdata.Channel; string inviter = ircdata.Nick; if (OnInvite != null) { OnInvite(inviter, channel, ircdata); } } private void _Event_MODE(Data ircdata) { if (IsMe(ircdata.RawMessageEx[2])) { // my mode changed _Usermode = ircdata.RawMessageEx[3].Substring(1); } else { string mode = ircdata.RawMessageEx[3]; string parameter = String.Join(" ", ircdata.RawMessageEx, 4, ircdata.RawMessageEx.Length-4); string[] parameters = parameter.Split(new Char[] {' '}); bool add = false; bool remove = false; int modelength = mode.Length; string temp; Channel channel = null; if (ChannelSyncing) { channel = GetChannel(ircdata.Channel); } IEnumerator parametersEnumerator = parameters.GetEnumerator(); // bring the enumerator to the 1. element parametersEnumerator.MoveNext(); for (int i = 0; i < modelength; i++) { switch(mode[i]) { case '-': add = false; remove = true; break; case '+': add = true; remove = false; break; case 'o': temp = (string)parametersEnumerator.Current; parametersEnumerator.MoveNext(); if (add) { if (ChannelSyncing) { // update the op list channel.Ops.Add(temp.ToLower(), GetIrcUser(temp)); #if LOG4NET Logger.ChannelSyncing.Debug("added op: "+temp+" to: "+ircdata.Channel); #endif // update the user op status GetChannelUser(ircdata.Channel, temp).IsOp = true; #if LOG4NET Logger.ChannelSyncing.Debug("set op status: "+temp+" for: "+ircdata.Channel); #endif } if (OnOp != null) { OnOp(ircdata.Channel, ircdata.Nick, temp, ircdata); } } if (remove) { if (ChannelSyncing) { // update the op list channel.Ops.Remove(temp.ToLower()); #if LOG4NET Logger.ChannelSyncing.Debug("removed op: "+temp+" from: "+ircdata.Channel); #endif // update the user op status GetChannelUser(ircdata.Channel, temp).IsOp = false; #if LOG4NET Logger.ChannelSyncing.Debug("unset op status: "+temp+" for: "+ircdata.Channel); #endif } if (OnDeop != null) { OnDeop(ircdata.Channel, ircdata.Nick, temp, ircdata); } } break; case 'v': temp = (string)parametersEnumerator.Current; parametersEnumerator.MoveNext(); if (add) { if (ChannelSyncing) { // update the voice list channel.Voices.Add(temp.ToLower(), GetIrcUser(temp)); #if LOG4NET Logger.ChannelSyncing.Debug("added voice: "+temp+" to: "+ircdata.Channel); #endif // update the user voice status GetChannelUser(ircdata.Channel, temp).IsVoice = true; #if LOG4NET Logger.ChannelSyncing.Debug("set voice status: "+temp+" for: "+ircdata.Channel); #endif } if (OnVoice != null) { OnVoice(ircdata.Channel, ircdata.Nick, temp, ircdata); } } if (remove) { if (ChannelSyncing) { // update the voice list channel.Voices.Remove(temp.ToLower()); #if LOG4NET Logger.ChannelSyncing.Debug("removed voice: "+temp+" from: "+ircdata.Channel); #endif // update the user voice status GetChannelUser(ircdata.Channel, temp).IsVoice = false; #if LOG4NET Logger.ChannelSyncing.Debug("unset voice status: "+temp+" for: "+ircdata.Channel); #endif } if (OnDevoice != null) { OnDevoice(ircdata.Channel, ircdata.Nick, temp, ircdata); } } break; case 'b': temp = (string)parametersEnumerator.Current; parametersEnumerator.MoveNext(); if (add) { if (ChannelSyncing) { channel.Bans.Add(temp); #if LOG4NET Logger.ChannelSyncing.Debug("added ban: "+temp+" to: "+ircdata.Channel); #endif } if (OnBan != null) { OnBan(ircdata.Channel, ircdata.Nick, temp, ircdata); } } if (remove) { if (ChannelSyncing) { channel.Bans.Remove(temp); #if LOG4NET Logger.ChannelSyncing.Debug("removed ban: "+temp+" from: "+ircdata.Channel); #endif } if (OnUnban != null) { OnUnban(ircdata.Channel, ircdata.Nick, temp, ircdata); } } break; case 'l': temp = (string)parametersEnumerator.Current; parametersEnumerator.MoveNext(); if (add) { if (ChannelSyncing) { channel.UserLimit = int.Parse(temp); #if LOG4NET Logger.ChannelSyncing.Debug("stored user limit for: "+ircdata.Channel); #endif } } if (remove) { if (ChannelSyncing) { channel.UserLimit = 0; #if LOG4NET Logger.ChannelSyncing.Debug("removed user limit for: "+ircdata.Channel); #endif } } break; case 'k': temp = (string)parametersEnumerator.Current; parametersEnumerator.MoveNext(); if (add) { if (ChannelSyncing) { channel.Key = temp; #if LOG4NET Logger.ChannelSyncing.Debug("stored channel key for: "+ircdata.Channel); #endif } } if (remove) { if (ChannelSyncing) { channel.Key = ""; #if LOG4NET Logger.ChannelSyncing.Debug("removed channel key for: "+ircdata.Channel); #endif } } break; default: if (add) { if (ChannelSyncing) { channel.Mode += mode[i]; #if LOG4NET Logger.ChannelSyncing.Debug("added channel mode ("+mode[i]+") for: "+ircdata.Channel); #endif } } if (remove) { if (ChannelSyncing) { channel.Mode = channel.Mode.Replace(mode[i], new char()); #if LOG4NET Logger.ChannelSyncing.Debug("removed channel mode ("+mode[i]+") for: "+ircdata.Channel); #endif } } break; } } } if ((ircdata.Type == ReceiveType.UserModeChange) && (OnUserModeChange != null)) { OnUserModeChange(ircdata); } if ((ircdata.Type == ReceiveType.ChannelModeChange) && (OnChannelModeChange != null)) { OnChannelModeChange(ircdata); } if (OnModeChange != null) { OnModeChange(ircdata); } } private void _Event_RPL_WELCOME(Data ircdata) { // updating our nickname, that we got (maybe cutted...) _Nickname = ircdata.RawMessageEx[2]; if (OnRegistered != null) { OnRegistered(); } } private void _Event_RPL_TOPIC(Data ircdata) { string topic = ircdata.Message; string channel = ircdata.Channel; if (ChannelSyncing && IsJoined(channel)) { GetChannel(channel).Topic = topic; #if LOG4NET Logger.ChannelSyncing.Debug("stored topic for channel: "+channel); #endif } if (OnTopic != null) { OnTopic(channel, topic, ircdata); } } private void _Event_RPL_NOTOPIC(Data ircdata) { string channel = ircdata.Channel; if (ChannelSyncing && IsJoined(channel)) { GetChannel(channel).Topic = ""; #if LOG4NET Logger.ChannelSyncing.Debug("stored empty topic for channel: "+channel); #endif } if (OnTopic != null) { OnTopic(channel, "", ircdata); } } private void _Event_RPL_NAMREPLY(Data ircdata) { string channel = ircdata.Channel; string[] userlist = ircdata.MessageEx; if (ChannelSyncing && IsJoined(channel)) { string nickname; bool op; bool voice; foreach (string user in userlist) { if (user.Length <= 0) { continue; } op = false; voice = false; switch (user[0]) { case '@': op = true; nickname = user.Substring(1); break; case '+': voice = true; nickname = user.Substring(1); break; // RFC VIOLATION // some IRC network do this and break our channel sync... case '&': nickname = user.Substring(1); break; case '%': nickname = user.Substring(1); break; default: nickname = user; break; } IrcUser ircuser = GetIrcUser(nickname); ChannelUser channeluser = GetChannelUser(channel, nickname); if (ircuser == null) { #if LOG4NET Logger.ChannelSyncing.Debug("creating IrcUser: "+nickname+" because he doesn't exist yet"); #endif ircuser = new IrcUser(nickname, this); _IrcUsers.Add(nickname.ToLower(), ircuser); } if (channeluser == null) { #if LOG4NET Logger.ChannelSyncing.Debug("creating ChannelUser: "+nickname+" for Channel: "+channel+" because he doesn't exist yet"); #endif channeluser = new ChannelUser(channel, ircuser); GetChannel(channel).UnsafeUsers.Add(nickname.ToLower(), channeluser); } channeluser.IsOp = op; channeluser.IsVoice = voice; } } if (OnNameReply != null) { OnNameReply(channel, userlist, ircdata); } } private void _Event_RPL_WHOREPLY(Data ircdata) { string channel = ircdata.Channel; string ident = ircdata.RawMessageEx[4]; string host = ircdata.RawMessageEx[5]; string server = ircdata.RawMessageEx[6]; string nick = ircdata.RawMessageEx[7]; string usermode = ircdata.RawMessageEx[8]; string realname = ircdata.Message.Substring(2); int hopcount = 0; string temp = ircdata.RawMessageEx[9].Substring(1); try { hopcount = int.Parse(temp); } catch (FormatException) { #if LOG4NET Logger.MessageParser.Warn("couldn't parse (as int): '"+temp+"'"); #endif } bool op = false; bool voice = false; bool ircop = false; bool away = false; int usermodelength = usermode.Length; for (int i = 0; i < usermodelength; i++) { switch (usermode[i]) { case 'H': away = false; break; case 'G': away = true; break; case '@': op = true; break; case '+': voice = true; break; case '*': ircop = true; break; } } if (ChannelSyncing) { #if LOG4NET Logger.ChannelSyncing.Debug("updating userinfo (from whoreply) for user: "+nick+" channel: "+channel); #endif IrcUser ircuser = GetIrcUser(nick); ircuser.Ident = ident; ircuser.Host = host; ircuser.Server = server; ircuser.Nick = nick; ircuser.HopCount = hopcount; ircuser.Realname = realname; ircuser.IsAway = away; ircuser.IsIrcOp = ircop; switch (channel[0]) { case '#': case '!': case '&': case '+': // this channel may not be where we are joined! // see RFC 1459 and RFC 2812, it must return a channelname // we use this channel info when possible... ChannelUser channeluser = GetChannelUser(channel, nick); if (channeluser != null) { channeluser.IsOp = op; channeluser.IsVoice = voice; } break; } } if (OnWho != null) { OnWho(channel, nick, ident, host, realname, away, op, voice, ircop, server, hopcount, ircdata); } } private void _Event_RPL_CHANNELMODEIS(Data ircdata) { if (ChannelSyncing && IsJoined(ircdata.Channel)) { GetChannel(ircdata.Channel).Mode = ircdata.RawMessageEx[4]; } } private void _Event_ERR_NICKNAMEINUSE(Data ircdata) { #if LOG4NET Logger.Connection.Warn("nickname collision detected, changing nickname"); #endif string nickname; Random rand = new Random(); int number = rand.Next(); if (Nickname.Length > 5) { nickname = Nickname.Substring(0, 5)+number; } else { nickname = Nickname.Substring(0, Nickname.Length-1)+number; } Nick(nickname, Priority.Critical); } // </internal messagehandler> } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Squareup.Okhttp.Internal { // Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']" [global::Android.Runtime.Register ("com/squareup/okhttp/internal/DiskLruCache", DoNotGenerateAcw=true)] public sealed partial class DiskLruCache : global::Java.Lang.Object, global::Java.IO.ICloseable { // Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']" [global::Android.Runtime.Register ("com/squareup/okhttp/internal/DiskLruCache$Editor", DoNotGenerateAcw=true)] public sealed partial class Editor : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor.FaultHidingOutputStream']" [global::Android.Runtime.Register ("com/squareup/okhttp/internal/DiskLruCache$Editor$FaultHidingOutputStream", DoNotGenerateAcw=true)] public partial class FaultHidingOutputStream : global::Java.IO.FilterOutputStream { protected FaultHidingOutputStream (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/squareup/okhttp/internal/DiskLruCache$Editor", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Editor); } } internal Editor (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_abort; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='abort' and count(parameter)=0]" [Register ("abort", "()V", "")] public void Abort () { if (id_abort == IntPtr.Zero) id_abort = JNIEnv.GetMethodID (class_ref, "abort", "()V"); JNIEnv.CallVoidMethod (Handle, id_abort); } static IntPtr id_abortUnlessCommitted; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='abortUnlessCommitted' and count(parameter)=0]" [Register ("abortUnlessCommitted", "()V", "")] public void AbortUnlessCommitted () { if (id_abortUnlessCommitted == IntPtr.Zero) id_abortUnlessCommitted = JNIEnv.GetMethodID (class_ref, "abortUnlessCommitted", "()V"); JNIEnv.CallVoidMethod (Handle, id_abortUnlessCommitted); } static IntPtr id_commit; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='commit' and count(parameter)=0]" [Register ("commit", "()V", "")] public void Commit () { if (id_commit == IntPtr.Zero) id_commit = JNIEnv.GetMethodID (class_ref, "commit", "()V"); JNIEnv.CallVoidMethod (Handle, id_commit); } static IntPtr id_getString_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='getString' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getString", "(I)Ljava/lang/String;", "")] public string GetString (int p0) { if (id_getString_I == IntPtr.Zero) id_getString_I = JNIEnv.GetMethodID (class_ref, "getString", "(I)Ljava/lang/String;"); return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getString_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_newInputStream_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='newInputStream' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("newInputStream", "(I)Ljava/io/InputStream;", "")] public global::System.IO.Stream NewInputStream (int p0) { if (id_newInputStream_I == IntPtr.Zero) id_newInputStream_I = JNIEnv.GetMethodID (class_ref, "newInputStream", "(I)Ljava/io/InputStream;"); return global::Android.Runtime.InputStreamInvoker.FromJniHandle (JNIEnv.CallObjectMethod (Handle, id_newInputStream_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_newOutputStream_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='newOutputStream' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("newOutputStream", "(I)Ljava/io/OutputStream;", "")] public global::System.IO.Stream NewOutputStream (int p0) { if (id_newOutputStream_I == IntPtr.Zero) id_newOutputStream_I = JNIEnv.GetMethodID (class_ref, "newOutputStream", "(I)Ljava/io/OutputStream;"); return global::Android.Runtime.OutputStreamInvoker.FromJniHandle (JNIEnv.CallObjectMethod (Handle, id_newOutputStream_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_set_ILjava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Editor']/method[@name='set' and count(parameter)=2 and parameter[1][@type='int'] and parameter[2][@type='java.lang.String']]" [Register ("set", "(ILjava/lang/String;)V", "")] public void Set (int p0, string p1) { if (id_set_ILjava_lang_String_ == IntPtr.Zero) id_set_ILjava_lang_String_ = JNIEnv.GetMethodID (class_ref, "set", "(ILjava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallVoidMethod (Handle, id_set_ILjava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } } // Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Entry']" [global::Android.Runtime.Register ("com/squareup/okhttp/internal/DiskLruCache$Entry", DoNotGenerateAcw=true)] public sealed partial class Entry : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/squareup/okhttp/internal/DiskLruCache$Entry", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Entry); } } internal Entry (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_getLengths; public string Lengths { // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Entry']/method[@name='getLengths' and count(parameter)=0]" [Register ("getLengths", "()Ljava/lang/String;", "GetGetLengthsHandler")] get { if (id_getLengths == IntPtr.Zero) id_getLengths = JNIEnv.GetMethodID (class_ref, "getLengths", "()Ljava/lang/String;"); return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getLengths), JniHandleOwnership.TransferLocalRef); } } static IntPtr id_getCleanFile_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Entry']/method[@name='getCleanFile' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getCleanFile", "(I)Ljava/io/File;", "")] public global::Java.IO.File GetCleanFile (int p0) { if (id_getCleanFile_I == IntPtr.Zero) id_getCleanFile_I = JNIEnv.GetMethodID (class_ref, "getCleanFile", "(I)Ljava/io/File;"); return global::Java.Lang.Object.GetObject<global::Java.IO.File> (JNIEnv.CallObjectMethod (Handle, id_getCleanFile_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_getDirtyFile_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Entry']/method[@name='getDirtyFile' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getDirtyFile", "(I)Ljava/io/File;", "")] public global::Java.IO.File GetDirtyFile (int p0) { if (id_getDirtyFile_I == IntPtr.Zero) id_getDirtyFile_I = JNIEnv.GetMethodID (class_ref, "getDirtyFile", "(I)Ljava/io/File;"); return global::Java.Lang.Object.GetObject<global::Java.IO.File> (JNIEnv.CallObjectMethod (Handle, id_getDirtyFile_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } } // Metadata.xml XPath class reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Snapshot']" [global::Android.Runtime.Register ("com/squareup/okhttp/internal/DiskLruCache$Snapshot", DoNotGenerateAcw=true)] public sealed partial class Snapshot : global::Java.Lang.Object, global::Java.IO.ICloseable { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/squareup/okhttp/internal/DiskLruCache$Snapshot", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Snapshot); } } internal Snapshot (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_close; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Snapshot']/method[@name='close' and count(parameter)=0]" [Register ("close", "()V", "")] public void Close () { if (id_close == IntPtr.Zero) id_close = JNIEnv.GetMethodID (class_ref, "close", "()V"); JNIEnv.CallVoidMethod (Handle, id_close); } static IntPtr id_edit; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Snapshot']/method[@name='edit' and count(parameter)=0]" [Register ("edit", "()Lcom/squareup/okhttp/internal/DiskLruCache$Editor;", "")] public global::Com.Squareup.Okhttp.Internal.DiskLruCache.Editor Edit () { if (id_edit == IntPtr.Zero) id_edit = JNIEnv.GetMethodID (class_ref, "edit", "()Lcom/squareup/okhttp/internal/DiskLruCache$Editor;"); return global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.DiskLruCache.Editor> (JNIEnv.CallObjectMethod (Handle, id_edit), JniHandleOwnership.TransferLocalRef); } static IntPtr id_getInputStream_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Snapshot']/method[@name='getInputStream' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getInputStream", "(I)Ljava/io/InputStream;", "")] public global::System.IO.Stream GetInputStream (int p0) { if (id_getInputStream_I == IntPtr.Zero) id_getInputStream_I = JNIEnv.GetMethodID (class_ref, "getInputStream", "(I)Ljava/io/InputStream;"); return global::Android.Runtime.InputStreamInvoker.FromJniHandle (JNIEnv.CallObjectMethod (Handle, id_getInputStream_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } static IntPtr id_getLength_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Snapshot']/method[@name='getLength' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getLength", "(I)J", "")] public long GetLength (int p0) { if (id_getLength_I == IntPtr.Zero) id_getLength_I = JNIEnv.GetMethodID (class_ref, "getLength", "(I)J"); return JNIEnv.CallLongMethod (Handle, id_getLength_I, new JValue (p0)); } static IntPtr id_getString_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache.Snapshot']/method[@name='getString' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getString", "(I)Ljava/lang/String;", "")] public string GetString (int p0) { if (id_getString_I == IntPtr.Zero) id_getString_I = JNIEnv.GetMethodID (class_ref, "getString", "(I)Ljava/lang/String;"); return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getString_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/squareup/okhttp/internal/DiskLruCache", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (DiskLruCache); } } internal DiskLruCache (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_getDirectory; public global::Java.IO.File Directory { // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='getDirectory' and count(parameter)=0]" [Register ("getDirectory", "()Ljava/io/File;", "GetGetDirectoryHandler")] get { if (id_getDirectory == IntPtr.Zero) id_getDirectory = JNIEnv.GetMethodID (class_ref, "getDirectory", "()Ljava/io/File;"); return global::Java.Lang.Object.GetObject<global::Java.IO.File> (JNIEnv.CallObjectMethod (Handle, id_getDirectory), JniHandleOwnership.TransferLocalRef); } } static IntPtr id_isClosed; public bool IsClosed { // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='isClosed' and count(parameter)=0]" [Register ("isClosed", "()Z", "GetIsClosedHandler")] get { if (id_isClosed == IntPtr.Zero) id_isClosed = JNIEnv.GetMethodID (class_ref, "isClosed", "()Z"); return JNIEnv.CallBooleanMethod (Handle, id_isClosed); } } static IntPtr id_getMaxSize; static IntPtr id_setMaxSize_J; public long MaxSize { // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='getMaxSize' and count(parameter)=0]" [Register ("getMaxSize", "()J", "GetGetMaxSizeHandler")] get { if (id_getMaxSize == IntPtr.Zero) id_getMaxSize = JNIEnv.GetMethodID (class_ref, "getMaxSize", "()J"); return JNIEnv.CallLongMethod (Handle, id_getMaxSize); } // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='setMaxSize' and count(parameter)=1 and parameter[1][@type='long']]" [Register ("setMaxSize", "(J)V", "GetSetMaxSize_JHandler")] set { if (id_setMaxSize_J == IntPtr.Zero) id_setMaxSize_J = JNIEnv.GetMethodID (class_ref, "setMaxSize", "(J)V"); JNIEnv.CallVoidMethod (Handle, id_setMaxSize_J, new JValue (value)); } } static IntPtr id_close; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='close' and count(parameter)=0]" [Register ("close", "()V", "")] public void Close () { if (id_close == IntPtr.Zero) id_close = JNIEnv.GetMethodID (class_ref, "close", "()V"); JNIEnv.CallVoidMethod (Handle, id_close); } static IntPtr id_delete; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='delete' and count(parameter)=0]" [Register ("delete", "()V", "")] public void Delete () { if (id_delete == IntPtr.Zero) id_delete = JNIEnv.GetMethodID (class_ref, "delete", "()V"); JNIEnv.CallVoidMethod (Handle, id_delete); } static IntPtr id_edit_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='edit' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("edit", "(Ljava/lang/String;)Lcom/squareup/okhttp/internal/DiskLruCache$Editor;", "")] public global::Com.Squareup.Okhttp.Internal.DiskLruCache.Editor Edit (string p0) { if (id_edit_Ljava_lang_String_ == IntPtr.Zero) id_edit_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "edit", "(Ljava/lang/String;)Lcom/squareup/okhttp/internal/DiskLruCache$Editor;"); IntPtr native_p0 = JNIEnv.NewString (p0); global::Com.Squareup.Okhttp.Internal.DiskLruCache.Editor __ret = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.DiskLruCache.Editor> (JNIEnv.CallObjectMethod (Handle, id_edit_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_flush; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='flush' and count(parameter)=0]" [Register ("flush", "()V", "")] public void Flush () { if (id_flush == IntPtr.Zero) id_flush = JNIEnv.GetMethodID (class_ref, "flush", "()V"); JNIEnv.CallVoidMethod (Handle, id_flush); } static IntPtr id_get_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='get' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("get", "(Ljava/lang/String;)Lcom/squareup/okhttp/internal/DiskLruCache$Snapshot;", "")] public global::Com.Squareup.Okhttp.Internal.DiskLruCache.Snapshot Get (string p0) { if (id_get_Ljava_lang_String_ == IntPtr.Zero) id_get_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "get", "(Ljava/lang/String;)Lcom/squareup/okhttp/internal/DiskLruCache$Snapshot;"); IntPtr native_p0 = JNIEnv.NewString (p0); global::Com.Squareup.Okhttp.Internal.DiskLruCache.Snapshot __ret = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.DiskLruCache.Snapshot> (JNIEnv.CallObjectMethod (Handle, id_get_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_open_Ljava_io_File_IIJ; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='open' and count(parameter)=4 and parameter[1][@type='java.io.File'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='long']]" [Register ("open", "(Ljava/io/File;IIJ)Lcom/squareup/okhttp/internal/DiskLruCache;", "")] public static global::Com.Squareup.Okhttp.Internal.DiskLruCache Open (global::Java.IO.File p0, int p1, int p2, long p3) { if (id_open_Ljava_io_File_IIJ == IntPtr.Zero) id_open_Ljava_io_File_IIJ = JNIEnv.GetStaticMethodID (class_ref, "open", "(Ljava/io/File;IIJ)Lcom/squareup/okhttp/internal/DiskLruCache;"); global::Com.Squareup.Okhttp.Internal.DiskLruCache __ret = global::Java.Lang.Object.GetObject<global::Com.Squareup.Okhttp.Internal.DiskLruCache> (JNIEnv.CallStaticObjectMethod (class_ref, id_open_Ljava_io_File_IIJ, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (p3)), JniHandleOwnership.TransferLocalRef); return __ret; } static IntPtr id_remove_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='remove' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("remove", "(Ljava/lang/String;)Z", "")] public bool Remove (string p0) { if (id_remove_Ljava_lang_String_ == IntPtr.Zero) id_remove_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "remove", "(Ljava/lang/String;)Z"); IntPtr native_p0 = JNIEnv.NewString (p0); bool __ret = JNIEnv.CallBooleanMethod (Handle, id_remove_Ljava_lang_String_, new JValue (native_p0)); JNIEnv.DeleteLocalRef (native_p0); return __ret; } static IntPtr id_size; // Metadata.xml XPath method reference: path="/api/package[@name='com.squareup.okhttp.internal']/class[@name='DiskLruCache']/method[@name='size' and count(parameter)=0]" [Register ("size", "()J", "")] public long Size () { if (id_size == IntPtr.Zero) id_size = JNIEnv.GetMethodID (class_ref, "size", "()J"); return JNIEnv.CallLongMethod (Handle, id_size); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// The metrics associated with a host /// First published in XenServer 4.0. /// </summary> public partial class Host_metrics : XenObject<Host_metrics> { public Host_metrics() { } public Host_metrics(string uuid, long memory_total, long memory_free, bool live, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.memory_total = memory_total; this.memory_free = memory_free; this.live = live; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new Host_metrics from a Proxy_Host_metrics. /// </summary> /// <param name="proxy"></param> public Host_metrics(Proxy_Host_metrics proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(Host_metrics update) { uuid = update.uuid; memory_total = update.memory_total; memory_free = update.memory_free; live = update.live; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_Host_metrics proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; memory_total = proxy.memory_total == null ? 0 : long.Parse((string)proxy.memory_total); memory_free = proxy.memory_free == null ? 0 : long.Parse((string)proxy.memory_free); live = (bool)proxy.live; last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Host_metrics ToProxy() { Proxy_Host_metrics result_ = new Proxy_Host_metrics(); result_.uuid = (uuid != null) ? uuid : ""; result_.memory_total = memory_total.ToString(); result_.memory_free = memory_free.ToString(); result_.live = live; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new Host_metrics from a Hashtable. /// </summary> /// <param name="table"></param> public Host_metrics(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); memory_total = Marshalling.ParseLong(table, "memory_total"); memory_free = Marshalling.ParseLong(table, "memory_free"); live = Marshalling.ParseBool(table, "live"); last_updated = Marshalling.ParseDateTime(table, "last_updated"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Host_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._memory_total, other._memory_total) && Helper.AreEqual2(this._memory_free, other._memory_free) && Helper.AreEqual2(this._live, other._live) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, Host_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Host_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static Host_metrics get_record(Session session, string _host_metrics) { return new Host_metrics((Proxy_Host_metrics)session.proxy.host_metrics_get_record(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Get a reference to the host_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Host_metrics> get_by_uuid(Session session, string _uuid) { return XenRef<Host_metrics>.Create(session.proxy.host_metrics_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get the uuid field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static string get_uuid(Session session, string _host_metrics) { return (string)session.proxy.host_metrics_get_uuid(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse(); } /// <summary> /// Get the memory/total field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static long get_memory_total(Session session, string _host_metrics) { return long.Parse((string)session.proxy.host_metrics_get_memory_total(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Get the memory/free field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static long get_memory_free(Session session, string _host_metrics) { return long.Parse((string)session.proxy.host_metrics_get_memory_free(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Get the live field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static bool get_live(Session session, string _host_metrics) { return (bool)session.proxy.host_metrics_get_live(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse(); } /// <summary> /// Get the last_updated field of the given host_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static DateTime get_last_updated(Session session, string _host_metrics) { return session.proxy.host_metrics_get_last_updated(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse(); } /// <summary> /// Get the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _host_metrics) { return Maps.convert_from_proxy_string_string(session.proxy.host_metrics_get_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "").parse()); } /// <summary> /// Set the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _host_metrics, Dictionary<string, string> _other_config) { session.proxy.host_metrics_set_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given host_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _host_metrics, string _key, string _value) { session.proxy.host_metrics_add_to_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given host_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_host_metrics">The opaque_ref of the given host_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _host_metrics, string _key) { session.proxy.host_metrics_remove_from_other_config(session.uuid, (_host_metrics != null) ? _host_metrics : "", (_key != null) ? _key : "").parse(); } /// <summary> /// Return a list of all the host_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Host_metrics>> get_all(Session session) { return XenRef<Host_metrics>.Create(session.proxy.host_metrics_get_all(session.uuid).parse()); } /// <summary> /// Get all the host_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Host_metrics>, Host_metrics> get_all_records(Session session) { return XenRef<Host_metrics>.Create<Proxy_Host_metrics>(session.proxy.host_metrics_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// Total host memory (bytes) /// </summary> public virtual long memory_total { get { return _memory_total; } set { if (!Helper.AreEqual(value, _memory_total)) { _memory_total = value; Changed = true; NotifyPropertyChanged("memory_total"); } } } private long _memory_total; /// <summary> /// Free host memory (bytes) /// </summary> public virtual long memory_free { get { return _memory_free; } set { if (!Helper.AreEqual(value, _memory_free)) { _memory_free = value; Changed = true; NotifyPropertyChanged("memory_free"); } } } private long _memory_free; /// <summary> /// Pool master thinks this host is live /// </summary> public virtual bool live { get { return _live; } set { if (!Helper.AreEqual(value, _live)) { _live = value; Changed = true; NotifyPropertyChanged("live"); } } } private bool _live; /// <summary> /// Time at which this information was last updated /// </summary> public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; Changed = true; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Marten.Internal; using Marten.Internal.Operations; using Marten.Internal.Sessions; using Weasel.Postgresql; using Marten.Patching; using Marten.Services; using Marten.Util; using Npgsql; namespace Marten.Events.Daemon { /// <summary> /// Incrementally built batch command for projection updates /// </summary> public class ProjectionUpdateBatch : IUpdateBatch, IDisposable, ISessionWorkTracker { public EventRange Range { get; } private readonly DocumentSessionBase _session; private readonly CancellationToken _token; private readonly IList<Page> _pages = new List<Page>(); private Page _current; internal ProjectionUpdateBatch(EventGraph events, DocumentSessionBase session, EventRange range, CancellationToken token) { Range = range; _session = session; _token = token; Queue = new ActionBlock<IStorageOperation>(processOperation, new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 1, EnsureOrdered = true, CancellationToken = token}); startNewPage(session); var progressOperation = range.BuildProgressionOperation(events); Queue.Post(progressOperation); } public ActionBlock<IStorageOperation> Queue { get; } private void startNewPage(IMartenSession session) { _current = new Page(session); _pages.Add(_current); } private void processOperation(IStorageOperation operation) { if (_token.IsCancellationRequested) return; _current.Append(operation); if (_current.Count >= _session.Options.UpdateBatchSize) { startNewPage(_session); } } void IUpdateBatch.ApplyChanges(IMartenSession session) { if (_token.IsCancellationRequested) return; var exceptions = new List<Exception>(); foreach (var page in _pages) { page.ApplyChanges(exceptions); // Wanna fail fast here instead of trying the next batch if (exceptions.Any()) { throw new AggregateException(exceptions); } } } async Task IUpdateBatch.ApplyChangesAsync(IMartenSession session, CancellationToken token) { if (_token.IsCancellationRequested) return; var exceptions = new List<Exception>(); foreach (var page in _pages) { await page.ApplyChangesAsync(exceptions, token); // Wanna fail fast here instead of trying the next batch if (exceptions.Any()) { throw new AggregateException(exceptions); } } } public class Page { private readonly IMartenSession _session; public int Count { get; private set; } private readonly NpgsqlCommand _command = new NpgsqlCommand(); private readonly CommandBuilder _builder; private readonly List<IStorageOperation> _operations = new List<IStorageOperation>(); public Page(IMartenSession session) { _session = session; _builder = new CommandBuilder(_command); } public void Append(IStorageOperation operation) { Count++; operation.ConfigureCommand(_builder, _session); _builder.Append(";"); _operations.Add(operation); } public void ApplyChanges(IList<Exception> exceptions) { _command.CommandText = _builder.ToString(); using var reader = _session.Database.ExecuteReader(_command); UpdateBatch.ApplyCallbacks(_operations, reader, exceptions); } public async Task ApplyChangesAsync(IList<Exception> exceptions, CancellationToken token) { _command.CommandText = _builder.ToString(); using var reader = await _session.Database.ExecuteReaderAsync(_command, token); await UpdateBatch.ApplyCallbacksAsync(_operations, reader, exceptions, token); } } public void Dispose() { _session.Dispose(); Queue.Complete(); } IEnumerable<IDeletion> IUnitOfWork.Deletions() { throw new NotSupportedException(); } IEnumerable<IDeletion> IUnitOfWork.DeletionsFor<T>() { throw new NotSupportedException(); } IEnumerable<IDeletion> IUnitOfWork.DeletionsFor(Type documentType) { throw new NotSupportedException(); } IEnumerable<object> IUnitOfWork.Updates() { throw new NotSupportedException(); } IEnumerable<object> IUnitOfWork.Inserts() { throw new NotSupportedException(); } IEnumerable<T> IUnitOfWork.UpdatesFor<T>() { throw new NotSupportedException(); } IEnumerable<T> IUnitOfWork.InsertsFor<T>() { throw new NotSupportedException(); } IEnumerable<T> IUnitOfWork.AllChangedFor<T>() { throw new NotSupportedException(); } IList<StreamAction> IUnitOfWork.Streams() { throw new NotSupportedException(); } IEnumerable<PatchOperation> IUnitOfWork.Patches() { throw new NotSupportedException(); } IEnumerable<IStorageOperation> IUnitOfWork.Operations() { throw new NotSupportedException(); } IEnumerable<IStorageOperation> IUnitOfWork.OperationsFor<T>() { throw new NotSupportedException(); } IEnumerable<IStorageOperation> IUnitOfWork.OperationsFor(Type documentType) { throw new NotSupportedException(); } IEnumerable<object> IChangeSet.Updated => throw new NotSupportedException(); IEnumerable<object> IChangeSet.Inserted => throw new NotSupportedException(); IEnumerable<IDeletion> IChangeSet.Deleted => throw new NotSupportedException(); IEnumerable<IEvent> IChangeSet.GetEvents() { throw new NotSupportedException(); } IEnumerable<PatchOperation> IChangeSet.Patches => throw new NotSupportedException(); IEnumerable<StreamAction> IChangeSet.GetStreams() { throw new NotSupportedException(); } IChangeSet IChangeSet.Clone() { throw new NotSupportedException(); } void ISessionWorkTracker.Reset() { throw new NotSupportedException(); } void ISessionWorkTracker.Add(IStorageOperation operation) { Queue.Post(operation); } void ISessionWorkTracker.Sort(StoreOptions options) { throw new NotSupportedException(); } List<StreamAction> ISessionWorkTracker.Streams => throw new NotSupportedException(); IReadOnlyList<IStorageOperation> ISessionWorkTracker.AllOperations => throw new NotSupportedException(); void ISessionWorkTracker.Eject<T>(T document) { throw new NotSupportedException(); } bool ISessionWorkTracker.TryFindStream(string streamKey, out StreamAction stream) { throw new NotSupportedException(); } bool ISessionWorkTracker.TryFindStream(Guid streamId, out StreamAction stream) { throw new NotSupportedException(); } bool ISessionWorkTracker.HasOutstandingWork() { throw new NotSupportedException(); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Tests.Common; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; using Umbraco.Extensions; using Constants = Umbraco.Cms.Core.Constants; using FileSystems = Umbraco.Cms.Core.IO.FileSystems; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Scoping { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewEmptyPerTest)] public class ScopeFileSystemsTests : UmbracoIntegrationTest { private MediaFileManager MediaFileManager => GetRequiredService<MediaFileManager>(); private IHostingEnvironment HostingEnvironment => GetRequiredService<IHostingEnvironment>(); [SetUp] public void SetUp() => ClearFiles(IOHelper); [TearDown] public void Teardown() { ClearFiles(IOHelper); } private void ClearFiles(IIOHelper ioHelper) { TestHelper.DeleteDirectory(ioHelper.MapPath("media")); TestHelper.DeleteDirectory(ioHelper.MapPath("FileSysTests")); TestHelper.DeleteDirectory(ioHelper.MapPath(Constants.SystemDirectories.TempData.EnsureEndsWith('/') + "ShadowFs")); } [Test] public void MediaFileManager_does_not_write_to_physical_file_system_when_scoped_if_scope_does_not_complete() { string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService<ILogger<PhysicalFileSystem>>(), rootPath, rootUrl); MediaFileManager mediaFileManager = MediaFileManager; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); using (ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { MediaFileManager.FileSystem.AddFile("f1.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); } // After scope is disposed ensure shadow wrapper didn't commit to physical Assert.IsFalse(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); } [Test] public void MediaFileManager_writes_to_physical_file_system_when_scoped_and_scope_is_completed() { string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService<ILogger<PhysicalFileSystem>>(), rootPath, rootUrl); MediaFileManager mediaFileManager = MediaFileManager; Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); using (IScope scope = ScopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { mediaFileManager.FileSystem.AddFile("f1.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); scope.Complete(); Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); } // After scope is disposed ensure shadow wrapper writes to physical file system Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f1.txt")); } [Test] public void MultiThread() { string rootPath = HostingEnvironment.MapPathWebRoot(GlobalSettings.UmbracoMediaPath); string rootUrl = HostingEnvironment.ToAbsolute(GlobalSettings.UmbracoMediaPath); var physMediaFileSystem = new PhysicalFileSystem(IOHelper, HostingEnvironment, GetRequiredService<ILogger<PhysicalFileSystem>>(), rootPath, rootUrl); MediaFileManager mediaFileManager = MediaFileManager; var taskHelper = new TaskHelper(Mock.Of<ILogger<TaskHelper>>()); IScopeProvider scopeProvider = ScopeProvider; using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { mediaFileManager.FileSystem.AddFile("f1.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f1.txt")); Assert.IsFalse(physMediaFileSystem.FileExists("f1.txt")); // execute on another disconnected thread (execution context will not flow) Task t = taskHelper.ExecuteBackgroundTask(() => { Assert.IsFalse(mediaFileManager.FileSystem.FileExists("f1.txt")); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) { mediaFileManager.FileSystem.AddFile("f2.txt", ms); } Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f2.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f2.txt")); return Task.CompletedTask; }); Task.WaitAll(t); Assert.IsTrue(mediaFileManager.FileSystem.FileExists("f2.txt")); Assert.IsTrue(physMediaFileSystem.FileExists("f2.txt")); } } [Test] public void SingleShadow() { var taskHelper = new TaskHelper(Mock.Of<ILogger<TaskHelper>>()); IScopeProvider scopeProvider = ScopeProvider; bool isThrown = false; using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { // This is testing when another thread concurrently tries to create a scoped file system // because at the moment we don't support concurrent scoped filesystems. Task t = taskHelper.ExecuteBackgroundTask(() => { // ok to create a 'normal' other scope using (IScope other = scopeProvider.CreateScope()) { other.Complete(); } // not ok to create a 'scoped filesystems' other scope // we will get a "Already shadowing." exception. Assert.Throws<InvalidOperationException>(() => { using IScope other = scopeProvider.CreateScope(scopeFileSystems: true); }); isThrown = true; return Task.CompletedTask; }); Task.WaitAll(t); } Assert.IsTrue(isThrown); } [Test] public void SingleShadowEvenDetached() { var taskHelper = new TaskHelper(Mock.Of<ILogger<TaskHelper>>()); var scopeProvider = (ScopeProvider)ScopeProvider; using (IScope scope = scopeProvider.CreateScope(scopeFileSystems: true)) { // This is testing when another thread concurrently tries to create a scoped file system // because at the moment we don't support concurrent scoped filesystems. Task t = taskHelper.ExecuteBackgroundTask(() => { // not ok to create a 'scoped filesystems' other scope // because at the moment we don't support concurrent scoped filesystems // even a detached one // we will get a "Already shadowing." exception. Assert.Throws<InvalidOperationException>(() => { using IScope other = scopeProvider.CreateDetachedScope(scopeFileSystems: true); }); return Task.CompletedTask; }); Task.WaitAll(t); } IScope detached = scopeProvider.CreateDetachedScope(scopeFileSystems: true); Assert.IsNull(scopeProvider.AmbientScope); Assert.Throws<InvalidOperationException>(() => { // even if there is no ambient scope, there's a single shadow using IScope other = scopeProvider.CreateScope(scopeFileSystems: true); }); scopeProvider.AttachScope(detached); detached.Dispose(); } } }
/* Copyright (c) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; using System.Xml; using System.Collections; using System.Net; using System.IO; using Google.GData.Client; using Google.GData.Extensions.Apps; namespace Google.GData.Apps { /// <summary> /// The UserService class extends the AppsService abstraction /// to define a service that is preconfigured for access to Google Apps /// user accounts feeds. /// </summary> public class UserService : Service { /// <summary> /// Constructor /// </summary> /// <param name="applicationName">The name of the client application /// using this service.</param> public UserService(string applicationName) : base(AppsNameTable.GAppsService, applicationName) { this.NewAtomEntry += new FeedParserEventHandler(this.OnParsedNewUserEntry); this.NewFeed += new ServiceEventHandler(this.OnParsedNewFeed); // You can set factory.methodOverride = true if you are behind a // proxy that filters out HTTP methods such as PUT and DELETE. } /// <summary> /// overwritten Query method /// </summary> /// <param name="feedQuery">The FeedQuery to use</param> /// <returns>the retrieved UserFeed</returns> public UserFeed Query(UserQuery feedQuery) { try { Stream feedStream = Query(feedQuery.Uri); UserFeed feed = new UserFeed(feedQuery.Uri, this); feed.Parse(feedStream, AlternativeFormat.Atom); feedStream.Close(); if (feedQuery.RetrieveAllUsers) { AtomLink next, prev = null; while ((next = feed.Links.FindService("next", null)) != null && next != prev) { feedStream = Query(new Uri(next.HRef.ToString())); feed.Parse(feedStream, AlternativeFormat.Atom); feedStream.Close(); prev = next; } } return feed; } catch (GDataRequestException e) { AppsException a = AppsException.ParseAppsException(e); throw (a == null ? e : a); } } /// <summary> /// Inserts a new user account entry into the specified feed. /// </summary> /// <param name="feed">the feed into which this entry should be inserted</param> /// <param name="entry">the entry to insert</param> /// <returns>the inserted entry</returns> public UserEntry Insert(UserFeed feed, UserEntry entry) { try { return base.Insert(feed, entry) as UserEntry; } catch (GDataRequestException e) { AppsException a = AppsException.ParseAppsException(e); throw (a == null ? e : a); } } /// <summary> /// Inserts a new user account entry into the feed at the /// specified URI. /// </summary> /// <param name="feedUri">the URI of the feed into which this entry should be inserted</param> /// <param name="entry">the entry to insert</param> /// <returns>the inserted entry</returns> public UserEntry Insert(Uri feedUri, UserEntry entry) { try { return base.Insert(feedUri, entry) as UserEntry; } catch (GDataRequestException e) { AppsException a = AppsException.ParseAppsException(e); throw (a == null ? e : a); } } /// <summary> /// Overridden Delete method that throws AppsException /// </summary> /// <param name="uri">the URI to delete</param> public new void Delete(Uri uri) { try { base.Delete(uri); } catch (GDataRequestException e) { AppsException a = AppsException.ParseAppsException(e); throw (a == null ? e : a); } } /// <summary> /// Overridden Delete method that throws AppsException /// </summary> /// <param name="entry">the entry to delete</param> public void Delete(UserEntry entry) { try { base.Delete(entry); } catch (GDataRequestException e) { AppsException a = AppsException.ParseAppsException(e); throw (a == null ? e : a); } } /// <summary> /// Event handler. Called when a new list entry is parsed. /// </summary> /// <param name="sender">the object that's sending the evet</param> /// <param name="e">FeedParserEventArguments, holds the feedentry</param> protected void OnParsedNewUserEntry(object sender, FeedParserEventArgs e) { if (e == null) { throw new ArgumentNullException("e"); } if (e.CreatingEntry == true) { e.Entry = new UserEntry(); } } /// <summary> /// Feed handler. Instantiates a new <code>UserFeed</code>. /// </summary> /// <param name="sender">the object that's sending the evet</param> /// <param name="e"><code>ServiceEventArgs</code>, holds the feed</param> protected void OnParsedNewFeed(object sender, ServiceEventArgs e) { Tracing.TraceMsg("Created new user feed"); if (e == null) { throw new ArgumentNullException("e"); } e.Feed = new UserFeed(e.Uri, e.Service); } } }
using System; using System.Drawing; using System.Linq; using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreImage; using MonoTouch.CoreBluetooth; using System.Collections.Generic; using MonoTouch.HealthKit; namespace Xamarin.HeartMonitor { /// <summary> /// HeartRateMonitor sample for iOS 8 /// /// HRM code for Mac by Aaron Bockover /// HealthKit integration by Larry O'Brien /// </summary> /// <remarks> /// Icon for this app uses heart found here /// https://www.iconfinder.com/icons/299063/heart_icon#size=512 /// and is used under the Creative Commons license /// http://creativecommons.org/licenses/by/3.0/ /// </remarks> public class MainScreen : UIViewController { CBCentralManager manager = new CBCentralManager (); HeartRateMonitor monitor; List<HeartRateMonitor> heartRateMonitors = new List<HeartRateMonitor> (); UILabel statusLabel, heartRateLabel, heartRateUnitLabel, deviceNameLabel, permissionsLabel; UIButton connectButton, storeData; HKHealthStore healthKitStore; public override void ViewDidLoad () { base.ViewDidLoad (); #region UI controls statusLabel = new UILabel (new RectangleF(10, 30, 300, 30)); statusLabel.Text = "waiting..."; heartRateLabel = new UILabel(new RectangleF(10, 70, 150, 30)); heartRateLabel.Font = UIFont.BoldSystemFontOfSize (36); heartRateLabel.TextColor = UIColor.Red; heartRateUnitLabel = new UILabel(new RectangleF(160, 70, 150, 30)); deviceNameLabel = new UILabel(new RectangleF(10, 120, 300, 30)); connectButton = UIButton.FromType (UIButtonType.System); connectButton.SetTitle ("Connect", UIControlState.Normal); connectButton.SetTitle ("searching...", UIControlState.Disabled); connectButton.Enabled = false; connectButton.Frame = new RectangleF (10, 160, 300, 30); connectButton.TouchUpInside += ConnectToSelectedDevice; permissionsLabel = new UILabel (new RectangleF (10, 200, 300, 60)); storeData = UIButton.FromType (UIButtonType.System); storeData.Frame = new RectangleF (10, 250, 300, 30); storeData.SetTitle ("requires permission", UIControlState.Disabled); storeData.SetTitle ("Store in HealthKit", UIControlState.Normal); storeData.Enabled = false; storeData.TouchUpInside += (sender, e) => { UpdateHealthKit(heartRateLabel.Text); // pretty hacky :) }; Add (statusLabel); Add (heartRateLabel); Add (heartRateUnitLabel); Add (deviceNameLabel); Add (connectButton); Add (permissionsLabel); Add (storeData); #endregion InitializeCoreBluetooth (); #region HealthKit // https://gist.github.com/lobrien/1217d3cff7b29716c0d3 // http://www.knowing.net/index.php/2014/07/11/exploring-healthkit-with-xamarin-provisioning-and-permissions-illustrated-walkthrough/ healthKitStore = new HKHealthStore(); //Permissions //Request HealthKit authorization var heartRateId = HKQuantityTypeIdentifierKey.HeartRate; var heartRateType = HKObjectType.GetQuantityType (heartRateId); //Request to write heart rate, read nothing... healthKitStore.RequestAuthorizationToShare (new NSSet (new [] { heartRateType }), new NSSet (), (success, error) => InvokeOnMainThread (() => { if (success) { //Whatever... Console.WriteLine ("RequestAuthorizationToShare: success"); permissionsLabel.Text = "HealthKit access is enabled!"; storeData.Enabled = true; } else { //Whatever... Console.WriteLine ("RequestAuthorizationToShare: failed"); permissionsLabel.Text = "No permission to access HealthKit :-("; storeData.Enabled = false; } if (error != null) { Console.WriteLine ("HealthKit authorization error: " + error); } })); #endregion } #region HealthKit void UpdateHealthKit(string s) { //Creating a heartbeat sample int result = 0; if (Int32.TryParse (s, out result)) { var heartRateId = HKQuantityTypeIdentifierKey.HeartRate; var heartRateType = HKObjectType.GetQuantityType (heartRateId); var heartRateQuantityType = HKQuantityType.GetQuantityType (heartRateId); //Beats per minute = "Count/Minute" as a unit var heartRateUnitType = HKUnit.Count.UnitDividedBy (HKUnit.Minute); var quantity = HKQuantity.FromQuantity (heartRateUnitType, result); //If we know where the sensor is... var metadata = new HKMetadata (); metadata.HeartRateSensorLocation = HKHeartRateSensorLocation.Chest; //Create the sample var heartRateSample = HKQuantitySample.FromType (heartRateQuantityType, quantity, new NSDate (), new NSDate (), metadata); //Attempt to store it... healthKitStore.SaveObject (heartRateSample, (success, error) => { //Error will be non-null if permissions not granted Console.WriteLine ("Write succeeded: " + success); if (error != null) { Console.WriteLine (error); } }); } } #endregion #region Heart Pulse UI void DisconnectMonitor () { statusLabel.Text = "Not connected"; heartRateLabel.Text = "0"; heartRateLabel.Hidden = true; heartRateUnitLabel.Hidden = true; deviceNameLabel.Text = String.Empty; deviceNameLabel.Hidden = true; connectButton.Enabled = false; if (monitor != null) { monitor.Dispose (); monitor = null; } } void OnHeartRateUpdated (object sender, HeartBeatEventArgs e) { heartRateUnitLabel.Hidden = false; heartRateLabel.Hidden = false; heartRateLabel.Text = e.CurrentHeartBeat.Rate.ToString(); var monitor = (HeartRateMonitor)sender; if (monitor.Location == HeartRateMonitorLocation.Unknown) { statusLabel.Text = "Connected"; } else { statusLabel.Text = String.Format ("Connected on {0}", monitor.Location); } deviceNameLabel.Hidden = false; deviceNameLabel.Text = monitor.Name; } void OnHeartBeat (object sender, EventArgs e) { // TODO: removed the animation stuff from Mac Console.WriteLine ("OnHeartBeat"); } #endregion #region Bluetooth void ConnectToSelectedDevice (object sender, EventArgs e) { if (heartRateMonitors.Count > 0) { monitor = heartRateMonitors [0]; Console.WriteLine ("monitor:" + monitor); if (monitor != null) { statusLabel.Text = "Connecting to " + monitor.Name + " ... "; monitor.Connect (); } } else { statusLabel.Text = "No heart rate monitors detected"; Console.WriteLine ("No heart rate monitors detected"); } } void InitializeCoreBluetooth () { manager.UpdatedState += OnCentralManagerUpdatedState; //HACK: Modified this to just quit after finding the first heart rate monitor EventHandler<CBDiscoveredPeripheralEventArgs> discovered = null; discovered += (sender, e) => { Console.WriteLine ("discovered!"); if (monitor != null) { monitor.Dispose (); } monitor = new HeartRateMonitor (manager, e.Peripheral); monitor.HeartRateUpdated += OnHeartRateUpdated; monitor.HeartBeat += OnHeartBeat; heartRateMonitors.Add (monitor); connectButton.Enabled = true; //HACK: instead of adding to a list, just use this one statusLabel.Text = "Found " + monitor.Name + "."; manager.DiscoveredPeripheral -= discovered; }; manager.DiscoveredPeripheral += discovered; manager.ConnectedPeripheral += (sender, e) => e.Peripheral.DiscoverServices (); manager.DisconnectedPeripheral += (sender, e) => DisconnectMonitor (); } void OnCentralManagerUpdatedState (object sender, EventArgs e) { string message = null; switch (manager.State) { case CBCentralManagerState.PoweredOn: HeartRateMonitor.ScanForHeartRateMonitors (manager); //connectButton.Enabled = true; message = "Scanning..."; return; case CBCentralManagerState.Unsupported: message = "The platform or hardware does not support Bluetooth Low Energy."; break; case CBCentralManagerState.Unauthorized: message = "The application is not authorized to use Bluetooth Low Energy."; break; case CBCentralManagerState.PoweredOff: message = "Bluetooth is currently powered off."; break; default: message = "Unhandled state: " + manager.State; break; } if (message != null) { var alert = new UIAlertView ("Alert", message, null, "OK", null); alert.Show (); } } #endregion } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Debugger.V2 { /// <summary> /// Settings for a <see cref="Controller2Client"/>. /// </summary> public sealed partial class Controller2Settings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="Controller2Settings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="Controller2Settings"/>. /// </returns> public static Controller2Settings GetDefault() => new Controller2Settings(); /// <summary> /// Constructs a new <see cref="Controller2Settings"/> object with default settings. /// </summary> public Controller2Settings() { } private Controller2Settings(Controller2Settings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); RegisterDebuggeeSettings = existing.RegisterDebuggeeSettings; ListActiveBreakpointsSettings = existing.ListActiveBreakpointsSettings; UpdateActiveBreakpointSettings = existing.UpdateActiveBreakpointSettings; OnCopy(existing); } partial void OnCopy(Controller2Settings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="Controller2Client"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="Controller2Client"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="Controller2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="Controller2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="Controller2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="Controller2Client"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="Controller2Client"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="Controller2Client"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 60000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(60000), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Controller2Client.RegisterDebuggee</c> and <c>Controller2Client.RegisterDebuggeeAsync</c>. /// </summary> /// <remarks> /// The default <c>Controller2Client.RegisterDebuggee</c> and /// <c>Controller2Client.RegisterDebuggeeAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings RegisterDebuggeeSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Controller2Client.ListActiveBreakpoints</c> and <c>Controller2Client.ListActiveBreakpointsAsync</c>. /// </summary> /// <remarks> /// The default <c>Controller2Client.ListActiveBreakpoints</c> and /// <c>Controller2Client.ListActiveBreakpointsAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ListActiveBreakpointsSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>Controller2Client.UpdateActiveBreakpoint</c> and <c>Controller2Client.UpdateActiveBreakpointAsync</c>. /// </summary> /// <remarks> /// The default <c>Controller2Client.UpdateActiveBreakpoint</c> and /// <c>Controller2Client.UpdateActiveBreakpointAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 60000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 60000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings UpdateActiveBreakpointSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="Controller2Settings"/> object.</returns> public Controller2Settings Clone() => new Controller2Settings(this); } /// <summary> /// Controller2 client wrapper, for convenient use. /// </summary> public abstract partial class Controller2Client { /// <summary> /// The default endpoint for the Controller2 service, which is a host of "clouddebugger.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouddebugger.googleapis.com", 443); /// <summary> /// The default Controller2 scopes. /// </summary> /// <remarks> /// The default Controller2 scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// <item><description>"https://www.googleapis.com/auth/cloud_debugger"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud_debugger", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="Controller2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="Controller2Settings"/>.</param> /// <returns>The task representing the created <see cref="Controller2Client"/>.</returns> public static async Task<Controller2Client> CreateAsync(ServiceEndpoint endpoint = null, Controller2Settings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="Controller2Client"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="Controller2Settings"/>.</param> /// <returns>The created <see cref="Controller2Client"/>.</returns> public static Controller2Client Create(ServiceEndpoint endpoint = null, Controller2Settings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="Controller2Client"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="Controller2Settings"/>.</param> /// <returns>The created <see cref="Controller2Client"/>.</returns> public static Controller2Client Create(Channel channel, Controller2Settings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); Controller2.Controller2Client grpcClient = new Controller2.Controller2Client(channel); return new Controller2ClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, Controller2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, Controller2Settings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, Controller2Settings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, Controller2Settings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC Controller2 client. /// </summary> public virtual Controller2.Controller2Client GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="debuggee"> /// Debuggee information to register. /// The fields `project`, `uniquifier`, `description` and `agent_version` /// of the debuggee must be set. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<RegisterDebuggeeResponse> RegisterDebuggeeAsync( Debuggee debuggee, CallSettings callSettings = null) => RegisterDebuggeeAsync( new RegisterDebuggeeRequest { Debuggee = GaxPreconditions.CheckNotNull(debuggee, nameof(debuggee)), }, callSettings); /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="debuggee"> /// Debuggee information to register. /// The fields `project`, `uniquifier`, `description` and `agent_version` /// of the debuggee must be set. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<RegisterDebuggeeResponse> RegisterDebuggeeAsync( Debuggee debuggee, CancellationToken cancellationToken) => RegisterDebuggeeAsync( debuggee, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="debuggee"> /// Debuggee information to register. /// The fields `project`, `uniquifier`, `description` and `agent_version` /// of the debuggee must be set. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual RegisterDebuggeeResponse RegisterDebuggee( Debuggee debuggee, CallSettings callSettings = null) => RegisterDebuggee( new RegisterDebuggeeRequest { Debuggee = GaxPreconditions.CheckNotNull(debuggee, nameof(debuggee)), }, callSettings); /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<RegisterDebuggeeResponse> RegisterDebuggeeAsync( RegisterDebuggeeRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual RegisterDebuggeeResponse RegisterDebuggee( RegisterDebuggeeRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="debuggeeId"> /// Identifies the debuggee. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListActiveBreakpointsResponse> ListActiveBreakpointsAsync( string debuggeeId, CallSettings callSettings = null) => ListActiveBreakpointsAsync( new ListActiveBreakpointsRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), }, callSettings); /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="debuggeeId"> /// Identifies the debuggee. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListActiveBreakpointsResponse> ListActiveBreakpointsAsync( string debuggeeId, CancellationToken cancellationToken) => ListActiveBreakpointsAsync( debuggeeId, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="debuggeeId"> /// Identifies the debuggee. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ListActiveBreakpointsResponse ListActiveBreakpoints( string debuggeeId, CallSettings callSettings = null) => ListActiveBreakpoints( new ListActiveBreakpointsRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), }, callSettings); /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ListActiveBreakpointsResponse> ListActiveBreakpointsAsync( ListActiveBreakpointsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ListActiveBreakpointsResponse ListActiveBreakpoints( ListActiveBreakpointsRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="debuggeeId"> /// Identifies the debuggee being debugged. /// </param> /// <param name="breakpoint"> /// Updated breakpoint information. /// The field `id` must be set. /// The agent must echo all Breakpoint specification fields in the update. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<UpdateActiveBreakpointResponse> UpdateActiveBreakpointAsync( string debuggeeId, Breakpoint breakpoint, CallSettings callSettings = null) => UpdateActiveBreakpointAsync( new UpdateActiveBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), Breakpoint = GaxPreconditions.CheckNotNull(breakpoint, nameof(breakpoint)), }, callSettings); /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="debuggeeId"> /// Identifies the debuggee being debugged. /// </param> /// <param name="breakpoint"> /// Updated breakpoint information. /// The field `id` must be set. /// The agent must echo all Breakpoint specification fields in the update. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<UpdateActiveBreakpointResponse> UpdateActiveBreakpointAsync( string debuggeeId, Breakpoint breakpoint, CancellationToken cancellationToken) => UpdateActiveBreakpointAsync( debuggeeId, breakpoint, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="debuggeeId"> /// Identifies the debuggee being debugged. /// </param> /// <param name="breakpoint"> /// Updated breakpoint information. /// The field `id` must be set. /// The agent must echo all Breakpoint specification fields in the update. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual UpdateActiveBreakpointResponse UpdateActiveBreakpoint( string debuggeeId, Breakpoint breakpoint, CallSettings callSettings = null) => UpdateActiveBreakpoint( new UpdateActiveBreakpointRequest { DebuggeeId = GaxPreconditions.CheckNotNullOrEmpty(debuggeeId, nameof(debuggeeId)), Breakpoint = GaxPreconditions.CheckNotNull(breakpoint, nameof(breakpoint)), }, callSettings); /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<UpdateActiveBreakpointResponse> UpdateActiveBreakpointAsync( UpdateActiveBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual UpdateActiveBreakpointResponse UpdateActiveBreakpoint( UpdateActiveBreakpointRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// Controller2 client wrapper implementation, for convenient use. /// </summary> public sealed partial class Controller2ClientImpl : Controller2Client { private readonly ApiCall<RegisterDebuggeeRequest, RegisterDebuggeeResponse> _callRegisterDebuggee; private readonly ApiCall<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse> _callListActiveBreakpoints; private readonly ApiCall<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse> _callUpdateActiveBreakpoint; /// <summary> /// Constructs a client wrapper for the Controller2 service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="Controller2Settings"/> used within this client </param> public Controller2ClientImpl(Controller2.Controller2Client grpcClient, Controller2Settings settings) { GrpcClient = grpcClient; Controller2Settings effectiveSettings = settings ?? Controller2Settings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callRegisterDebuggee = clientHelper.BuildApiCall<RegisterDebuggeeRequest, RegisterDebuggeeResponse>( GrpcClient.RegisterDebuggeeAsync, GrpcClient.RegisterDebuggee, effectiveSettings.RegisterDebuggeeSettings); _callListActiveBreakpoints = clientHelper.BuildApiCall<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>( GrpcClient.ListActiveBreakpointsAsync, GrpcClient.ListActiveBreakpoints, effectiveSettings.ListActiveBreakpointsSettings); _callUpdateActiveBreakpoint = clientHelper.BuildApiCall<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>( GrpcClient.UpdateActiveBreakpointAsync, GrpcClient.UpdateActiveBreakpoint, effectiveSettings.UpdateActiveBreakpointSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(Controller2.Controller2Client grpcClient, Controller2Settings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC Controller2 client. /// </summary> public override Controller2.Controller2Client GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_RegisterDebuggeeRequest(ref RegisterDebuggeeRequest request, ref CallSettings settings); partial void Modify_ListActiveBreakpointsRequest(ref ListActiveBreakpointsRequest request, ref CallSettings settings); partial void Modify_UpdateActiveBreakpointRequest(ref UpdateActiveBreakpointRequest request, ref CallSettings settings); /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<RegisterDebuggeeResponse> RegisterDebuggeeAsync( RegisterDebuggeeRequest request, CallSettings callSettings = null) { Modify_RegisterDebuggeeRequest(ref request, ref callSettings); return _callRegisterDebuggee.Async(request, callSettings); } /// <summary> /// Registers the debuggee with the controller service. /// /// All agents attached to the same application must call this method with /// exactly the same request content to get back the same stable `debuggee_id`. /// Agents should call this method again whenever `google.rpc.Code.NOT_FOUND` /// is returned from any controller method. /// /// This protocol allows the controller service to disable debuggees, recover /// from data loss, or change the `debuggee_id` format. Agents must handle /// `debuggee_id` value changing upon re-registration. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override RegisterDebuggeeResponse RegisterDebuggee( RegisterDebuggeeRequest request, CallSettings callSettings = null) { Modify_RegisterDebuggeeRequest(ref request, ref callSettings); return _callRegisterDebuggee.Sync(request, callSettings); } /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<ListActiveBreakpointsResponse> ListActiveBreakpointsAsync( ListActiveBreakpointsRequest request, CallSettings callSettings = null) { Modify_ListActiveBreakpointsRequest(ref request, ref callSettings); return _callListActiveBreakpoints.Async(request, callSettings); } /// <summary> /// Returns the list of all active breakpoints for the debuggee. /// /// The breakpoint specification (`location`, `condition`, and `expressions` /// fields) is semantically immutable, although the field values may /// change. For example, an agent may update the location line number /// to reflect the actual line where the breakpoint was set, but this /// doesn't change the breakpoint semantics. /// /// This means that an agent does not need to check if a breakpoint has changed /// when it encounters the same breakpoint on a successive call. /// Moreover, an agent should remember the breakpoints that are completed /// until the controller removes them from the active list to avoid /// setting those breakpoints again. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override ListActiveBreakpointsResponse ListActiveBreakpoints( ListActiveBreakpointsRequest request, CallSettings callSettings = null) { Modify_ListActiveBreakpointsRequest(ref request, ref callSettings); return _callListActiveBreakpoints.Sync(request, callSettings); } /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<UpdateActiveBreakpointResponse> UpdateActiveBreakpointAsync( UpdateActiveBreakpointRequest request, CallSettings callSettings = null) { Modify_UpdateActiveBreakpointRequest(ref request, ref callSettings); return _callUpdateActiveBreakpoint.Async(request, callSettings); } /// <summary> /// Updates the breakpoint state or mutable fields. /// The entire Breakpoint message must be sent back to the controller service. /// /// Updates to active breakpoint fields are only allowed if the new value /// does not change the breakpoint specification. Updates to the `location`, /// `condition` and `expressions` fields should not alter the breakpoint /// semantics. These may only make changes such as canonicalizing a value /// or snapping the location to the correct line of code. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override UpdateActiveBreakpointResponse UpdateActiveBreakpoint( UpdateActiveBreakpointRequest request, CallSettings callSettings = null) { Modify_UpdateActiveBreakpointRequest(ref request, ref callSettings); return _callUpdateActiveBreakpoint.Sync(request, callSettings); } } // Partial classes to enable page-streaming }
/* Bullet for XNA Copyright (c) 2003-2007 Vsevolod Klementjev http://www.codeplex.com/xnadevru Bullet original C++ version Copyright (c) 2003-2007 Erwin Coumans http://bulletphysics.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Generic; using System.Text; namespace XnaDevRu.BulletX.LinearMath { internal class Vector3 : QuadWord { public Vector3() { } public Vector3(float x, float y, float z) : base(x, y, z) { } public void SetInterpolate3(Vector3 a, Vector3 b, float c) { float s = 1.0f - c; X = s * a.X + c * b.X; Y = s * a.Y + c * b.Y; Z = s * a.Z + c * b.Z; } public float LengthSquared() { return Dot(this, this); } public float Length() { return (float)Math.Sqrt(LengthSquared()); } public int MinAxis() { return X < Y ? (X < Z ? 0 : 2) : (Y < Z ? 1 : 2); } public int MaxAxis() { return X < Y ? (Y < Z ? 2 : 1) : (X < Z ? 2 : 0); } public int FurthestAxis() { return Absolute(this).MinAxis(); } public int ClosestAxis() { return Absolute(this).MaxAxis(); } public Vector3 Rotate(Vector3 axis, float angle) { Vector3 o = axis * Dot(axis, this); Vector3 x = this - o; Vector3 y = Cross(axis, this); return (o + x * (float)Math.Cos(angle) + y * (float)Math.Sin(angle)); } public static Vector3 Lerp(Vector3 a, Vector3 b, float c) { return new Vector3( a.X + (b.X - a.X) * c, a.Y + (b.Y - a.Y) * c, a.Z + (b.Z - a.Z) * c); } public static float Angle(Vector3 a, Vector3 b) { float s = (float)Math.Sqrt(a.LengthSquared() * b.LengthSquared()); if (s == 0) throw new DivideByZeroException(); return (float)Math.Acos(Dot(a, b) / s); } public static Vector3 Absolute(Vector3 a) { return new Vector3( Math.Abs(a.X), Math.Abs(a.Y), Math.Abs(a.Z)); } public static Vector3 Normalize(Vector3 a) { return a / a.Length(); } public static Vector3 Cross(Vector3 a, Vector3 b) { return new Vector3( a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X); } public static float Dot(Vector3 a, Vector3 b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } public static float Triple(Vector3 a, Vector3 b, Vector3 c) { return a.X * (b.Y * c.Z - b.Z * c.Y) + a.Y * (b.Z * c.X - b.X * c.Z) + a.Z * (b.X * c.Y - b.Y * c.X); } public static float Distance(Vector3 a, Vector3 b) { return (b - a).Length(); } public static float DistanceSquared(Vector3 a, Vector3 b) { return (b - a).LengthSquared(); } public static Vector3 Rotate(Vector3 a, Vector3 axis, float angle) { Vector3 o = axis * Dot(axis, a); Vector3 x = a - o; Vector3 y = Cross(axis, a); return (o + x * (float)Math.Cos(angle) + y * (float)Math.Sin(angle)); } public static Vector3 operator +(Vector3 a, Vector3 b) { return new Vector3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } public static Vector3 operator -(Vector3 a, Vector3 b) { return new Vector3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static Vector3 operator -(Vector3 a) { return new Vector3(-a.X, -a.Y, -a.Z); } public static Vector3 operator *(float b, Vector3 a) { return new Vector3(a.X * b, a.Y * b, a.Z * b); } public static Vector3 operator *(Vector3 a, float b) { return new Vector3(a.X * b, a.Y * b, a.Z * b); } public static Vector3 operator *(Vector3 a, Vector3 b) { return new Vector3(a.X * b.X, a.Y * b.Y, a.Z * b.Z); } public static Vector3 operator /(Vector3 a, float b) { if (b == 0) throw new DivideByZeroException(); return new Vector3(a.X / b, a.Y / b, a.Z / b); } public static Vector3 operator /(Vector3 a, Vector3 b) { if (b.X == 0 || b.Y == 0 || b.Z == 0) throw new DivideByZeroException(); return new Vector3(a.X / b.X, a.Y / b.Y, a.Z / b.Z); } public static bool operator ==(Vector3 a, Vector3 b) { return a.X == b.X && a.Y == b.Y && a.Z == b.Z; } public static bool operator !=(Vector3 a, Vector3 b) { return a.X != b.X || a.Y != b.Y || a.Z != b.Z; } public static explicit operator Microsoft.Xna.Framework.Vector3(Vector3 a) { return new Microsoft.Xna.Framework.Vector3(a.X, a.Y, a.Z); } public override bool Equals(object obj) { return object.Equals(this, obj); } public override int GetHashCode() { return X.GetHashCode() & Y.GetHashCode() & Z.GetHashCode(); } public override string ToString() { return string.Format("{0}, {1}, {2}", X, Y, Z); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using ViewROI; using HalconDotNet; namespace SmartWindow1 { /// <summary> /// This project demonstrates how to use the routines of the HWndCtrl class /// to control the functions like moving and zooming. There are two /// ways of accessing this feature. One is to use GUI Components like /// sliders and numeric devices to receive events for the motion and /// scaling factor. /// Before forwarding the GUI handle events to the HWndCtrl, /// you have to specify the range of values that is used for the GUI /// components by providing an array containing /// the minimum and the maximum value of the GUI component, as well as /// its initial value. As an alternative, you can let the HWndCtrl use the /// mouse device as a trigger. The example SmartWindow2Form shows how to /// do this. /// </summary> public class SmartWindow1Form : System.Windows.Forms.Form { private System.Windows.Forms.TrackBar XTrackBar; private System.Windows.Forms.Label label2; private System.ComponentModel.Container components = null; private HWndCtrl hWndControl; private System.Windows.Forms.TrackBar YTrackBar; private System.Windows.Forms.NumericUpDown ZoomUpDown; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private HalconDotNet.HWindowControl viewPort; private System.Windows.Forms.Button resetButton; public SmartWindow1Form() { InitializeComponent(); } 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.XTrackBar = new System.Windows.Forms.TrackBar(); this.YTrackBar = new System.Windows.Forms.TrackBar(); this.ZoomUpDown = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.resetButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.viewPort = new HalconDotNet.HWindowControl(); ((System.ComponentModel.ISupportInitialize)(this.XTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.YTrackBar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ZoomUpDown)).BeginInit(); this.SuspendLayout(); // // XTrackBar // this.XTrackBar.Location = new System.Drawing.Point(48, 488); this.XTrackBar.Maximum = 100; this.XTrackBar.Name = "XTrackBar"; this.XTrackBar.Size = new System.Drawing.Size(616, 42); this.XTrackBar.TabIndex = 1; this.XTrackBar.TickStyle = System.Windows.Forms.TickStyle.Both; this.XTrackBar.Value = 50; this.XTrackBar.Scroll += new System.EventHandler(this.XTrackBar_Scroll); // // YTrackBar // this.YTrackBar.Location = new System.Drawing.Point(680, 16); this.YTrackBar.Maximum = 100; this.YTrackBar.Name = "YTrackBar"; this.YTrackBar.Orientation = System.Windows.Forms.Orientation.Vertical; this.YTrackBar.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.YTrackBar.Size = new System.Drawing.Size(42, 464); this.YTrackBar.TabIndex = 2; this.YTrackBar.TickStyle = System.Windows.Forms.TickStyle.Both; this.YTrackBar.Value = 50; this.YTrackBar.Scroll += new System.EventHandler(this.YTrackBar_Scroll); // // ZoomUpDown // this.ZoomUpDown.Increment = new System.Decimal(new int[] { 10, 0, 0, 0}); this.ZoomUpDown.Location = new System.Drawing.Point(744, 512); this.ZoomUpDown.Maximum = new System.Decimal(new int[] { 1600, 0, 0, 0}); this.ZoomUpDown.Minimum = new System.Decimal(new int[] { 1, 0, 0, 0}); this.ZoomUpDown.Name = "ZoomUpDown"; this.ZoomUpDown.Size = new System.Drawing.Size(56, 20); this.ZoomUpDown.TabIndex = 4; this.ZoomUpDown.Value = new System.Decimal(new int[] { 100, 0, 0, 0}); this.ZoomUpDown.ValueChanged += new System.EventHandler(this.ZoomUpDown_ValueChanged); // // label2 // this.label2.Location = new System.Drawing.Point(736, 488); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 16); this.label2.TabIndex = 5; this.label2.Text = "Zoomfactor"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // resetButton // this.resetButton.Location = new System.Drawing.Point(784, 24); this.resetButton.Name = "resetButton"; this.resetButton.Size = new System.Drawing.Size(96, 48); this.resetButton.TabIndex = 6; this.resetButton.Text = "Reset View"; this.resetButton.Click += new System.EventHandler(this.resetButton_Click); // // label1 // this.label1.Location = new System.Drawing.Point(56, 536); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(64, 24); this.label1.TabIndex = 7; this.label1.Text = "X-Axis"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label3 // this.label3.Location = new System.Drawing.Point(728, 24); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 24); this.label3.TabIndex = 8; this.label3.Text = "Y-Axis"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label4 // this.label4.Location = new System.Drawing.Point(808, 512); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(24, 24); this.label4.TabIndex = 9; this.label4.Text = "%"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // viewPort // this.viewPort.BackColor = System.Drawing.Color.Black; this.viewPort.BorderColor = System.Drawing.Color.Black; this.viewPort.ImagePart = new System.Drawing.Rectangle(0, 0, 640, 480); this.viewPort.Location = new System.Drawing.Point(56, 24); this.viewPort.Name = "viewPort"; this.viewPort.Size = new System.Drawing.Size(608, 440); this.viewPort.TabIndex = 10; this.viewPort.WindowSize = new System.Drawing.Size(608, 440); // // SmartWindow1Form // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(896, 573); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.viewPort, this.label4, this.label1, this.resetButton, this.label2, this.ZoomUpDown, this.YTrackBar, this.XTrackBar, this.label3}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "SmartWindow1Form"; this.Text = "SmartWindow"; this.Load += new System.EventHandler(this.SmartWindow1Form_Load); ((System.ComponentModel.ISupportInitialize)(this.XTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.YTrackBar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ZoomUpDown)).EndInit(); this.ResumeLayout(false); } #endregion [STAThread] static void Main() { Application.Run(new SmartWindow1Form()); } /**************************************************************************/ /* Setup the GUI for the SmartWindow application in terms of * registering the Window Control class and setting up all values * and flags to use the GUI based viewfunctions (zoom and move) **************************************************************************/ private void SmartWindow1Form_Load(object sender, System.EventArgs e) { hWndControl = new HWndCtrl(viewPort); Init(); } private void Init() { String fileName = "patras"; HImage image; try { image = new HImage(fileName); } catch(HOperatorException) { MessageBox.Show("Problem occured while reading file!", "SmartWindow1", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } hWndControl.addIconicVar(image); hWndControl.repaint(); hWndControl.setGUICompRangeX( new int[]{ XTrackBar.Minimum, XTrackBar.Maximum}, XTrackBar.Value ); hWndControl.setGUICompRangeY( new int[]{ YTrackBar.Minimum, YTrackBar.Maximum}, YTrackBar.Maximum-YTrackBar.Value); } /**************************************************************************/ /* Adjust the view using GUI components for moving along the x and y * direction and for changing the zoom of the image displayed * *************************************************************************/ private void XTrackBar_Scroll(object sender, System.EventArgs e) { hWndControl.moveXByGUIHandle(XTrackBar.Value); } private void YTrackBar_Scroll(object sender, System.EventArgs e) { hWndControl.moveYByGUIHandle(YTrackBar.Maximum-YTrackBar.Value); } private void ZoomUpDown_ValueChanged(object sender, System.EventArgs e) { hWndControl.zoomByGUIHandle((int)ZoomUpDown.Value); } /**************************************************************************/ /* Reset the view to its initial setting * *************************************************************************/ private void resetButton_Click(object sender, System.EventArgs e) { XTrackBar.Value = 50; YTrackBar.Value = 50; ZoomUpDown.Value = 100; hWndControl.resetGUIInitValues(XTrackBar.Value, (YTrackBar.Maximum-YTrackBar.Value)); hWndControl.resetWindow(); hWndControl.repaint(); } }//end of class }//end of namespace
/* Josip Medved <[email protected]> * www.medo64.com * MIT License */ //2017-08-15: Replacing ThreadStatic with Lazy<RandomNumberGenerator>. //2016-01-08: Added ANSIX923 and ISO10126 padding modes. //2015-12-27: Initial version. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; namespace Medo.Security.Cryptography { /// <summary> /// Twofish algorithm implementation. /// This class cannot be inherited. /// </summary> /// <remarks>https://www.schneier.com/twofish.html</remarks> public sealed class TwofishManaged : SymmetricAlgorithm { /// <summary> /// Initializes a new instance. /// </summary> public TwofishManaged() : base() { base.KeySizeValue = 256; base.BlockSizeValue = 128; base.FeedbackSizeValue = base.BlockSizeValue; base.LegalBlockSizesValue = new KeySizes[] { new KeySizes(128, 128, 0) }; base.LegalKeySizesValue = new KeySizes[] { new KeySizes(128, 256, 64) }; base.Mode = CipherMode.CBC; //same as default base.Padding = PaddingMode.PKCS7; } /// <summary> /// Creates a symmetric decryptor object. /// </summary> /// <param name="rgbKey">The secret key to be used for the symmetric algorithm. The key size must be 128, 192, or 256 bits.</param> /// <param name="rgbIV">The IV to be used for the symmetric algorithm.</param> public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { if (rgbKey == null) { throw new ArgumentNullException("rgbKey", "Key cannot be null."); } if (rgbKey.Length != KeySize / 8) { throw new ArgumentOutOfRangeException("rgbKey", "Key size mismatch."); } if (Mode == CipherMode.CBC) { if (rgbIV == null) { throw new ArgumentNullException("rgbIV", "IV cannot be null."); } if (rgbIV.Length != 16) { throw new ArgumentOutOfRangeException("rgbIV", "Invalid IV size."); } } return NewEncryptor(rgbKey, Mode, rgbIV, TwofishManagedTransformMode.Decrypt); } /// <summary> /// Creates a symmetric encryptor object. /// </summary> /// <param name="rgbKey">The secret key to be used for the symmetric algorithm. The key size must be 128, 192, or 256 bits.</param> /// <param name="rgbIV">The IV to be used for the symmetric algorithm.</param> public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { if (rgbKey == null) { throw new ArgumentNullException("rgbKey", "Key cannot be null."); } if (rgbKey.Length != KeySize / 8) { throw new ArgumentOutOfRangeException("rgbKey", "Key size mismatch."); } if (Mode == CipherMode.CBC) { if (rgbIV == null) { throw new ArgumentNullException("rgbIV", "IV cannot be null."); } if (rgbIV.Length != 16) { throw new ArgumentOutOfRangeException("rgbIV", "Invalid IV size."); } } return NewEncryptor(rgbKey, Mode, rgbIV, TwofishManagedTransformMode.Encrypt); } /// <summary> /// Generates a random initialization vector to be used for the algorithm. /// </summary> public override void GenerateIV() { IVValue = new byte[FeedbackSizeValue / 8]; Rng.Value.GetBytes(IVValue); } /// <summary> /// Generates a random key to be used for the algorithm. /// </summary> public override void GenerateKey() { KeyValue = new byte[KeySizeValue / 8]; Rng.Value.GetBytes(KeyValue); } /// <summary> /// Gets or sets the mode for operation of the symmetric algorithm. /// </summary> public override CipherMode Mode { get { return base.Mode; } set { if ((value != CipherMode.CBC) && (value != CipherMode.ECB)) { throw new CryptographicException("Cipher mode is not supported."); } base.Mode = value; } } /// <summary> /// Gets or sets the mode for operation of the symmetric algorithm. /// </summary> public override PaddingMode Padding { get { return base.Padding; } set { switch (value) { case PaddingMode.None: case PaddingMode.PKCS7: case PaddingMode.Zeros: case PaddingMode.ANSIX923: case PaddingMode.ISO10126: base.Padding = value; break; default: throw new CryptographicException("Padding mode is not supported."); } } } #region Private private static readonly Lazy<RandomNumberGenerator> Rng = new Lazy<RandomNumberGenerator>(() => RandomNumberGenerator.Create()); private ICryptoTransform NewEncryptor(byte[] rgbKey, CipherMode mode, byte[] rgbIV, TwofishManagedTransformMode encryptMode) { if (rgbKey == null) { rgbKey = new byte[KeySize / 8]; Rng.Value.GetBytes(rgbKey); } if ((mode != CipherMode.ECB) && (rgbIV == null)) { rgbIV = new byte[KeySize / 8]; Rng.Value.GetBytes(rgbIV); } return new TwofishManagedTransform(rgbKey, mode, rgbIV, encryptMode, Padding); } #endregion } /// <summary> /// Performs a cryptographic transformation of data using the Twofish algorithm. /// This class cannot be inherited. /// </summary> public sealed class TwofishManagedTransform : ICryptoTransform { internal TwofishManagedTransform(byte[] key, CipherMode mode, byte[] iv, TwofishManagedTransformMode transformMode, PaddingMode paddingMode) { TransformMode = transformMode; PaddingMode = paddingMode; var key32 = new uint[key.Length / 4]; Buffer.BlockCopy(key, 0, key32, 0, key.Length); if (iv != null) { var iv32 = new uint[iv.Length / 4]; Buffer.BlockCopy(iv, 0, iv32, 0, iv.Length); Implementation = new TwofishImplementation(key32, iv32, mode); } else { Implementation = new TwofishImplementation(key32, null, mode); } } private readonly TwofishManagedTransformMode TransformMode; private readonly PaddingMode PaddingMode; private readonly TwofishImplementation Implementation; /// <summary> /// Gets a value indicating whether the current transform can be reused. /// </summary> public bool CanReuseTransform { get { return false; } } /// <summary> /// Gets a value indicating whether multiple blocks can be transformed. /// </summary> public bool CanTransformMultipleBlocks { get { return true; } } /// <summary> /// Gets the input block size (in bytes). /// </summary> public int InputBlockSize { get { return 16; } } //block is always 128 bits /// <summary> /// Gets the output block size (in bytes). /// </summary> public int OutputBlockSize { get { return 16; } } //block is always 128 bits /// <summary> /// Releases resources. /// </summary> public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { Implementation.Dispose(); if (PaddingBuffer != null) { Array.Clear(PaddingBuffer, 0, PaddingBuffer.Length); } } } [ThreadStatic()] private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create(); private byte[] PaddingBuffer; //used to store last block under decrypting as to work around CryptoStream implementation details. /// <summary> /// Transforms the specified region of the input byte array and copies the resulting transform to the specified region of the output byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the input byte array to use as data.</param> /// <param name="outputBuffer">The output to which to write the transform.</param> /// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2233:OperationsShouldNotOverflow", MessageId = "outputOffset+16", Justification = "Value will never cause the arithmetic operation to overflow.")] public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer", "Input buffer cannot be null."); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset", "Offset must be non-negative number."); } if ((inputCount <= 0) || (inputCount % 16 != 0) || (inputCount > inputBuffer.Length)) { throw new ArgumentOutOfRangeException("inputCount", "Invalid input count."); } if ((inputBuffer.Length - inputCount) < inputOffset) { throw new ArgumentOutOfRangeException("inputCount", "Invalid input length."); } if (outputBuffer == null) { throw new ArgumentNullException("outputBuffer", "Output buffer cannot be null."); } if (outputOffset + inputCount > outputBuffer.Length) { throw new ArgumentOutOfRangeException("outputOffset", "Insufficient buffer."); } if (TransformMode == TwofishManagedTransformMode.Encrypt) { #region Encrypt for (var i = 0; i < inputCount; i += 16) { Implementation.BlockEncrypt(inputBuffer, inputOffset + i, outputBuffer, outputOffset + i); } return inputCount; #endregion } else { #region Decrypt var bytesWritten = 0; if (PaddingBuffer != null) { Implementation.BlockDecrypt(PaddingBuffer, 0, outputBuffer, outputOffset); outputOffset += 16; bytesWritten += 16; } for (var i = 0; i < inputCount - 16; i += 16) { Implementation.BlockDecrypt(inputBuffer, inputOffset + i, outputBuffer, outputOffset); outputOffset += 16; bytesWritten += 16; } if (PaddingMode == PaddingMode.None) { Implementation.BlockDecrypt(inputBuffer, inputOffset + inputCount - 16, outputBuffer, outputOffset); bytesWritten += 16; } else { //save last block without processing because decryption otherwise cannot detect padding in CryptoStream if (PaddingBuffer == null) { PaddingBuffer = new byte[16]; } Buffer.BlockCopy(inputBuffer, inputOffset + inputCount - 16, PaddingBuffer, 0, 16); } return bytesWritten; #endregion } } /// <summary> /// Transforms the specified region of the specified byte array. /// </summary> /// <param name="inputBuffer">The input for which to compute the transform.</param> /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the byte array to use as data.</param> public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) { throw new ArgumentNullException("inputBuffer", "Input buffer cannot be null."); } if (inputOffset < 0) { throw new ArgumentOutOfRangeException("inputOffset", "Offset must be non-negative number."); } if ((inputCount < 0) || (inputCount > inputBuffer.Length)) { throw new ArgumentOutOfRangeException("inputCount", "Invalid input count."); } if ((inputBuffer.Length - inputCount) < inputOffset) { throw new ArgumentOutOfRangeException("inputCount", "Invalid input length."); } if (TransformMode == TwofishManagedTransformMode.Encrypt) { #region Encrypt int paddedLength; byte[] paddedInputBuffer; int paddedInputOffset; if (PaddingMode == PaddingMode.PKCS7) { paddedLength = inputCount / 16 * 16 + 16; //to round to next whole block paddedInputBuffer = new byte[paddedLength]; paddedInputOffset = 0; Buffer.BlockCopy(inputBuffer, inputOffset, paddedInputBuffer, 0, inputCount); var added = (byte)(paddedLength - inputCount); for (var i = inputCount; i < inputCount + added; i++) { paddedInputBuffer[i] = added; } } else if (PaddingMode == PaddingMode.Zeros) { paddedLength = (inputCount + 15) / 16 * 16; //to round to next whole block paddedInputBuffer = new byte[paddedLength]; paddedInputOffset = 0; Buffer.BlockCopy(inputBuffer, inputOffset, paddedInputBuffer, 0, inputCount); } else if (PaddingMode == PaddingMode.ANSIX923) { paddedLength = inputCount / 16 * 16 + 16; //to round to next whole block paddedInputBuffer = new byte[paddedLength]; paddedInputOffset = 0; Buffer.BlockCopy(inputBuffer, inputOffset, paddedInputBuffer, 0, inputCount); paddedInputBuffer[paddedInputBuffer.Length - 1] = (byte)(paddedLength - inputCount); } else if (PaddingMode == PaddingMode.ISO10126) { paddedLength = inputCount / 16 * 16 + 16; //to round to next whole block paddedInputBuffer = new byte[paddedLength]; Rng.GetBytes(paddedInputBuffer); paddedInputOffset = 0; Buffer.BlockCopy(inputBuffer, inputOffset, paddedInputBuffer, 0, inputCount); paddedInputBuffer[paddedInputBuffer.Length - 1] = (byte)(paddedLength - inputCount); } else { if (inputCount % 16 != 0) { throw new ArgumentOutOfRangeException("inputCount", "Invalid input count for a given padding."); } paddedLength = inputCount; paddedInputBuffer = inputBuffer; paddedInputOffset = inputOffset; } var outputBuffer = new byte[paddedLength]; for (var i = 0; i < paddedLength; i += 16) { Implementation.BlockEncrypt(paddedInputBuffer, paddedInputOffset + i, outputBuffer, i); } return outputBuffer; #endregion } else { #region Decrypt if (inputCount % 16 != 0) { throw new ArgumentOutOfRangeException("inputCount", "Invalid input count."); } var outputBuffer = new byte[inputCount + ((PaddingBuffer != null) ? 16 : 0)]; var outputOffset = 0; if (PaddingBuffer != null) { //process leftover padding buffer to keep CryptoStream happy Implementation.BlockDecrypt(PaddingBuffer, 0, outputBuffer, 0); outputOffset = 16; } for (var i = 0; i < inputCount; i += 16) { Implementation.BlockDecrypt(inputBuffer, inputOffset + i, outputBuffer, outputOffset + i); } return RemovePadding(outputBuffer, PaddingMode); #endregion } } private static byte[] RemovePadding(byte[] outputBuffer, PaddingMode paddingMode) { if (paddingMode == PaddingMode.PKCS7) { var padding = outputBuffer[outputBuffer.Length - 1]; if ((padding < 1) || (padding > 16)) { throw new CryptographicException("Invalid padding."); } for (var i = outputBuffer.Length - padding; i < outputBuffer.Length; i++) { if (outputBuffer[i] != padding) { throw new CryptographicException("Invalid padding."); } } var newOutputBuffer = new byte[outputBuffer.Length - padding]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return newOutputBuffer; } else if (paddingMode == PaddingMode.Zeros) { var newOutputLength = outputBuffer.Length; for (var i = outputBuffer.Length - 1; i >= outputBuffer.Length - 16; i--) { if (outputBuffer[i] != 0) { newOutputLength = i + 1; break; } } if (newOutputLength == outputBuffer.Length) { return outputBuffer; } else { var newOutputBuffer = new byte[newOutputLength]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return newOutputBuffer; } } else if (paddingMode == PaddingMode.ANSIX923) { var padding = outputBuffer[outputBuffer.Length - 1]; if ((padding < 1) || (padding > 16)) { throw new CryptographicException("Invalid padding."); } for (var i = outputBuffer.Length - padding; i < outputBuffer.Length - 1; i++) { if (outputBuffer[i] != 0) { throw new CryptographicException("Invalid padding."); } } var newOutputBuffer = new byte[outputBuffer.Length - padding]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return newOutputBuffer; } else if (paddingMode == PaddingMode.ISO10126) { var padding = outputBuffer[outputBuffer.Length - 1]; if ((padding < 1) || (padding > 16)) { throw new CryptographicException("Invalid padding."); } var newOutputBuffer = new byte[outputBuffer.Length - padding]; Buffer.BlockCopy(outputBuffer, 0, newOutputBuffer, 0, newOutputBuffer.Length); return newOutputBuffer; } else { return outputBuffer; } } private class TwofishImplementation : IDisposable { public TwofishImplementation(uint[] key, uint[] iv, CipherMode cipherMode) { Key = new DWord[key.Length]; for (var i = 0; i < Key.Length; i++) { Key[i] = (DWord)key[i]; } if (iv != null) { IV = new DWord[iv.Length]; for (var i = 0; i < IV.Length; i++) { IV[i] = (DWord)iv[i]; } } CipherMode = cipherMode; ReKey(); } private readonly DWord[] Key; private readonly DWord[] IV; private readonly CipherMode CipherMode; private const int BlockSize = 128; //number of bits per block private const int Rounds = 16; //default number of rounds for 128/192/256-bit keys private const int MaxKeyBits = 256; //max number of bits of key private const int InputWhiten = 0; private const int OutputWhiten = (InputWhiten + BlockSize / 32); private const int RoundSubkeys = (OutputWhiten + BlockSize / 32); private const int TotalSubkeys = (RoundSubkeys + 2 * Rounds); private readonly DWord[] SBoxKeys = new DWord[MaxKeyBits / 64]; //key bits used for S-boxes private readonly DWord[] SubKeys = new DWord[TotalSubkeys]; //round subkeys, input/output whitening bits public void Dispose() { Array.Clear(Key, 0, Key.Length); if (IV != null) { Array.Clear(IV, 0, IV.Length); } Array.Clear(SBoxKeys, 0, SBoxKeys.Length); Array.Clear(SubKeys, 0, SubKeys.Length); } #region ReKey private const int SubkeyStep = 0x02020202; private const int SubkeyBump = 0x01010101; private const int SubkeyRotateLeft = 9; /// <summary> /// Initialize the Twofish key schedule from key32 /// </summary> private void ReKey() { BuildMds(); //built only first time it is accessed var k32e = new DWord[Key.Length / 2]; var k32o = new DWord[Key.Length / 2]; //even/odd key dwords var k64Cnt = Key.Length / 2; for (var i = 0; i < k64Cnt; i++) { //split into even/odd key dwords k32e[i] = Key[2 * i]; k32o[i] = Key[2 * i + 1]; SBoxKeys[k64Cnt - 1 - i] = ReedSolomonMdsEncode(k32e[i], k32o[i]); //compute S-box keys using (12,8) Reed-Solomon code over GF(256) } var subkeyCnt = RoundSubkeys + 2 * Rounds; var keyLen = Key.Length * 4 * 8; for (var i = 0; i < subkeyCnt / 2; i++) { //compute round subkeys for PHT var A = F32((DWord)(i * SubkeyStep), k32e, keyLen); //A uses even key dwords var B = F32((DWord)(i * SubkeyStep + SubkeyBump), k32o, keyLen); //B uses odd key dwords B = RotateLeft(B, 8); SubKeys[2 * i] = A + B; //combine with a PHT SubKeys[2 * i + 1] = RotateLeft(A + 2 * B, SubkeyRotateLeft); } } #endregion #region Encrypt/decrypt /// <summary> /// Encrypt block(s) of data using Twofish. /// </summary> internal void BlockEncrypt(byte[] inputBuffer, int inputOffset, byte[] outputBuffer, int outputBufferOffset) { var x = new DWord[BlockSize / 32]; for (var i = 0; i < BlockSize / 32; i++) { //copy in the block, add whitening x[i] = new DWord(inputBuffer, inputOffset + i * 4) ^ SubKeys[InputWhiten + i]; if (CipherMode == CipherMode.CBC) { x[i] ^= IV[i]; } } var keyLen = Key.Length * 4 * 8; for (var r = 0; r < Rounds; r++) { //main Twofish encryption loop var t0 = F32(x[0], SBoxKeys, keyLen); var t1 = F32(RotateLeft(x[1], 8), SBoxKeys, keyLen); x[3] = RotateLeft(x[3], 1); x[2] ^= t0 + t1 + SubKeys[RoundSubkeys + 2 * r]; //PHT, round keys x[3] ^= t0 + 2 * t1 + SubKeys[RoundSubkeys + 2 * r + 1]; x[2] = RotateRight(x[2], 1); if (r < Rounds - 1) { //swap for next round var tmp = x[0]; x[0] = x[2]; x[2] = tmp; tmp = x[1]; x[1] = x[3]; x[3] = tmp; } } for (var i = 0; i < BlockSize / 32; i++) { //copy out, with whitening var outValue = x[i] ^ SubKeys[OutputWhiten + i]; outputBuffer[outputBufferOffset + i * 4 + 0] = outValue.B0; outputBuffer[outputBufferOffset + i * 4 + 1] = outValue.B1; outputBuffer[outputBufferOffset + i * 4 + 2] = outValue.B2; outputBuffer[outputBufferOffset + i * 4 + 3] = outValue.B3; if (CipherMode == CipherMode.CBC) { IV[i] = outValue; } } } /// <summary> /// Decrypt block(s) of data using Twofish. /// </summary> internal void BlockDecrypt(byte[] inputBuffer, int inputOffset, byte[] outputBuffer, int outputBufferOffset) { var x = new DWord[BlockSize / 32]; var input = new DWord[BlockSize / 32]; for (var i = 0; i < BlockSize / 32; i++) { //copy in the block, add whitening input[i] = new DWord(inputBuffer, inputOffset + i * 4); x[i] = input[i] ^ SubKeys[OutputWhiten + i]; } var keyLen = Key.Length * 4 * 8; for (var r = Rounds - 1; r >= 0; r--) { //main Twofish decryption loop var t0 = F32(x[0], SBoxKeys, keyLen); var t1 = F32(RotateLeft(x[1], 8), SBoxKeys, keyLen); x[2] = RotateLeft(x[2], 1); x[2] ^= t0 + t1 + SubKeys[RoundSubkeys + 2 * r]; //PHT, round keys x[3] ^= t0 + 2 * t1 + SubKeys[RoundSubkeys + 2 * r + 1]; x[3] = RotateRight(x[3], 1); if (r > 0) { //unswap, except for last round t0 = x[0]; x[0] = x[2]; x[2] = t0; t1 = x[1]; x[1] = x[3]; x[3] = t1; } } for (var i = 0; i < BlockSize / 32; i++) { //copy out, with whitening x[i] ^= SubKeys[InputWhiten + i]; if (CipherMode == CipherMode.CBC) { x[i] ^= IV[i]; IV[i] = input[i]; } outputBuffer[outputBufferOffset + i * 4 + 0] = x[i].B0; outputBuffer[outputBufferOffset + i * 4 + 1] = x[i].B1; outputBuffer[outputBufferOffset + i * 4 + 2] = x[i].B2; outputBuffer[outputBufferOffset + i * 4 + 3] = x[i].B3; } } #endregion #region F32 /// <summary> /// Run four bytes through keyed S-boxes and apply MDS matrix. /// </summary> private static DWord F32(DWord x, DWord[] k32, int keyLen) { if (keyLen >= 256) { x.B0 = (byte)(P8x8[P_04, x.B0] ^ k32[3].B0); x.B1 = (byte)(P8x8[P_14, x.B1] ^ k32[3].B1); x.B2 = (byte)(P8x8[P_24, x.B2] ^ k32[3].B2); x.B3 = (byte)(P8x8[P_34, x.B3] ^ k32[3].B3); } if (keyLen >= 192) { x.B0 = (byte)(P8x8[P_03, x.B0] ^ k32[2].B0); x.B1 = (byte)(P8x8[P_13, x.B1] ^ k32[2].B1); x.B2 = (byte)(P8x8[P_23, x.B2] ^ k32[2].B2); x.B3 = (byte)(P8x8[P_33, x.B3] ^ k32[2].B3); } if (keyLen >= 128) { x = MdsTable[0, P8x8[P_01, P8x8[P_02, x.B0] ^ k32[1].B0] ^ k32[0].B0] ^ MdsTable[1, P8x8[P_11, P8x8[P_12, x.B1] ^ k32[1].B1] ^ k32[0].B1] ^ MdsTable[2, P8x8[P_21, P8x8[P_22, x.B2] ^ k32[1].B2] ^ k32[0].B2] ^ MdsTable[3, P8x8[P_31, P8x8[P_32, x.B3] ^ k32[1].B3] ^ k32[0].B3]; } return x; } private static DWord RotateLeft(DWord x, int n) { return ((x << n) | (x >> (32 - n))); } private static DWord RotateRight(DWord x, int n) { return ((x >> n) | (x << (32 - n))); } private static readonly uint P_01 = 0; private static readonly uint P_02 = 0; private static readonly uint P_03 = (P_01 ^ 1); //"extend" to larger key sizes private static readonly uint P_04 = 1; private static readonly uint P_11 = 0; private static readonly uint P_12 = 1; private static readonly uint P_13 = (P_11 ^ 1); private static readonly uint P_14 = 0; private static readonly uint P_21 = 1; private static readonly uint P_22 = 0; private static readonly uint P_23 = (P_21 ^ 1); private static readonly uint P_24 = 0; private static readonly uint P_31 = 1; private static readonly uint P_32 = 1; private static readonly uint P_33 = (P_31 ^ 1); private static readonly uint P_34 = 1; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Member", Justification = "Multidimensional array does not waste space.")] private static readonly byte[,] P8x8 = { { 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48, 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23, 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82, 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C, 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61, 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B, 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1, 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66, 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7, 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA, 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71, 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8, 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7, 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2, 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90, 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB, 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF, 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B, 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64, 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A, 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A, 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02, 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D, 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72, 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8, 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4, 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00, 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0 }, { 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F, 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D, 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5, 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3, 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51, 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96, 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C, 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70, 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8, 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC, 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2, 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9, 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17, 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3, 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E, 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49, 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9, 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01, 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48, 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19, 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64, 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5, 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69, 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E, 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC, 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB, 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9, 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2, 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91 } }; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", MessageId = "Member", Justification = "Multidimensional array does not waste space.")] private static readonly DWord[,] MdsTable = new DWord[4, 256]; private static bool MdsTableBuilt = false; private static readonly object BuildMdsSyncLock = new object(); private static void BuildMds() { lock (BuildMdsSyncLock) { if (MdsTableBuilt) { return; } var m1 = new byte[2]; var mX = new byte[2]; var mY = new byte[4]; for (var i = 0; i < 256; i++) { m1[0] = P8x8[0, i]; /* compute all the matrix elements */ mX[0] = (byte)Mul_X(m1[0]); mY[0] = (byte)Mul_Y(m1[0]); m1[1] = P8x8[1, i]; mX[1] = (byte)Mul_X(m1[1]); mY[1] = (byte)Mul_Y(m1[1]); MdsTable[0, i].B0 = m1[1]; MdsTable[0, i].B1 = mX[1]; MdsTable[0, i].B2 = mY[1]; MdsTable[0, i].B3 = mY[1]; //SetMDS(0); MdsTable[1, i].B0 = mY[0]; MdsTable[1, i].B1 = mY[0]; MdsTable[1, i].B2 = mX[0]; MdsTable[1, i].B3 = m1[0]; //SetMDS(1); MdsTable[2, i].B0 = mX[1]; MdsTable[2, i].B1 = mY[1]; MdsTable[2, i].B2 = m1[1]; MdsTable[2, i].B3 = mY[1]; //SetMDS(2); MdsTable[3, i].B0 = mX[0]; MdsTable[3, i].B1 = m1[0]; MdsTable[3, i].B2 = mY[0]; MdsTable[3, i].B3 = mX[0]; //SetMDS(3); } MdsTableBuilt = true; } } #endregion #region Reed-Solomon private const uint RS_GF_FDBK = 0x14D; //field generator /// <summary> /// Use (12,8) Reed-Solomon code over GF(256) to produce a key S-box dword from two key material dwords. /// </summary> /// <param name="k0">1st dword</param> /// <param name="k1">2nd dword</param> private static DWord ReedSolomonMdsEncode(DWord k0, DWord k1) { var r = new DWord(); for (var i = 0; i < 2; i++) { r ^= (i > 0) ? k0 : k1; //merge in 32 more key bits for (var j = 0; j < 4; j++) { //shift one byte at a time var b = (byte)(r >> 24); var g2 = (byte)((b << 1) ^ (((b & 0x80) > 0) ? RS_GF_FDBK : 0)); var g3 = (byte)(((b >> 1) & 0x7F) ^ (((b & 1) > 0) ? RS_GF_FDBK >> 1 : 0) ^ g2); r.B3 = (byte)(r.B2 ^ g3); r.B2 = (byte)(r.B1 ^ g2); r.B1 = (byte)(r.B0 ^ g3); r.B0 = b; } } return r; } private static uint Mul_X(uint x) { return Mx_X(x); } private static uint Mul_Y(uint x) { return Mx_Y(x); } private static uint Mx_X(uint x) { return (uint)(x ^ LFSR2(x)); //5B } private static uint Mx_Y(uint x) { return (uint)(x ^ LFSR1(x) ^ LFSR2(x)); //EF } private const uint MDS_GF_FDBK = 0x169; //primitive polynomial for GF(256) private static uint LFSR1(uint x) { return (uint)((x >> 1) ^ (((x & 0x01) > 0) ? MDS_GF_FDBK / 2 : 0)); } static private uint LFSR2(uint x) { return (uint)((x >> 2) ^ (((x & 0x02) > 0) ? MDS_GF_FDBK / 2 : 0) ^ (((x & 0x01) > 0) ? MDS_GF_FDBK / 4 : 0)); } #endregion [DebuggerDisplay("{Value}")] [StructLayout(LayoutKind.Explicit)] private struct DWord { //makes extracting bytes from uint faster and looks better [FieldOffset(0)] public byte B0; [FieldOffset(1)] public byte B1; [FieldOffset(2)] public byte B2; [FieldOffset(3)] public byte B3; [FieldOffset(0)] private uint Value; private DWord(uint value) : this() { Value = value; } internal DWord(byte[] buffer, int offset) : this() { B0 = buffer[offset + 0]; B1 = buffer[offset + 1]; B2 = buffer[offset + 2]; B3 = buffer[offset + 3]; } public static explicit operator uint(DWord expr) { return expr.Value; } public static explicit operator DWord(int value) { return new DWord((uint)value); } public static explicit operator DWord(uint value) { return new DWord(value); } public static DWord operator +(DWord expr1, DWord expr2) { expr1.Value += expr2.Value; return expr1; } public static DWord operator *(uint value, DWord expr) { expr.Value = value * expr.Value; return expr; } public static DWord operator |(DWord expr1, DWord expr2) { expr1.Value |= expr2.Value; return expr1; } public static DWord operator ^(DWord expr1, DWord expr2) { expr1.Value ^= expr2.Value; return expr1; } public static DWord operator <<(DWord expr, int count) { expr.Value <<= count; return expr; } public static DWord operator >>(DWord expr, int count) { expr.Value >>= count; return expr; } } } } internal enum TwofishManagedTransformMode { Encrypt = 0, Decrypt = 1 } }
namespace FakeItEasy.Specs { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FakeItEasy.Core; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; [Collection("DummyCreationSpecs")] public abstract class DummyCreationSpecsBase { [Scenario] public void InterfaceCreation( IDisposable dummy) { "Given a fakeable interface type" .See<IDisposable>(); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<IDisposable>()); "Then it returns a fake of that type" .x(() => dummy.Should().BeAFake()); } [Scenario] public void AbstractClassCreation( TextReader dummy) { "Given a fakeable abstract class type" .See<TextReader>(); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<TextReader>()); "Then it returns a fake of that type" .x(() => dummy.Should().BeAFake()); } [Scenario] public void ValueTypeCreation( DateTime dummy) { "Given a value type" .See<DateTime>(); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<DateTime>()); "Then it returns the default value for that type" .x(() => dummy.Should().Be(default(DateTime))); } [Scenario] public void NullableTypeCreation( int? dummy) { "Given a nullable type" .See<int?>(); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<int?>()); "Then it returns the default value for that type" .x(() => dummy.Should().Be(default(int?))); } [Scenario] public void StringCreation( string dummy1, string dummy2) { "When a dummy string is requested" .x(() => dummy1 = this.CreateDummy<string>()); "And another dummy string is requested" .x(() => dummy2 = this.CreateDummy<string>()); "Then it returns an empty string the first time" .x(() => dummy1.Should().Be(string.Empty)); "Then it returns an empty string the second time" .x(() => dummy2.Should().Be(string.Empty)); "And the two strings are the same reference" .x(() => dummy1.Should().BeSameAs(dummy2)); } [Scenario] public void TypeWithDummyFactoryCreation( Foo dummy) { "Given a type" .See<Foo>(); "And a dummy factory for that type" .See<FooDummyFactory>(); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<Foo>()); "Then it returns a dummy created by the dummy factory" .x(() => dummy.Bar.Should().Be(42)); } [Scenario] public void CollectionOfDummyCreation( IList<DateTime> dummies) { "Given a type" .See<DateTime>(); "When a collection of that type is requested" .x(() => dummies = this.CreateCollectionOfDummy<DateTime>(10)); "Then it returns a collection with the specified number of dummies" .x(() => dummies.Should().HaveCount(10)); } [Scenario] public void ClassWhoseLongerConstructorThrowsCreation( ClassWhoseLongerConstructorThrows dummy1, ClassWhoseLongerConstructorThrows dummy2) { "Given a type with multiple constructors" .See<ClassWhoseLongerConstructorThrows>(); "And its longer constructor throws" .See(() => new ClassWhoseLongerConstructorThrows(0, 0)); // If multiple theads attempt to create the dummy at the same time, the // unsuccessful constructors may be called more than once, so serialize dummy // creation for this test. "And nobody else is trying to create a dummy of the class right now" .x(() => Monitor.TryEnter(ClassWhoseLongerConstructorThrows.SyncRoot, TimeSpan.FromSeconds(30)).Should().BeTrue("we must enter the monitor")) .Teardown(() => Monitor.Exit(ClassWhoseLongerConstructorThrows.SyncRoot)); "When a dummy of that type is requested" .x(() => dummy1 = this.CreateDummy<ClassWhoseLongerConstructorThrows>()); "And another dummy of that type is requested" .x(() => dummy2 = this.CreateDummy<ClassWhoseLongerConstructorThrows>()); "Then it returns a dummy from the first request" .x(() => dummy1.Should().NotBeNull()); "And the dummy is created via the shorter constructor" .x(() => dummy1.CalledConstructor.Should().Be("(int)")); "And it returns a dummy from the second request" .x(() => dummy2.Should().NotBeNull()); "And that dummy is created via the shorter constructor" .x(() => dummy2.CalledConstructor.Should().Be("(int)")); "And the dummies are distinct" .x(() => dummy1.Should().NotBeSameAs(dummy2)); "And the longer constructor was only attempted once" .x(() => ClassWhoseLongerConstructorThrows.NumberOfTimesLongerConstructorWasCalled.Should().Be(1)); } [Scenario] public void SealedClassWhoseLongerConstructorThrowsCreation( SealedClassWhoseLongerConstructorThrows dummy) { "Given a sealed type with multiple constructors" .See<SealedClassWhoseLongerConstructorThrows>(); "And its longer constructor throws" .See(() => new SealedClassWhoseLongerConstructorThrows(0, 0)); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<SealedClassWhoseLongerConstructorThrows>()); "Then it returns a dummy" .x(() => dummy.Should().NotBeNull()); "And the dummy is created via the shorter constructor" .x(() => dummy.CalledConstructor.Should().Be("(int)")); } [Scenario] public void ClassWithLongConstructorWhoseArgumentsCannotBeResolvedCreation( ClassWithLongConstructorWhoseArgumentsCannotBeResolved dummy) { "Given a type with multiple constructors" .See<ClassWithLongConstructorWhoseArgumentsCannotBeResolved>(); "And its longer constructor's argument cannot be resolved" .See(() => new ClassWithLongConstructorWhoseArgumentsCannotBeResolved(A.Dummy<ClassWhoseDummyFactoryThrows>(), A.Dummy<int>())); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<ClassWithLongConstructorWhoseArgumentsCannotBeResolved>()); "Then it returns a dummy" .x(() => dummy.Should().NotBeNull()); "And the dummy is created via the shorter constructor" .x(() => dummy.CalledConstructor.Should().Be("(int)")); } [Scenario] public void SealedClassWithLongConstructorWhoseArgumentsCannotBeResolvedCreation( SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved dummy) { "Given a sealed type with multiple constructors" .See<SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved>(); "And its longer constructor's argument cannot be resolved" .See(() => new SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved(A.Dummy<ClassWhoseDummyFactoryThrows>(), A.Dummy<int>())); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved>()); "Then it returns a dummy" .x(() => dummy.Should().NotBeNull()); "And the dummy is created via the shorter constructor" .x(() => dummy.CalledConstructor.Should().Be("(int)")); } [Scenario] public void ClassWithRecursiveDependencyCreation(Exception exception) { "Given a type that can't be made into a Dummy because it has a recursive dependency" .See<ClassWithRecursiveDependency>(); "When a dummy of that type is requested" .x(() => exception = Record.Exception(() => this.CreateDummy<ClassWithRecursiveDependency>())); "Then it throws an exception of type DummyCreationException" .x(() => exception.Should().BeAnExceptionOfType<DummyCreationException>()); "And its message indicates that a dummy couldn't be created due to the dependency" .x(() => exception.Message.Should().BeModuloLineEndings(@" Failed to create dummy of type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithRecursiveDependency: No Dummy Factory produced a result. It is not a Task. It is not a Lazy. It is not a tuple. It is not a value type. The constructors with the following signatures were not tried: (*FakeItEasy.Specs.DummyCreationSpecsBase+AnIntermediateClassInTheRecursiveDependencyChain) Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors. ")); } [Scenario] public void ClassWithNoPublicConstructorCreation(Exception exception) { "Given a type that can't be made into a Dummy because it has no public constructor" .See<ClassWithNoPublicConstructors>(); "When a dummy of that type is requested" .x(() => exception = Record.Exception(() => this.CreateDummy<ClassWithNoPublicConstructors>())); "Then it throws an exception of type DummyCreationException" .x(() => exception.Should().BeAnExceptionOfType<DummyCreationException>()); "And its message indicates that a dummy couldn't be created" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create dummy of type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoPublicConstructors: No Dummy Factory produced a result. It is not a Task. It is not a Lazy. It is not a tuple. It is not a value type. It has no public constructors. Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoPublicConstructors. An exception of type Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was caught during this call. Its message was: Can not instantiate proxy of class: FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoPublicConstructors. Could not find a parameterless constructor. ")); } [Scenario] public void ClassWhoseOnlyConstructorThrowsCreation(Exception exception) { "Given a type that can't be made into a Dummy because its only public constructor throws" .See<ClassWithNoPublicConstructors>(); "When a dummy of that type is requested" .x(() => exception = Record.Exception(() => this.CreateDummy<ClassWithThrowingConstructor>())); "Then it throws an exception of type DummyCreationException" .x(() => exception.Should().BeAnExceptionOfType<DummyCreationException>()); "And its message indicates that a dummy couldn't be created" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create dummy of type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithThrowingConstructor: No Dummy Factory produced a result. It is not a Task. It is not a Lazy. It is not a tuple. It is not a value type. Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithThrowingConstructor. An exception of type System.Exception was caught during this call. Its message was: constructor threw")); } [Scenario] public void PrivateAbstractClassCreation(Exception exception) { "Given a type that can't be made into a Dummy because is a private abstract class" .See<PrivateAbstractClass>(); "When a dummy of that type is requested" .x(() => exception = Record.Exception(() => this.CreateDummy<PrivateAbstractClass>())); "Then it throws an exception of type DummyCreationException" .x(() => exception.Should().BeAnExceptionOfType<DummyCreationException>()); "And its message indicates that a dummy couldn't be created" .x(() => exception.Message.Should().MatchModuloLineEndings(@" Failed to create dummy of type FakeItEasy.Specs.DummyCreationSpecsBase+PrivateAbstractClass: No Dummy Factory produced a result. It is not a Task. It is not a Lazy. It is not a tuple. It is not a value type. It is abstract. Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.DummyCreationSpecsBase+PrivateAbstractClass. An exception of type Castle.DynamicProxy.Generators.GeneratorException was caught during this call. Its message was: Can not create proxy for type FakeItEasy.Specs.DummyCreationSpecsBase+PrivateAbstractClass because it is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo(*DynamicProxyGenAssembly2*)] attribute*")); } [Scenario] public void ClassWhoseConstructorArgumentsCannotBeResolvedCreation(Exception exception) { "Given a type that can't be made into a Dummy because the arguments for its constructor cannot be resolved" .See<ClassWithNoResolvableConstructors>(); "When a dummy of that type is requested" .x(() => exception = Record.Exception(() => this.CreateDummy<ClassWithNoResolvableConstructors>())); "Then it throws an exception of type DummyCreationException" .x(() => exception.Should().BeAnExceptionOfType<DummyCreationException>()); "And its message indicates that a dummy couldn't be created" .x(() => exception.Message.Should().BeModuloLineEndings(@" Failed to create dummy of type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoResolvableConstructors: No Dummy Factory produced a result. It is not a Task. It is not a Lazy. It is not a tuple. It is not a value type. The constructors with the following signatures were not tried: (*FakeItEasy.Specs.DummyCreationSpecsBase+ClassWhoseDummyFactoryThrows) Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors. ")); } [Scenario] public void CollectionOfClassWithNoPublicConstructor(Exception exception) { "Given a type that can't be made into a Dummy" .See<ClassWithNoPublicConstructors>(); "When a collection of dummies of that type is requested" .x(() => exception = Record.Exception(() => this.CreateCollectionOfDummy<ClassWithNoPublicConstructors>(1))); "Then it throws an exception of type DummyCreationException" .x(() => exception.Should().BeAnExceptionOfType<DummyCreationException>()); "And its message indicates that a dummy couldn't be created" .x(() => exception.Message.Should().StartWithModuloLineEndings(@" Failed to create dummy of type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoPublicConstructors: No Dummy Factory produced a result. It is not a Task. It is not a Lazy. It is not a tuple. It is not a value type. It has no public constructors. Below is a list of reasons for failure per attempted constructor: Constructor with signature () failed: No usable default constructor was found on the type FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoPublicConstructors. An exception of type Castle.DynamicProxy.InvalidProxyConstructorArgumentsException was caught during this call. Its message was: Can not instantiate proxy of class: FakeItEasy.Specs.DummyCreationSpecsBase+ClassWithNoPublicConstructors. Could not find a parameterless constructor.")); } [Scenario] public void AvoidLongSelfReferentialConstructor( ClassWithLongSelfReferentialConstructor dummy1, ClassWithLongSelfReferentialConstructor dummy2) { "Given a class with multiple constructors" .See<ClassWithLongSelfReferentialConstructor>(); "And the class has a one-parameter constructor not using its own type" .See(() => new ClassWithLongSelfReferentialConstructor(typeof(object))); "And the class has a two-parameter constructor using its own type" .See(() => new ClassWithLongSelfReferentialConstructor(typeof(object), A.Dummy<ClassWithLongSelfReferentialConstructor>())); "When a dummy of the class is requested" .x(() => dummy1 = this.CreateDummy<ClassWithLongSelfReferentialConstructor>()); "And I create another dummy of the class" .x(() => dummy2 = this.CreateDummy<ClassWithLongSelfReferentialConstructor>()); "Then the first dummy is not null" .x(() => dummy1.Should().NotBeNull()); "And it was created using the one-parameter constructor" .x(() => dummy1.NumberOfConstructorParameters.Should().Be(1)); "And the second dummy is not null" .x(() => dummy2.Should().NotBeNull()); "And it was created using the one-parameter constructor" .x(() => dummy2.NumberOfConstructorParameters.Should().Be(1)); } [Scenario] public void TupleCreation(Tuple<Foo, string> dummy) { "Given a type" .See<Foo>(); "And another type" .See<string>(); "When a dummy tuple of those types of these types is requested" .x(() => dummy = this.CreateDummy<Tuple<Foo, string>>()); "Then the first item of the tuple is a dummy" .x(() => dummy.Item1.Should().BeOfType<Foo>()); "And the second item of the tuple is a dummy" .x(() => dummy.Item2.Should().BeOfType<string>()); } [Scenario] public void ValueTupleCreation((Foo foo, string s) dummy) { "Given a type" .See<Foo>(); "And another type" .See<string>(); "When a dummy value tuple of those types is requested" .x(() => dummy = this.CreateDummy<(Foo, string)>()); "Then the first item of the tuple is a dummy" .x(() => dummy.foo.Should().BeOfType<Foo>()); "And the second item of the tuple is a dummy" .x(() => dummy.s.Should().BeOfType<string>()); } [Scenario] public void LazyCreation(Lazy<string> dummy) { "Given a type" .See<string>(); "When a dummy lazy of that type is requested" .x(() => dummy = this.CreateDummy<Lazy<string>>()); "Then it returns a lazy" .x(() => dummy.Should().BeOfType<Lazy<string>>()); "And the lazy's value isn't created yet" .x(() => dummy.IsValueCreated.Should().BeFalse()); "And the lazy's value returns a dummy of its type" .x(() => dummy.Value.Should().BeOfType<string>()); } [Scenario] public void LazyCreationNonDummyable(Lazy<NonDummyable> dummy) { "Given a non-dummyable type" .See<NonDummyable>(); "When a dummy lazy of that type is requested" .x(() => dummy = this.CreateDummy<Lazy<NonDummyable>>()); "Then it returns a lazy" .x(() => dummy.Should().BeOfType<Lazy<NonDummyable>>()); "And the lazy's value isn't created yet" .x(() => dummy.IsValueCreated.Should().BeFalse()); "And the lazy's value returns null" .x(() => dummy.Value.Should().BeNull()); } [Scenario] public void LazyCreationIsLazy(Lazy<LazilyCreated> dummy) { "Given a type that tracks instance creation" .x(() => LazilyCreated.IsInstanceCreated = false); "When a dummy lazy of this type is requested" .x(() => dummy = this.CreateDummy<Lazy<LazilyCreated>>()); "Then the dummy value isn't created yet" .x(() => LazilyCreated.IsInstanceCreated.Should().BeFalse()); "And the value is created on first access" .x(() => dummy.Value.Should().BeAssignableTo<LazilyCreated>()); } [Scenario] public void TaskCreation(Task dummy) { "Given the Task type" .See<Task>(); "When a dummy task is requested" .x(() => dummy = this.CreateDummy<Task>()); "Then it returns a task" .x(() => dummy.Should().BeAssignableTo<Task>()); "And the task is completed successfully" .x(() => dummy.Status.Should().Be(TaskStatus.RanToCompletion)); } [Scenario] public void TaskOfTCreation(Task<string> dummy) { "Given a type" .See<string>(); "When a dummy task of that type is requested" .x(() => dummy = this.CreateDummy<Task<string>>()); "Then it returns a task" .x(() => dummy.Should().BeOfType<Task<string>>()); "And the task is completed successfully" .x(() => dummy.Status.Should().Be(TaskStatus.RanToCompletion)); "And the task's result is a dummy of the value type" .x(() => dummy.Result.Should().BeOfType<string>()); } [Scenario] public void TaskOfTCreationNonDummyable(Task<NonDummyable> dummy) { "Given a non-dummyable type" .See<NonDummyable>(); "When a dummy task of that type is requested" .x(() => dummy = this.CreateDummy<Task<NonDummyable>>()); "Then it returns a task" .x(() => dummy.Should().BeOfType<Task<NonDummyable>>()); "And the task is completed successfully" .x(() => dummy.Status.Should().Be(TaskStatus.RanToCompletion)); "And the task's result is null" .x(() => dummy.Result.Should().BeNull()); } [Scenario] public void ValueTaskCreation(ValueTask dummy) { "Given the ValueTask type" .See<ValueTask>(); "When a dummy ValueTask is requested" .x(() => dummy = this.CreateDummy<ValueTask>()); "Then it returns a ValueTask" .x(() => dummy.Should().BeOfType<ValueTask>()); "And the ValueTask is completed successfully" .x(() => dummy.IsCompletedSuccessfully.Should().BeTrue()); } [Scenario] public void ValueTaskOfTCreation(ValueTask<string> dummy) { "Given a type" .See<string>(); "When a dummy ValueTask of that type is requested" .x(() => dummy = this.CreateDummy<ValueTask<string>>()); "Then it returns a ValueTask" .x(() => dummy.Should().BeOfType<ValueTask<string>>()); "And the ValueTask is completed successfully" .x(() => dummy.IsCompletedSuccessfully.Should().BeTrue()); "And the ValueTask's result is a dummy of the value type" .x(() => dummy.Result.Should().BeOfType<string>()); } [Scenario] public void ValueTaskOfTCreationNonDummyable(ValueTask<NonDummyable> dummy) { "Given a type" .See<NonDummyable>(); "When a dummy ValueTask of that type is requested" .x(() => dummy = this.CreateDummy<ValueTask<NonDummyable>>()); "Then it returns a ValueTask" .x(() => dummy.Should().BeOfType<ValueTask<NonDummyable>>()); "And the ValueTask is completed successfully" .x(() => dummy.IsCompletedSuccessfully.Should().BeTrue()); "And the ValueTask's result is null" .x(() => dummy.Result.Should().BeNull()); } [Scenario] public void CreateDummyThatIsNull(ClassWhoseDummyIsNull dummy) { "Given a type whose dummy factory returns null" .See<ClassWhoseDummyIsNull>(); "When a dummy of that type is requested" .x(() => dummy = this.CreateDummy<ClassWhoseDummyIsNull>()); "Then it returns null" .x(() => dummy.Should().BeNull()); } [Scenario] public void CreateDummyThatNeedsNullConstructorParameter(ClassThatRequiresClassWhoseDummyIsNull dummy) { "Given a type whose dummy factory returns null" .See<ClassWhoseDummyIsNull>(); "And a class whose constructor requires an argument of that type" .See<ClassThatRequiresClassWhoseDummyIsNull>(); "When a dummy of the latter type is requested" .x(() => dummy = this.CreateDummy<ClassThatRequiresClassWhoseDummyIsNull>()); "Then it returns a non-null dummy object" .x(() => dummy.Should().NotBeNull()); } public class ClassWithNoPublicConstructors { private ClassWithNoPublicConstructors() { } } public class ClassWithRecursiveDependency { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "a", Justification = "Required for testing.")] public ClassWithRecursiveDependency(AnIntermediateClassInTheRecursiveDependencyChain a) { } } public class AnIntermediateClassInTheRecursiveDependencyChain { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "c", Justification = "Required for testing.")] public AnIntermediateClassInTheRecursiveDependencyChain(ClassWithRecursiveDependency c) { } } public class ClassWithThrowingConstructor { public ClassWithThrowingConstructor() { throw new Exception("constructor threw"); } } public class ClassWithNoResolvableConstructors { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "c", Justification = "Required for testing.")] public ClassWithNoResolvableConstructors(ClassWhoseDummyFactoryThrows c) { } } private abstract class PrivateAbstractClass { } protected abstract T CreateDummy<T>(); protected abstract IList<T> CreateCollectionOfDummy<T>(int count); public class Foo { public int Bar { get; set; } } public class FooDummyFactory : DummyFactory<Foo> { protected override Foo Create() { return new Foo { Bar = 42 }; } } public class NonDummyable { // Internal constructor prevents creation of a dummy internal NonDummyable() { } } public sealed class ClassWhoseLongerConstructorThrows { public static readonly object SyncRoot = new object(); private static int numberOfTimesLongerConstructorWasCalled; public string CalledConstructor { get; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] public ClassWhoseLongerConstructorThrows(int i) { this.CalledConstructor = "(int)"; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "j", Justification = "Required for testing.")] public ClassWhoseLongerConstructorThrows(int i, int j) { this.CalledConstructor = "(int, int)"; Interlocked.Increment(ref numberOfTimesLongerConstructorWasCalled); throw new Exception("(int, int) constructor threw"); } public static int NumberOfTimesLongerConstructorWasCalled => numberOfTimesLongerConstructorWasCalled; } public sealed class SealedClassWhoseLongerConstructorThrows { public string CalledConstructor { get; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] public SealedClassWhoseLongerConstructorThrows(int i) { this.CalledConstructor = "(int)"; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "j", Justification = "Required for testing.")] public SealedClassWhoseLongerConstructorThrows(int i, int j) { this.CalledConstructor = "(int, int)"; throw new Exception("(int, int) constructor threw"); } } public class ClassWithLongConstructorWhoseArgumentsCannotBeResolved { public string CalledConstructor { get; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] public ClassWithLongConstructorWhoseArgumentsCannotBeResolved(int i) { this.CalledConstructor = "(int)"; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "c", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] public ClassWithLongConstructorWhoseArgumentsCannotBeResolved(ClassWhoseDummyFactoryThrows c, int i) { this.CalledConstructor = "(ClassWhoseDummyFactoryThrows, int)"; } } public sealed class SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved { public string CalledConstructor { get; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] public SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved(int i) { this.CalledConstructor = "(int)"; } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "c", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "i", Justification = "Required for testing.")] public SealedClassWithLongConstructorWhoseArgumentsCannotBeResolved(ClassWhoseDummyFactoryThrows c, int i) { this.CalledConstructor = "(ClassWhoseDummyFactoryThrows, int)"; } } public class ClassWhoseDummyFactoryThrows { } public class ClassWhoseDummyFactoryThrowsFactory : DummyFactory<ClassWhoseDummyFactoryThrows> { protected override ClassWhoseDummyFactoryThrows Create() { throw new NotSupportedException("dummy factory threw"); } } #pragma warning disable CA1052 public class LazilyCreated { public static bool IsInstanceCreated { get; set; } public LazilyCreated() { IsInstanceCreated = true; } } #pragma warning restore CA1052 public class ClassWhoseDummyIsNull { } public class ClassWhoseDummyIsNullFactory : DummyFactory<ClassWhoseDummyIsNull?> { protected override ClassWhoseDummyIsNull? Create() => null; } public class ClassThatRequiresClassWhoseDummyIsNull { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "unused", Justification = "This is just a dummy argument.")] public ClassThatRequiresClassWhoseDummyIsNull(ClassWhoseDummyIsNull unused) { } } } public class GenericDummyCreationSpecs : DummyCreationSpecsBase { protected override T CreateDummy<T>() { return A.Dummy<T>(); } protected override IList<T> CreateCollectionOfDummy<T>(int count) { return A.CollectionOfDummy<T>(count); } } public class NonGenericDummyCreationSpecs : DummyCreationSpecsBase { protected override T CreateDummy<T>() { return (T)Sdk.Create.Dummy(typeof(T))!; } protected override IList<T> CreateCollectionOfDummy<T>(int count) { return Sdk.Create.CollectionOfDummy(typeof(T), count).Cast<T>().ToList(); } } }
#region Copyright & license notice /* * Copyright: Copyright (c) 2007 Amazon Technologies, Inc. * License: Apache License, Version 2.0 */ #endregion using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Reflection; using Amazon.WebServices.MechanicalTurk.Domain; using Amazon.WebServices.MechanicalTurk.Advanced; namespace Amazon.WebServices.MechanicalTurk { /// <summary> /// Utilities for question handling /// </summary> public sealed class QuestionUtil { private static Regex formattedContentSplitter = new Regex("<FormattedContent>", RegexOptions.Compiled); private static Regex htmlContentSplitter = new Regex("<HTMLContent>", RegexOptions.Compiled); #region Constructors static QuestionUtil() { string xmlNamespace = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd"; // read the namespace for the schema from the generated file to dynamically reflect changes XmlRootAttribute[] atts = (XmlRootAttribute[]) (typeof(QuestionForm).GetCustomAttributes(typeof(System.Xml.Serialization.XmlRootAttribute), false)); if (atts.Length == 1) { xmlNamespace = atts[0].Namespace; } TPL_FREE_TEXT_QUESTION_FORM = TPL_FREE_TEXT_QUESTION_FORM.Replace("@NAMESPACE@", xmlNamespace); xmlNamespace = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"; // same for external question atts = (XmlRootAttribute[]) (typeof(ExternalQuestion).GetCustomAttributes(typeof(System.Xml.Serialization.XmlRootAttribute), false)); if (atts.Length == 1) { xmlNamespace = atts[0].Namespace; } TPL_EXTERNAL_QUESTION_FORM = TPL_EXTERNAL_QUESTION_FORM.Replace("@NAMESPACE@", xmlNamespace); xmlNamespace = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2011-11-11/HTMLQuestion.xsd"; // same for HTML question atts = (XmlRootAttribute[]) (typeof(HTMLQuestion).GetCustomAttributes(typeof(System.Xml.Serialization.XmlRootAttribute), false)); if (atts.Length == 1) { xmlNamespace = atts[0].Namespace; } TPL_HTML_QUESTION_FORM = TPL_HTML_QUESTION_FORM.Replace("@NAMESPACE@", xmlNamespace); } private QuestionUtil() { } #endregion #region Question handling private static string TPL_FREE_TEXT_QUESTION_FORM = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<QuestionForm xmlns=\"@NAMESPACE@\">" + "{0}" + "</QuestionForm>"; private static string TPL_EXTERNAL_QUESTION_FORM = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<ExternalQuestion xmlns=\"@NAMESPACE@\">" + "{0}" + "</ExternalQuestion>"; private static string TPL_HTML_QUESTION_FORM = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<HTMLQuestion xmlns=\"@NAMESPACE@\">" + "{0}" + "</HTMLQuestion>"; private static string TPL_FREE_TEXT_QUESTION_SINGLE = " <Question>" + " <QuestionIdentifier>{0}</QuestionIdentifier>" + " <QuestionContent>" + " <Text>{1}</Text>" + " </QuestionContent>" + " <AnswerSpecification>" + " <FreeTextAnswer/>" + " </AnswerSpecification>" + " </Question>"; private static string InjectCDataBlocksForFormattedContents(string question) { return InjectCDataBlocksForTag(question, "FormattedContent", formattedContentSplitter); } private static string InjectCDataBlocksForHTMLContents(string question) { return InjectCDataBlocksForTag(question, "HTMLContent", htmlContentSplitter); } /// <summary> /// Injects CDATA into the formatted contents, since the XML Serializer only /// properly handles CDATA when a custom CData serializer can be used /// (see http://geekswithblogs.net/cmartin/archive/2005/11/30/61705.aspx). /// This is not the case for us, because QuestionForm is generated and the /// question must be of type string. Not ideal. /// </summary> private static string InjectCDataBlocksForTag(string question, string tag, Regex splitter) { string startTag = "<" + tag + ">"; string endTag = "</" + tag + ">"; int i1 = question.IndexOf(startTag); if (i1 != -1) { // there is at least one formatted content - process them all string[] parts = splitter.Split(question); StringBuilder sb = new StringBuilder(); int i2 = 0; for (int i = 0; i < parts.Length; i++) { i2 = parts[i].IndexOf(endTag); if (i2 == -1) { sb.Append(parts[i]); } else { // wrap and unescape this block sb.Append(startTag + "<![CDATA["); sb.Append(XmlUtil.XmlDecode(parts[i].Substring(0, i2))); // cdata block sb.Append("]]>" + endTag); sb.Append(parts[i].Substring(i2 + endTag.Length)); } } question = sb.ToString(); } return question; } /// <summary> /// Serializes the question file, containing XML, into an XML string accepted by Mechanical Turk. Validates the XML /// and cleans up encoding. /// </summary> /// <param name="questionFile">A file to serialize, containing a QuestionForm, ExternalQuestion, or HTMLQuestion</param> /// <returns>XML string</returns> public static string SerializeQuestionFileToString(string questionFile) { if (questionFile == null) { throw new ArgumentNullException("questionFile", "Can't serialize null questionFile"); } string xml = File.ReadAllText(questionFile); if (xml.Contains("</QuestionForm>")) { return SerializeQuestionForm(ReadQuestionFormFromFile(questionFile)); } else if (xml.Contains("</ExternalQuestion>")) { return SerializeExternalQuestion(ReadExternalQuestionFromFile(questionFile)); } else if (xml.Contains("</HTMLQuestion>")) { return SerializeHTMLQuestion(ReadHTMLQuestionFromFile(questionFile)); } else { throw new ArgumentNullException("questionFile", "Can't find supported question type"); } } /// <summary> /// Serializes the question form into XML accepted by Mechanical Turk /// </summary> /// <param name="form">A <see cref="QuestionForm"/> instance to serialize</param> /// <returns>XML string</returns> public static string SerializeQuestionForm(QuestionForm form) { if (form == null) { throw new ArgumentNullException("form", "Can't serialize null form"); } string s1 = XmlUtil.SerializeXML(form); int i1 = s1.IndexOf("<Overview>"); if (i1 == -1) { i1 = s1.IndexOf("<Question>"); } if (i1 == -1) { throw new ArgumentException("Cannot serialize question form (contains no questions)"); } s1 = InjectCDataBlocksForFormattedContents(s1); s1= string.Format(TPL_FREE_TEXT_QUESTION_FORM, s1.Substring(i1, s1.IndexOf("</QuestionForm>") - i1)); return s1; } /// <summary> /// Deserializes XML into a question form /// </summary> /// <param name="xml">XML string</param> /// <returns>A <see cref="QuestionForm"/> instance</returns> public static QuestionForm DeserializeQuestionForm(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException("Can't deserialize empty or null XML to question form", "xml"); } return (QuestionForm)XmlUtil.DeserializeXML(typeof(QuestionForm), xml); } /// <summary> /// Reads a question form from an XML file /// </summary> /// <param name="file">File containing the question in XML format</param> /// <returns>A <see cref="QuestionForm"/> instance</returns> public static QuestionForm ReadQuestionFormFromFile(string file) { if (string.IsNullOrEmpty(file)) { throw new ArgumentException("Can't deserialize empty or null XML file to question form", "file"); } string xml = File.ReadAllText(file); return DeserializeQuestionForm(xml); } /// <summary> /// Serializes the external question into XML accepted by Mechanical Turk /// </summary> /// <param name="form">A <see cref="ExternalQuestion"/> instance to serialize</param> /// <returns>XML string</returns> public static string SerializeExternalQuestion(ExternalQuestion form) { if (form == null) { throw new ArgumentNullException("form", "Can't serialize null form"); } string s = XmlUtil.SerializeXML(form); // fast transform of xml serializer output int index1 = s.IndexOf("<ExternalQuestion") + 1; index1 = s.IndexOf('>', index1); s = s.Substring(index1+1).Replace("</ExternalQuestion>", string.Empty); return string.Format(TPL_EXTERNAL_QUESTION_FORM, s); } /// <summary> /// Deserializes XML into a external question /// </summary> /// <param name="xml">XML string</param> /// <returns>A <see cref="ExternalQuestion"/> instance</returns> public static ExternalQuestion DeserializeExternalQuestion(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException("Can't deserialize empty or null XML to external question", "xml"); } return (ExternalQuestion)XmlUtil.DeserializeXML(typeof(ExternalQuestion), xml); } /// <summary> /// Reads an external question from an XML file /// </summary> /// <param name="file">File containing the question in XML format</param> /// <returns>A <see cref="ExternalQuestion"/> instance</returns> public static ExternalQuestion ReadExternalQuestionFromFile(string file) { if (string.IsNullOrEmpty(file)) { throw new ArgumentException("Can't deserialize empty or null XML file to external question", "file"); } string xml = File.ReadAllText(file); return DeserializeExternalQuestion(xml); } /// <summary> /// Serializes the HTML question into XML accepted by Mechanical Turk /// </summary> /// <param name="question">A <see cref="HTMLQuestion"/> instance to serialize</param> /// <returns>XML string</returns> public static string SerializeHTMLQuestion(HTMLQuestion question) { if (question == null) { throw new ArgumentNullException("form", "Can't serialize null form"); } string s = XmlUtil.SerializeXML(question); s = InjectCDataBlocksForHTMLContents(s); // fast transform of xml serializer output int index1 = s.IndexOf("<HTMLQuestion") + 1; index1 = s.IndexOf('>', index1); s = s.Substring(index1 + 1).Replace("</HTMLQuestion>", string.Empty); return string.Format(TPL_HTML_QUESTION_FORM, s); } /// <summary> /// Deserializes XML into an HTML question /// </summary> /// <param name="xml">XML string</param> /// <returns>A <see cref="HTMLQuestion"/> instance</returns> public static HTMLQuestion DeserializeHTMLQuestion(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException("Can't deserialize empty or null XML to external question", "xml"); } return (HTMLQuestion)XmlUtil.DeserializeXML(typeof(HTMLQuestion), xml); } /// <summary> /// Reads an HTML question from an XML file /// </summary> /// <param name="file">File containing the question in XML format</param> /// <returns>A <see cref="HTMLQuestion"/> instance</returns> public static HTMLQuestion ReadHTMLQuestionFromFile(string file) { if (string.IsNullOrEmpty(file)) { throw new ArgumentException("Can't deserialize empty or null XML file to HTMLQuestion", "file"); } string xml = File.ReadAllText(file); return DeserializeHTMLQuestion(xml); } /// <summary> /// Constructs a Question XML String that contains a single freetext question. /// </summary> /// <param name="question">The question phrase to ask</param> /// <returns>Question in XML format</returns> public static string ConvertSingleFreeTextQuestionToXML(string question) { if (string.IsNullOrEmpty(question)) { throw new ArgumentException("Can't convert empty or null question to question form", "question"); } return ConvertMultipleFreeTextQuestionToXML(new string[] { question }); } /// <summary> /// Constructs a Question XML String that contains a multiple freetext questions /// </summary> /// <param name="questions">The question phrase to ask</param> /// <returns>Question in XML format</returns> public static string ConvertMultipleFreeTextQuestionToXML(string[] questions) { if (questions==null || questions.Length==0) { throw new ArgumentNullException("questions", "Empty or null question cannot be converted to XML"); } System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < questions.Length; i++) { if (questions[i] != null && questions[i].Length > 0) { sb.Append(string.Format(TPL_FREE_TEXT_QUESTION_SINGLE, i + 1, XmlUtil.XmlEncode(questions[i]))); } else { MTurkLog.Warn("Ignoring empty question at position {0}", i); } } return string.Format(TPL_FREE_TEXT_QUESTION_FORM, sb.ToString()); } /// <summary> /// Deserializes XML into a question form answer /// </summary> /// <param name="xml">XML string representing answers to a HIT question</param> /// <returns>A <see cref="QuestionFormAnswers"/> instance</returns> public static QuestionFormAnswers DeserializeQuestionFormAnswers(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException("Can't deserialize empty or null XML to question form answers", "xml"); } return (QuestionFormAnswers)XmlUtil.DeserializeXML(typeof(QuestionFormAnswers), xml); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; using System.Security; using System.Security.Cryptography; using System.Text; using System.Xml; using DeOps.Implementation; using DeOps.Implementation.Dht; using DeOps.Implementation.Protocol; using DeOps.Implementation.Protocol.Net; using DeOps.Implementation.Protocol.Special; using DeOps.Services.Update; using System.Xml.Serialization; namespace DeOps { public enum LoadModeType { Settings, AllCaches, LookupCache }; public enum AccessType { Public, Private, Secret }; /// <summary> /// Summary description for KimProfile. /// </summary> public class OpUser { public OpCore Core; public G2Protocol Protocol = new G2Protocol(); public string ProfilePath; public string RootPath; public string TempPath; public byte[] PasswordKey; // 32 bytes (256bit) public byte[] PasswordSalt; // 4 btyes public SettingsPacket Settings = new SettingsPacket(); // gui look public Bitmap OpIcon; public Bitmap OpSplash; public Action GuiIconUpdate; // loading identity, or temp load for processing invite public OpUser(string filepath, string password, OpCore core) { Core = core; // get password salt, first 16 bytes IV, next 4 is salt using (FileStream stream = File.OpenRead(filepath)) { stream.Seek(16, SeekOrigin.Begin); PasswordSalt = new byte[4]; stream.Read(PasswordSalt, 0, 4); } Init(filepath, password); } // used when creating new identity public OpUser(string filepath, string password) { SetNewPassword(password); Init(filepath, password); } private void Init(string filepath, string password) { ProfilePath = filepath; if(PasswordKey == null) PasswordKey = Utilities.GetPasswordKey(password, PasswordSalt); RootPath = Path.GetDirectoryName(filepath); TempPath = RootPath + Path.DirectorySeparatorChar + "Data" + Path.DirectorySeparatorChar + "0"; // clear temp directory try { if (Directory.Exists(TempPath)) Directory.Delete(TempPath, true); } catch { } Directory.CreateDirectory(TempPath); Random rndGen = new Random(); // default settings, set tcp/udp the same so forwarding is easier Settings.TcpPort = (ushort)rndGen.Next(5000, 9000); Settings.UdpPort = Settings.TcpPort; } public void Load(LoadModeType loadMode) { RijndaelManaged Password = new RijndaelManaged(); Password.Key = PasswordKey; byte[] iv = new byte[16]; byte[] salt = new byte[4]; OpCore lookup = null; if (Core != null) lookup = Core.Context.Lookup; try { using (TaggedStream file = new TaggedStream(ProfilePath, Protocol, ProcessSplash)) // tagged with splash { // first 16 bytes IV, next 4 bytes is salt file.Read(iv, 0, 16); file.Read(salt, 0, 4); Password.IV = iv; using (CryptoStream crypto = new CryptoStream(file, Password.CreateDecryptor(), CryptoStreamMode.Read)) { PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Read); G2Header root = null; while (stream.ReadPacket(ref root)) { if (loadMode == LoadModeType.Settings) { if (root.Name == IdentityPacket.OperationSettings) Settings = SettingsPacket.Decode(root); if (root.Name == IdentityPacket.UserInfo && Core != null && (Core.Sim == null || !Core.Sim.Internet.FreshStart)) Core.IndexInfo(UserInfo.Decode(root)); // save icon to identity file because only root node saves icon/splash to link file // to minimize link file size, but allow user to set custom icon/splash if there are not overrides if (root.Name == IdentityPacket.Icon) OpIcon = IconPacket.Decode(root).OpIcon; } if (lookup != null && (loadMode == LoadModeType.AllCaches || loadMode == LoadModeType.LookupCache)) { if (root.Name == IdentityPacket.LookupCachedIP) lookup.Network.Cache.AddSavedContact(CachedIP.Decode(root)); if (root.Name == IdentityPacket.LookupCachedWeb) lookup.Network.Cache.AddWebCache(WebCache.Decode(root)); } if (loadMode == LoadModeType.AllCaches) { if (root.Name == IdentityPacket.OpCachedIP) Core.Network.Cache.AddSavedContact(CachedIP.Decode(root)); if (root.Name == IdentityPacket.OpCachedWeb) Core.Network.Cache.AddWebCache(WebCache.Decode(root)); } } } } } catch(Exception ex) { throw ex; } } 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); OpSplash = (Bitmap)Bitmap.FromStream(new MemoryStream(data)); } } } public void Save() { if (Core != null && Core.InvokeRequired) { Debug.Assert(false); Core.RunInCoreAsync(() => Save()); return; } string backupPath = ProfilePath.Replace(".dop", ".bak"); if( !File.Exists(backupPath) && File.Exists(ProfilePath)) File.Copy(ProfilePath, backupPath, true); RijndaelManaged Password = new RijndaelManaged(); Password.Key = PasswordKey; try { // Attach to crypto stream and write file string tempPath = TempPath + Path.DirectorySeparatorChar + "firstsave"; if (Core != null) tempPath = Core.GetTempPath(); using (FileStream file = new FileStream(tempPath, FileMode.Create)) { // write encrypted part of file Password.GenerateIV(); file.Write(Password.IV, 0, Password.IV.Length); file.Write(PasswordSalt, 0, PasswordSalt.Length); using (CryptoStream crypto = new CryptoStream(file, Password.CreateEncryptor(), CryptoStreamMode.Write)) { PacketStream stream = new PacketStream(crypto, Protocol, FileAccess.Write); stream.WritePacket(Settings); if (Core != null) { if (Core.Context.Lookup != null) { Core.Context.Lookup.Network.Cache.SaveIPs(stream); Core.Context.Lookup.Network.Cache.SaveWeb(stream); } Core.Network.Cache.SaveIPs(stream); Core.Network.Cache.SaveWeb(stream); Core.SaveKeyIndex(stream); } if (OpIcon != null) stream.WritePacket(new IconPacket(IdentityPacket.Icon, OpIcon)); } } // write unencrypted splash using (FileStream file = new FileStream(tempPath, FileMode.Open)) { file.Seek(0, SeekOrigin.End); long startpos = file.Position; PacketStream stream = new PacketStream(file, Protocol, FileAccess.Write); // get right splash image (only used for startup logo, main setting is in link file) if (OpSplash != null) { MemoryStream mem = new MemoryStream(); OpSplash.Save(mem, ImageFormat.Jpeg); LargeDataPacket.Write(stream, IdentityPacket.Splash, mem.ToArray()); } else LargeDataPacket.Write(stream, IdentityPacket.Splash, null); file.WriteByte(0); // end packet stream byte[] last = BitConverter.GetBytes(startpos); file.Write(last, 0, last.Length); } File.Copy(tempPath, ProfilePath, true); File.Delete(tempPath); } catch (Exception ex) { if (Core != null) Core.ConsoleLog("Exception Identity::Save() " + ex.Message); else Core.UserMessage("Profile Save Error:\n" + ex.Message + "\nBackup Restored"); // restore backup if (File.Exists(backupPath)) File.Copy(backupPath, ProfilePath, true); } File.Delete(backupPath); } public static void CreateNew(string path, string opName, string userName, string password, AccessType access, byte[] opKey, bool globalIM) { OpUser user = new OpUser(path, password); user.Settings.Operation = opName; user.Settings.UserName = userName; user.Settings.KeyPair = new RSACryptoServiceProvider(1024); user.Settings.FileKey = Utilities.GenerateKey(new RNGCryptoServiceProvider(), 256); user.Settings.OpAccess = access; user.Settings.Security = SecurityLevel.Medium; user.Settings.GlobalIM = globalIM; // joining/creating public if (access == AccessType.Public) { // 256 bit rijn SHA256Managed sha256 = new SHA256Managed(); user.Settings.OpKey = sha256.ComputeHash(UTF8Encoding.UTF8.GetBytes(opName.ToLowerInvariant())); user.Settings.Security = SecurityLevel.Low; } // invite to private/secret else if (opKey != null) user.Settings.OpKey = opKey; // creating private/secret else if (globalIM) user.Settings.OpKey = DhtNetwork.GlobalIMKey; else user.Settings.OpKey = Utilities.GenerateKey(new RNGCryptoServiceProvider(), 256); user.Save(); // throws exception on failure } public void SetNewPassword(string password) { PasswordSalt = new byte[4]; RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider(); rnd.GetBytes(PasswordSalt); PasswordKey = Utilities.GetPasswordKey(password, PasswordSalt); // ensure save called soon after this function } public bool VerifyPassword(string password) { byte[] key = Utilities.GetPasswordKey(password, PasswordSalt); return Utilities.MemCompare(PasswordKey, key); } public string GetTitle() { return Settings.Operation + " - " + Settings.UserName; } public void IconUpdate() { Core.RunInGuiThread(GuiIconUpdate); } public Icon GetOpIcon() { if (OpIcon != null) return Icon.FromHandle(OpIcon.GetHicon()); else return Core.Context.DefaultIcon; } } public class IconPacket : G2Packet { byte Name; public Bitmap OpIcon; public IconPacket(byte name, Bitmap icon) { Name = name; OpIcon = icon; } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { MemoryStream stream = new MemoryStream(); OpIcon.Save(stream, ImageFormat.Png); protocol.WritePacket(null, Name, stream.ToArray()); return protocol.WriteFinish(); } } public static IconPacket Decode(G2Header root) { if (G2Protocol.ReadPayload(root)) { byte[] array = Utilities.ExtractBytes(root.Data, root.PayloadPos, root.PayloadSize); return new IconPacket(root.Name, (Bitmap) Bitmap.FromStream(new MemoryStream(array))); } return new IconPacket(root.Name, null); } } public class CachedIP : G2Packet { public const byte Packet_Contact = 0x10; public const byte Packet_LastSeen = 0x20; public const byte Packet_Bootstrap = 0x30; public byte Name; public DateTime LastSeen; public DhtContact Contact; public bool Bootstrap; public CachedIP() { } public CachedIP(byte name, DhtContact contact, bool bootstrap) { Name = name; LastSeen = contact.LastSeen; Contact = contact; Bootstrap = bootstrap; } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame saved = protocol.WritePacket(null, Name, null); Contact.WritePacket(protocol, saved, Packet_Contact); protocol.WritePacket(saved, Packet_LastSeen, BitConverter.GetBytes(LastSeen.ToBinary())); protocol.WritePacket(saved, Packet_Bootstrap, BitConverter.GetBytes(Bootstrap)); return protocol.WriteFinish(); } } public static CachedIP Decode(G2Header root) { CachedIP saved = new CachedIP(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Contact: saved.Contact = DhtContact.ReadPacket(child); break; case Packet_LastSeen: saved.LastSeen = DateTime.FromBinary(BitConverter.ToInt64(child.Data, child.PayloadPos)); break; case Packet_Bootstrap: saved.Bootstrap = BitConverter.ToBoolean(child.Data, child.PayloadPos); break; } } saved.Contact.LastSeen = saved.LastSeen; return saved; } } public class IdentityPacket { public const byte OperationSettings = 0x10; public const byte LookupSettings = 0x20; public const byte LookupCachedIP = 0x30; public const byte OpCachedIP = 0x40; public const byte LookupCachedWeb = 0x50; public const byte OpCachedWeb = 0x60; public const byte Icon = 0x70; public const byte Splash = 0x80; public const byte UserInfo = 0x90; public const byte Update = 0xA0; } public class UserInfo : G2Packet { const byte Packet_Name = 0x10; public string Name; public byte[] Key; public ulong ID; public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame user = protocol.WritePacket(null, IdentityPacket.UserInfo, Key); protocol.WritePacket(user, Packet_Name, UTF8Encoding.UTF8.GetBytes(Name)); return protocol.WriteFinish(); } } public static UserInfo Decode(G2Header root) { UserInfo user = new UserInfo(); if (G2Protocol.ReadPayload(root)) { user.Key = Utilities.ExtractBytes(root.Data, root.PayloadPos, root.PayloadSize); user.ID = Utilities.KeytoID(user.Key); } G2Protocol.ResetPacket(root); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Name: user.Name = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; } } return user; } } public class SettingsPacket : G2Packet { const byte Packet_Operation = 0x10; const byte Packet_UserName = 0x20; const byte Packet_TcpPort = 0x30; const byte Packet_UdpPort = 0x40; const byte Packet_OpKey = 0x50; const byte Packet_OpAccess = 0x60; const byte Packet_SecurityLevel = 0x70; const byte Packet_KeyPair = 0x80; const byte Packet_Location = 0x90; const byte Packet_FileKey = 0xA0; const byte Packet_AwayMsg = 0xB0; const byte Packet_GlobalIM = 0xC0; const byte Packet_Invisible = 0xD0; const byte Key_D = 0x10; const byte Key_DP = 0x20; const byte Key_DQ = 0x30; const byte Key_Exponent = 0x40; const byte Key_InverseQ = 0x50; const byte Key_Modulus = 0x60; const byte Key_P = 0x70; const byte Key_Q = 0x80; // general public string Operation; public string UserName; public string Location = ""; public string AwayMessage = ""; public bool Invisible; // network public ushort TcpPort; public ushort UdpPort; // private public byte[] OpKey; public AccessType OpAccess; public SecurityLevel Security; public bool GlobalIM; public RSACryptoServiceProvider KeyPair = new RSACryptoServiceProvider(); public byte[] KeyPublic; public byte[] FileKey; // derived from OpKey // the invite key is how we match the invite to the op of the invitee's public key // different than regular opID so that invite link / public link does not compramise // dht position of op on lookup network public byte[] PublicOpID; public SettingsPacket() { } public override byte[] Encode(G2Protocol protocol) { lock (protocol.WriteSection) { G2Frame settings = protocol.WritePacket(null, IdentityPacket.OperationSettings, null); protocol.WritePacket(settings, Packet_Operation, UTF8Encoding.UTF8.GetBytes(Operation)); protocol.WritePacket(settings, Packet_UserName, UTF8Encoding.UTF8.GetBytes(UserName)); protocol.WritePacket(settings, Packet_TcpPort, BitConverter.GetBytes(TcpPort)); protocol.WritePacket(settings, Packet_UdpPort, BitConverter.GetBytes(UdpPort)); protocol.WritePacket(settings, Packet_Location, UTF8Encoding.UTF8.GetBytes(Location)); protocol.WritePacket(settings, Packet_AwayMsg, UTF8Encoding.UTF8.GetBytes(AwayMessage)); protocol.WritePacket(settings, Packet_FileKey, FileKey); protocol.WritePacket(settings, Packet_OpKey, OpKey); protocol.WritePacket(settings, Packet_OpAccess, BitConverter.GetBytes((byte)OpAccess)); protocol.WritePacket(settings, Packet_SecurityLevel, BitConverter.GetBytes((int)Security)); if (GlobalIM) protocol.WritePacket(settings, Packet_GlobalIM, null); if (Invisible) protocol.WritePacket(settings, Packet_Invisible, null); RSAParameters rsa = KeyPair.ExportParameters(true); G2Frame key = protocol.WritePacket(settings, Packet_KeyPair, null); protocol.WritePacket(key, Key_D, rsa.D); protocol.WritePacket(key, Key_DP, rsa.DP); protocol.WritePacket(key, Key_DQ, rsa.DQ); protocol.WritePacket(key, Key_Exponent, rsa.Exponent); protocol.WritePacket(key, Key_InverseQ, rsa.InverseQ); protocol.WritePacket(key, Key_Modulus, rsa.Modulus); protocol.WritePacket(key, Key_P, rsa.P); protocol.WritePacket(key, Key_Q, rsa.Q); return protocol.WriteFinish(); } } public static SettingsPacket Decode(G2Header root) { SettingsPacket settings = new SettingsPacket(); G2Header child = new G2Header(root.Data); while (G2Protocol.ReadNextChild(root, child) == G2ReadResult.PACKET_GOOD) { if (child.Name == Packet_KeyPair) { DecodeKey(child, settings); continue; } if (child.Name == Packet_GlobalIM) { settings.GlobalIM = true; continue; } if (child.Name == Packet_Invisible) { settings.Invisible = true; continue; } if (!G2Protocol.ReadPayload(child)) continue; switch (child.Name) { case Packet_Operation: settings.Operation = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_UserName: settings.UserName = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_TcpPort: settings.TcpPort = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_UdpPort: settings.UdpPort = BitConverter.ToUInt16(child.Data, child.PayloadPos); break; case Packet_OpKey: settings.OpKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); byte[] pubID = new MD5CryptoServiceProvider().ComputeHash(settings.OpKey); settings.PublicOpID = Utilities.ExtractBytes(pubID, 0, 8); break; case Packet_FileKey: settings.FileKey = Utilities.ExtractBytes(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_OpAccess: settings.OpAccess = (AccessType)child.Data[child.PayloadPos]; break; case Packet_SecurityLevel: settings.Security = (SecurityLevel)BitConverter.ToInt32(child.Data, child.PayloadPos); break; case Packet_Location: settings.Location = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; case Packet_AwayMsg: settings.AwayMessage = UTF8Encoding.UTF8.GetString(child.Data, child.PayloadPos, child.PayloadSize); break; } } return settings; } private static void DecodeKey(G2Header child, SettingsPacket settings) { G2Header key = new G2Header(child.Data); RSAParameters rsa = new RSAParameters(); while (G2Protocol.ReadNextChild(child, key) == G2ReadResult.PACKET_GOOD) { if (!G2Protocol.ReadPayload(key)) continue; switch (key.Name) { case Key_D: rsa.D = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_DP: rsa.DP = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_DQ: rsa.DQ = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_Exponent: rsa.Exponent = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_InverseQ: rsa.InverseQ = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_Modulus: rsa.Modulus = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_P: rsa.P = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; case Key_Q: rsa.Q = Utilities.ExtractBytes(key.Data, key.PayloadPos, key.PayloadSize); break; } } settings.KeyPair.ImportParameters(rsa); settings.KeyPublic = rsa.Modulus; } } // save independently so all operations use same lookup settings for quick startup and lookup network stability public class LookupSettings { [Serializable] public class PortsConfig { public ulong UserID; public ushort Tcp; public ushort Udp; } public PortsConfig Ports; public string StartupPath; public byte[] BootstrapKey; public string BootstrapPath; public string UpdatePath; public string PortsConfigPath; public LookupSettings(string startupPath) { StartupPath = startupPath; BootstrapKey = new SHA256Managed().ComputeHash(UTF8Encoding.UTF8.GetBytes("bootstrap")); BootstrapPath = Path.Combine(startupPath, "bootstrap.dat"); UpdatePath = Path.Combine(startupPath, "update.dat"); PortsConfigPath = Path.Combine(startupPath, "lookup.xml"); } public void Load(DhtNetwork network) { // if the user has multiple ops, the lookup network is setup with the same settings // so it is easy to find and predictable for other's bootstrapping // we put it in local settings so we safe-guard these settings from moving to other computers // and having dupe dht lookup ids on the network try { var serializer = new XmlSerializer(typeof(PortsConfig)); using (var reader = new StreamReader(PortsConfigPath)) Ports = (PortsConfig)serializer.Deserialize(reader); } catch { Ports = new PortsConfig(); } if (Ports.UserID == 0 || network.Core.Sim != null) Ports.UserID = Utilities.StrongRandUInt64(network.Core.StrongRndGen); // keep tcp/udp the same by default if (Ports.Tcp == 0 || network.Core.Sim != null) Ports.Tcp = (ushort)network.Core.RndGen.Next(3000, 15000); if (Ports.Udp == 0 || network.Core.Sim != null) Ports.Udp = Ports.Tcp; // dont want instances saving and loading same lookup file if (network.Core.Sim == null && File.Exists(BootstrapPath)) { try { using (IVCryptoStream crypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey)) { PacketStream stream = new PacketStream(crypto, network.Protocol, FileAccess.Read); G2Header root = null; while (stream.ReadPacket(ref root)) { if (root.Name == IdentityPacket.LookupCachedIP) network.Cache.AddSavedContact(CachedIP.Decode(root)); if (root.Name == IdentityPacket.LookupCachedWeb) network.Cache.AddWebCache(WebCache.Decode(root)); } } } catch (Exception ex) { network.UpdateLog("Exception", "LookupSettings::Load " + ex.Message); } } } public void Save(OpCore core) { Debug.Assert(core.Network.IsLookup); try { var serializer = new XmlSerializer(typeof(PortsConfig)); using (var writer = new StreamWriter(PortsConfigPath)) serializer.Serialize(writer, Ports); } catch { } if (core.Sim != null) return; try { // Attach to crypto stream and write file using (IVCryptoStream crypto = IVCryptoStream.Save(BootstrapPath, BootstrapKey)) { PacketStream stream = new PacketStream(crypto, core.Network.Protocol, FileAccess.Write); if(core.Context.SignedUpdate != null) stream.WritePacket(core.Context.SignedUpdate); core.Network.Cache.SaveIPs(stream); core.Network.Cache.SaveWeb(stream); } } catch (Exception ex) { core.Network.UpdateLog("Exception", "LookupSettings::Save " + ex.Message); } } public void WriteUpdateInfo(OpCore core) { // non lookup core, embedding update packet Debug.Assert(!core.Network.IsLookup); string temp = Path.Combine(StartupPath, "temp.dat"); try { using (IVCryptoStream inCrypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey)) using (IVCryptoStream outCrypto = IVCryptoStream.Save(temp, BootstrapKey)) { byte[] update = core.Context.SignedUpdate.Encode(core.Network.Protocol); outCrypto.Write(update, 0, update.Length); PacketStream inStream = new PacketStream(inCrypto, core.Network.Protocol, FileAccess.Read); G2Header root = null; while (inStream.ReadPacket(ref root)) if (root.Name != IdentityPacket.Update) outCrypto.Write(root.Data, root.PacketPos, root.PacketSize); } File.Copy(temp, BootstrapPath, true); File.Delete(temp); } catch (Exception ex) { core.Network.UpdateLog("Exception", "WriteUpdateInfo::" + ex.Message); } } public UpdateInfo ReadUpdateInfo() { if (!File.Exists(BootstrapPath)) return null; try { using (IVCryptoStream crypto = IVCryptoStream.Load(BootstrapPath, BootstrapKey)) { PacketStream stream = new PacketStream(crypto, new G2Protocol(), FileAccess.Read); G2Header root = null; while (stream.ReadPacket(ref root)) if (root.Name == IdentityPacket.Update) return UpdateInfo.Decode(root); } } catch { } return null; } } }
using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json.Linq; using WiRK.Terminator; using WiRK.Terminator.MapElements; namespace WiRK.TwirkIt { internal static class MapRenderer { internal static JObject MapToJson(List<List<ITile>> map) { var jsonMap = new JObject { ["rows"] = map.Count(), ["columns"] = map.First().Count(), ["map"] = TileMapSprites(map), ["doodads"] = DoodadMapSprites(map) }; return jsonMap; } private static JArray DoodadMapSprites(List<List<ITile>> map) { int rowCount = map.Count(); int columnCount = map.First().Count(); var doodads = new JArray(); for (int i = 0; i < rowCount; ++i) { for (int j = 0; j < columnCount; ++j) { ITile tile = map[i][j]; var floor = tile as Floor; if (floor != null && floor.Edges.Any()) { var d = new List<int>(); foreach (var edge in floor.Edges) { if (edge.Item1 == Orientation.Top) { if (edge.Item2 is WallLaserEdge) { var lasers = edge.Item2 as WallLaserEdge; if (lasers.Lasers == 1) d.Add(120); else d.Add(123); } else if (edge.Item2 is WallPusherEdge) { var pusher = edge.Item2 as WallPusherEdge; if (pusher.Registers.Contains(1)) d.Add(9); else d.Add(1); } else // Simple Wall { d.Add(31); } } else if (edge.Item1 == Orientation.Right) { if (edge.Item2 is WallLaserEdge) { var lasers = edge.Item2 as WallLaserEdge; if (lasers.Lasers == 1) d.Add(121); else d.Add(124); } else if (edge.Item2 is WallPusherEdge) { var pusher = edge.Item2 as WallPusherEdge; if (pusher.Registers.Contains(1)) d.Add(10); else d.Add(2); } else // Simple Wall { d.Add(7); } } else if (edge.Item1 == Orientation.Bottom) { if (edge.Item2 is WallLaserEdge) { var lasers = edge.Item2 as WallLaserEdge; if (lasers.Lasers == 1) d.Add(112); else d.Add(115); } else if (edge.Item2 is WallPusherEdge) { var pusher = edge.Item2 as WallPusherEdge; if (pusher.Registers.Contains(1)) d.Add(11); else d.Add(3); } else // Simple Wall { d.Add(15); } } else //Left { if (edge.Item2 is WallLaserEdge) { var lasers = edge.Item2 as WallLaserEdge; if (lasers.Lasers == 1) d.Add(113); else d.Add(116); } else if (edge.Item2 is WallPusherEdge) { var pusher = edge.Item2 as WallPusherEdge; if (pusher.Registers.Contains(1)) d.Add(12); else d.Add(4); } else // Simple Wall { d.Add(23); } } } doodads.Add(new JArray(d)); continue; } doodads.Add(new JArray(-1)); } } return doodads; } private static JArray TileMapSprites(List<List<ITile>> map) { int rowCount = map.Count(); int columnCount = map.First().Count(); var tiles = new JArray(); for (int i = 0; i < rowCount; ++i) { for (int j = 0; j < columnCount; ++j) { ITile tile = map[i][j]; if (tile is ExpressConveyer) { var ec = tile as ExpressConveyer; if (ec.Entrances.Count == 1) { if (ec.Exit == Orientation.Top) { if (ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(20); else if (ec.Entrances.Any(x => x == Orientation.Left)) tiles.Add(25); else //right tiles.Add(26); } else if (ec.Exit == Orientation.Right) { if (ec.Entrances.Any(x => x == Orientation.Left)) tiles.Add(21); else if (ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(24); else //bottom tiles.Add(18); } else if (ec.Exit == Orientation.Bottom) { if (ec.Entrances.Any(x => x == Orientation.Left)) tiles.Add(19); else if (ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(28); else //right tiles.Add(16); } else // Exit is left { if (ec.Entrances.Any(x => x == Orientation.Right)) tiles.Add(29); else if (ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(27); else //Bottom tiles.Add(17); } } else if (ec.Entrances.Count == 2) { if (ec.Exit == Orientation.Top) { if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(80); if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(84); if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Right)) tiles.Add(91); } else if (ec.Exit == Orientation.Right) { if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(85); if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(81); if (ec.Entrances.Any(x => x == Orientation.Bottom) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(88); } else if (ec.Exit == Orientation.Bottom) { if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(93); if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(82); if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Right)) tiles.Add(89); } else // Exit is left { if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(83); if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(92); if (ec.Entrances.Any(x => x == Orientation.Bottom) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(90); } } else { throw new InvalidDataException(); } } else if (tile is Conveyer) { var ec = tile as Conveyer; if (ec.Entrances.Count == 1) { if (ec.Exit == Orientation.Top) { if (ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(36); else if (ec.Entrances.Any(x => x == Orientation.Left)) tiles.Add(41); else //right tiles.Add(42); } else if (ec.Exit == Orientation.Right) { if (ec.Entrances.Any(x => x == Orientation.Left)) tiles.Add(37); else if (ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(40); else //bottom tiles.Add(34); } else if (ec.Exit == Orientation.Bottom) { if (ec.Entrances.Any(x => x == Orientation.Left)) tiles.Add(35); else if (ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(44); else //right tiles.Add(32); } else // Exit is left { if (ec.Entrances.Any(x => x == Orientation.Right)) tiles.Add(45); else if (ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(43); else //Bottom tiles.Add(33); } } else if (ec.Entrances.Count == 2) { if (ec.Exit == Orientation.Top) { if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(64); if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(68); if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Right)) tiles.Add(75); } else if (ec.Exit == Orientation.Right) { if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(69); if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(65); if (ec.Entrances.Any(x => x == Orientation.Bottom) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(72); } else if (ec.Exit == Orientation.Bottom) { if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(77); if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(66); if (ec.Entrances.Any(x => x == Orientation.Left) && ec.Entrances.Any(x => x == Orientation.Right)) tiles.Add(73); } else // Exit is left { if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Bottom)) tiles.Add(67); if (ec.Entrances.Any(x => x == Orientation.Right) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(76); if (ec.Entrances.Any(x => x == Orientation.Bottom) && ec.Entrances.Any(x => x == Orientation.Top)) tiles.Add(74); } } else { throw new InvalidDataException(); } } else if (tile is Gear) { Gear gear = (Gear)tile; if (gear.Direction == Rotation.Clockwise) tiles.Add(39); else tiles.Add(38); } else if (tile is Pit) { tiles.Add(5); } else if (tile is WrenchHammer) { tiles.Add(6); } else if (tile is Wrench) { tiles.Add(14); } else if (tile is Floor) { tiles.Add(0); } } } return tiles; } } }
using System; using System.Collections.Generic; using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.Html; using ServiceStack.Logging; using ServiceStack.MiniProfiler; using ServiceStack.ServiceHost; using ServiceStack.VirtualPath; using ServiceStack.ServiceModel.Serialization; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Formats; using ServiceStack.WebHost.Endpoints.Support; using ServiceStack.WebHost.Endpoints.Utils; namespace ServiceStack.WebHost.Endpoints { public class EndpointHost { public static ServiceOperations ServiceOperations { get; private set; } public static ServiceOperations AllServiceOperations { get; private set; } public static IAppHost AppHost { get; internal set; } public static IContentTypeFilter ContentTypeFilter { get; set; } public static List<Action<IHttpRequest, IHttpResponse>> RawRequestFilters { get; private set; } public static List<Action<IHttpRequest, IHttpResponse, object>> RequestFilters { get; private set; } public static List<Action<IHttpRequest, IHttpResponse, object>> ResponseFilters { get; private set; } public static List<IViewEngine> ViewEngines { get; set; } public static Action<IHttpRequest, IHttpResponse, string, Exception> ExceptionHandler { get; set; } public static List<HttpHandlerResolverDelegate> CatchAllHandlers { get; set; } private static bool pluginsLoaded = false; public static List<IPlugin> Plugins { get; set; } public static IVirtualPathProvider VirtualPathProvider { get; set; } public static DateTime StartedAt { get; set; } public static DateTime ReadyAt { get; set; } static EndpointHost() { ContentTypeFilter = HttpResponseFilter.Instance; RawRequestFilters = new List<Action<IHttpRequest, IHttpResponse>>(); RequestFilters = new List<Action<IHttpRequest, IHttpResponse, object>>(); ResponseFilters = new List<Action<IHttpRequest, IHttpResponse, object>>(); ViewEngines = new List<IViewEngine>(); CatchAllHandlers = new List<HttpHandlerResolverDelegate>(); Plugins = new List<IPlugin> { new HtmlFormat(), new CsvFormat(), new MarkdownFormat(), }; } // Pre user config public static void ConfigureHost(IAppHost appHost, string serviceName, ServiceManager serviceManager) { AppHost = appHost; EndpointHostConfig.Instance.ServiceName = serviceName; EndpointHostConfig.Instance.ServiceManager = serviceManager; var config = EndpointHostConfig.Instance; Config = config; // avoid cross-dependency on Config setter VirtualPathProvider = new FileSystemVirtualPathProvider(AppHost, Config.WebHostPhysicalPath); } // Config has changed private static void ApplyConfigChanges() { config.ServiceEndpointsMetadataConfig = ServiceEndpointsMetadataConfig.Create(config.ServiceStackHandlerFactoryPath); JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers; JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers; } //After configure called public static void AfterInit() { StartedAt = DateTime.Now; if (config.EnableFeatures != Feature.All) { if ((Feature.Xml & config.EnableFeatures) != Feature.Xml) config.IgnoreFormatsInMetadata.Add("xml"); if ((Feature.Json & config.EnableFeatures) != Feature.Json) config.IgnoreFormatsInMetadata.Add("json"); if ((Feature.Jsv & config.EnableFeatures) != Feature.Jsv) config.IgnoreFormatsInMetadata.Add("jsv"); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) config.IgnoreFormatsInMetadata.Add("csv"); if ((Feature.Html & config.EnableFeatures) != Feature.Html) config.IgnoreFormatsInMetadata.Add("html"); if ((Feature.Soap11 & config.EnableFeatures) != Feature.Soap11) config.IgnoreFormatsInMetadata.Add("soap11"); if ((Feature.Soap12 & config.EnableFeatures) != Feature.Soap12) config.IgnoreFormatsInMetadata.Add("soap12"); } if ((Feature.Html & config.EnableFeatures) != Feature.Html) Plugins.RemoveAll(x => x is HtmlFormat); if ((Feature.Csv & config.EnableFeatures) != Feature.Csv) Plugins.RemoveAll(x => x is CsvFormat); if ((Feature.Markdown & config.EnableFeatures) != Feature.Markdown) Plugins.RemoveAll(x => x is MarkdownFormat); if ((Feature.Razor & config.EnableFeatures) != Feature.Razor) Plugins.RemoveAll(x => x is IRazorPlugin); //external if ((Feature.ProtoBuf & config.EnableFeatures) != Feature.ProtoBuf) Plugins.RemoveAll(x => x is IProtoBufPlugin); //external if (ExceptionHandler == null) { ExceptionHandler = (httpReq, httpRes, operationName, ex) => { var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message); var statusCode = ex.ToStatusCode(); //httpRes.WriteToResponse always calls .Close in it's finally statement so //if there is a problem writing to response, by now it will be closed if (!httpRes.IsClosed) { httpRes.WriteErrorToResponse(httpReq.ResponseContentType, operationName, errorMessage, ex, statusCode); } }; } var specifiedContentType = config.DefaultContentType; //Before plugins loaded ConfigurePlugins(); AppHost.LoadPlugin(Plugins.ToArray()); pluginsLoaded = true; AfterPluginsLoaded(specifiedContentType); ReadyAt = DateTime.Now; } private static void ConfigurePlugins() { //Some plugins need to initialize before other plugins are registered. foreach (var plugin in Plugins) { var preInitPlugin = plugin as IPreInitPlugin; if (preInitPlugin != null) { preInitPlugin.Configure(AppHost); } } } private static void AfterPluginsLoaded(string specifiedContentType) { if (!string.IsNullOrEmpty(specifiedContentType)) config.DefaultContentType = specifiedContentType; else if (string.IsNullOrEmpty(config.DefaultContentType)) config.DefaultContentType = ContentType.Json; config.ServiceManager.AfterInit(); ServiceManager = config.ServiceManager; //reset operations } public static void AddPlugin(params IPlugin[] plugins) { if (pluginsLoaded) { AppHost.LoadPlugin(plugins); ServiceManager.ReloadServiceOperations(); } else { foreach (var plugin in plugins) { Plugins.Add(plugin); } } } public static ServiceManager ServiceManager { get { return config.ServiceManager; } set { config.ServiceManager = value; ServiceOperations = value.ServiceOperations; AllServiceOperations = value.AllServiceOperations; } } public static class UserConfig { public static bool DebugMode { get { return Config != null && Config.DebugMode; } } } private static EndpointHostConfig config; public static EndpointHostConfig Config { get { return config; } set { if (value.ServiceName == null) throw new ArgumentNullException("ServiceName"); if (value.ServiceController == null) throw new ArgumentNullException("ServiceController"); config = value; ApplyConfigChanges(); } } /// <summary> /// Applies the raw request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyPreRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes) { foreach (var requestFilter in RawRequestFilters) { requestFilter(httpReq, httpRes); if (httpRes.IsClosed) break; } return httpRes.IsClosed; } /// <summary> /// Applies the request filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyRequestFilters(IHttpRequest httpReq, IHttpResponse httpRes, object requestDto) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Request Filters")) { //Exec all RequestFilter attributes with Priority < 0 var attributes = FilterAttributeCache.GetRequestFilterAttributes(requestDto.GetType()); var i = 0; for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.RequestFilter(httpReq, httpRes, requestDto); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec global filters foreach (var requestFilter in RequestFilters) { requestFilter(httpReq, httpRes, requestDto); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec remaining RequestFilter attributes with Priority >= 0 for (; i < attributes.Length; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.RequestFilter(httpReq, httpRes, requestDto); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } return httpRes.IsClosed; } } /// <summary> /// Applies the response filters. Returns whether or not the request has been handled /// and no more processing should be done. /// </summary> /// <returns></returns> public static bool ApplyResponseFilters(IHttpRequest httpReq, IHttpResponse httpRes, object response) { httpReq.ThrowIfNull("httpReq"); httpRes.ThrowIfNull("httpRes"); using (Profiler.Current.Step("Executing Response Filters")) { var responseDto = response.ToResponseDto(); var attributes = responseDto != null ? FilterAttributeCache.GetResponseFilterAttributes(responseDto.GetType()) : null; //Exec all ResponseFilter attributes with Priority < 0 var i = 0; if (attributes != null) { for (; i < attributes.Length && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } } //Exec global filters foreach (var responseFilter in ResponseFilters) { responseFilter(httpReq, httpRes, response); if (httpRes.IsClosed) return httpRes.IsClosed; } //Exec remaining RequestFilter attributes with Priority >= 0 if (attributes != null) { for (; i < attributes.Length; i++) { var attribute = attributes[i]; ServiceManager.Container.AutoWire(attribute); attribute.ResponseFilter(httpReq, httpRes, response); if (AppHost != null) //tests AppHost.Release(attribute); if (httpRes.IsClosed) return httpRes.IsClosed; } } return httpRes.IsClosed; } } public static void SetOperationTypes(ServiceOperations operationTypes, ServiceOperations allOperationTypes) { ServiceOperations = operationTypes; AllServiceOperations = allOperationTypes; } internal static object ExecuteService(object request, EndpointAttributes endpointAttributes, IHttpRequest httpReq, IHttpResponse httpRes) { using (Profiler.Current.Step("Execute Service")) { return config.ServiceController.Execute(request, new HttpRequestContext(httpReq, httpRes, request, endpointAttributes)); } } /// <summary> /// Call to signal the completion of a ServiceStack-handled Request /// </summary> internal static void CompleteRequest() { try { if (AppHost != null) { AppHost.OnEndRequest(); } } catch (Exception ex) {} } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// EmailCommseqStep /// </summary> [DataContract] public partial class EmailCommseqStep : IEquatable<EmailCommseqStep>, IValidatableObject { /// <summary> /// Type of step /// </summary> /// <value>Type of step</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum Begin for value: begin /// </summary> [EnumMember(Value = "begin")] Begin = 1, /// <summary> /// Enum Wait for value: wait /// </summary> [EnumMember(Value = "wait")] Wait = 2, /// <summary> /// Enum Email for value: email /// </summary> [EnumMember(Value = "email")] Email = 3, /// <summary> /// Enum Merge for value: merge /// </summary> [EnumMember(Value = "merge")] Merge = 4, /// <summary> /// Enum Condition for value: condition /// </summary> [EnumMember(Value = "condition")] Condition = 5, /// <summary> /// Enum End for value: end /// </summary> [EnumMember(Value = "end")] End = 6 } /// <summary> /// Type of step /// </summary> /// <value>Type of step</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// Initializes a new instance of the <see cref="EmailCommseqStep" /> class. /// </summary> /// <param name="altChildEmailCommunicationSequenceSteps">Array of child steps for the alternate path.</param> /// <param name="childEmailCommunicationSequenceSteps">Array of child steps.</param> /// <param name="emailCommunicationSequenceStepUuid">Email commseq step UUID.</param> /// <param name="emailPendingReview">True if the content of the email associated with this step is pending review by UltraCart.</param> /// <param name="emailRejected">True if the content of the email associated with this step was rejected during review by UltraCart.</param> /// <param name="emailRequiresReview">True if the content of the email associated with this step requires review by UltraCart.</param> /// <param name="filterProfileEquationJson">Filter profile equation JSON.</param> /// <param name="merchantNotes">Internal merchant notes.</param> /// <param name="stepConfigJson">Arbitrary Configuration for a step.</param> /// <param name="type">Type of step.</param> public EmailCommseqStep(List<EmailCommseqStep> altChildEmailCommunicationSequenceSteps = default(List<EmailCommseqStep>), List<EmailCommseqStep> childEmailCommunicationSequenceSteps = default(List<EmailCommseqStep>), string emailCommunicationSequenceStepUuid = default(string), bool? emailPendingReview = default(bool?), bool? emailRejected = default(bool?), bool? emailRequiresReview = default(bool?), string filterProfileEquationJson = default(string), string merchantNotes = default(string), string stepConfigJson = default(string), TypeEnum? type = default(TypeEnum?)) { this.AltChildEmailCommunicationSequenceSteps = altChildEmailCommunicationSequenceSteps; this.ChildEmailCommunicationSequenceSteps = childEmailCommunicationSequenceSteps; this.EmailCommunicationSequenceStepUuid = emailCommunicationSequenceStepUuid; this.EmailPendingReview = emailPendingReview; this.EmailRejected = emailRejected; this.EmailRequiresReview = emailRequiresReview; this.FilterProfileEquationJson = filterProfileEquationJson; this.MerchantNotes = merchantNotes; this.StepConfigJson = stepConfigJson; this.Type = type; } /// <summary> /// Array of child steps for the alternate path /// </summary> /// <value>Array of child steps for the alternate path</value> [DataMember(Name="alt_child_email_communication_sequence_steps", EmitDefaultValue=false)] public List<EmailCommseqStep> AltChildEmailCommunicationSequenceSteps { get; set; } /// <summary> /// Array of child steps /// </summary> /// <value>Array of child steps</value> [DataMember(Name="child_email_communication_sequence_steps", EmitDefaultValue=false)] public List<EmailCommseqStep> ChildEmailCommunicationSequenceSteps { get; set; } /// <summary> /// Email commseq step UUID /// </summary> /// <value>Email commseq step UUID</value> [DataMember(Name="email_communication_sequence_step_uuid", EmitDefaultValue=false)] public string EmailCommunicationSequenceStepUuid { get; set; } /// <summary> /// True if the content of the email associated with this step is pending review by UltraCart /// </summary> /// <value>True if the content of the email associated with this step is pending review by UltraCart</value> [DataMember(Name="email_pending_review", EmitDefaultValue=false)] public bool? EmailPendingReview { get; set; } /// <summary> /// True if the content of the email associated with this step was rejected during review by UltraCart /// </summary> /// <value>True if the content of the email associated with this step was rejected during review by UltraCart</value> [DataMember(Name="email_rejected", EmitDefaultValue=false)] public bool? EmailRejected { get; set; } /// <summary> /// True if the content of the email associated with this step requires review by UltraCart /// </summary> /// <value>True if the content of the email associated with this step requires review by UltraCart</value> [DataMember(Name="email_requires_review", EmitDefaultValue=false)] public bool? EmailRequiresReview { get; set; } /// <summary> /// Filter profile equation JSON /// </summary> /// <value>Filter profile equation JSON</value> [DataMember(Name="filter_profile_equation_json", EmitDefaultValue=false)] public string FilterProfileEquationJson { get; set; } /// <summary> /// Internal merchant notes /// </summary> /// <value>Internal merchant notes</value> [DataMember(Name="merchant_notes", EmitDefaultValue=false)] public string MerchantNotes { get; set; } /// <summary> /// Arbitrary Configuration for a step /// </summary> /// <value>Arbitrary Configuration for a step</value> [DataMember(Name="step_config_json", EmitDefaultValue=false)] public string StepConfigJson { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EmailCommseqStep {\n"); sb.Append(" AltChildEmailCommunicationSequenceSteps: ").Append(AltChildEmailCommunicationSequenceSteps).Append("\n"); sb.Append(" ChildEmailCommunicationSequenceSteps: ").Append(ChildEmailCommunicationSequenceSteps).Append("\n"); sb.Append(" EmailCommunicationSequenceStepUuid: ").Append(EmailCommunicationSequenceStepUuid).Append("\n"); sb.Append(" EmailPendingReview: ").Append(EmailPendingReview).Append("\n"); sb.Append(" EmailRejected: ").Append(EmailRejected).Append("\n"); sb.Append(" EmailRequiresReview: ").Append(EmailRequiresReview).Append("\n"); sb.Append(" FilterProfileEquationJson: ").Append(FilterProfileEquationJson).Append("\n"); sb.Append(" MerchantNotes: ").Append(MerchantNotes).Append("\n"); sb.Append(" StepConfigJson: ").Append(StepConfigJson).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as EmailCommseqStep); } /// <summary> /// Returns true if EmailCommseqStep instances are equal /// </summary> /// <param name="input">Instance of EmailCommseqStep to be compared</param> /// <returns>Boolean</returns> public bool Equals(EmailCommseqStep input) { if (input == null) return false; return ( this.AltChildEmailCommunicationSequenceSteps == input.AltChildEmailCommunicationSequenceSteps || this.AltChildEmailCommunicationSequenceSteps != null && this.AltChildEmailCommunicationSequenceSteps.SequenceEqual(input.AltChildEmailCommunicationSequenceSteps) ) && ( this.ChildEmailCommunicationSequenceSteps == input.ChildEmailCommunicationSequenceSteps || this.ChildEmailCommunicationSequenceSteps != null && this.ChildEmailCommunicationSequenceSteps.SequenceEqual(input.ChildEmailCommunicationSequenceSteps) ) && ( this.EmailCommunicationSequenceStepUuid == input.EmailCommunicationSequenceStepUuid || (this.EmailCommunicationSequenceStepUuid != null && this.EmailCommunicationSequenceStepUuid.Equals(input.EmailCommunicationSequenceStepUuid)) ) && ( this.EmailPendingReview == input.EmailPendingReview || (this.EmailPendingReview != null && this.EmailPendingReview.Equals(input.EmailPendingReview)) ) && ( this.EmailRejected == input.EmailRejected || (this.EmailRejected != null && this.EmailRejected.Equals(input.EmailRejected)) ) && ( this.EmailRequiresReview == input.EmailRequiresReview || (this.EmailRequiresReview != null && this.EmailRequiresReview.Equals(input.EmailRequiresReview)) ) && ( this.FilterProfileEquationJson == input.FilterProfileEquationJson || (this.FilterProfileEquationJson != null && this.FilterProfileEquationJson.Equals(input.FilterProfileEquationJson)) ) && ( this.MerchantNotes == input.MerchantNotes || (this.MerchantNotes != null && this.MerchantNotes.Equals(input.MerchantNotes)) ) && ( this.StepConfigJson == input.StepConfigJson || (this.StepConfigJson != null && this.StepConfigJson.Equals(input.StepConfigJson)) ) && ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AltChildEmailCommunicationSequenceSteps != null) hashCode = hashCode * 59 + this.AltChildEmailCommunicationSequenceSteps.GetHashCode(); if (this.ChildEmailCommunicationSequenceSteps != null) hashCode = hashCode * 59 + this.ChildEmailCommunicationSequenceSteps.GetHashCode(); if (this.EmailCommunicationSequenceStepUuid != null) hashCode = hashCode * 59 + this.EmailCommunicationSequenceStepUuid.GetHashCode(); if (this.EmailPendingReview != null) hashCode = hashCode * 59 + this.EmailPendingReview.GetHashCode(); if (this.EmailRejected != null) hashCode = hashCode * 59 + this.EmailRejected.GetHashCode(); if (this.EmailRequiresReview != null) hashCode = hashCode * 59 + this.EmailRequiresReview.GetHashCode(); if (this.FilterProfileEquationJson != null) hashCode = hashCode * 59 + this.FilterProfileEquationJson.GetHashCode(); if (this.MerchantNotes != null) hashCode = hashCode * 59 + this.MerchantNotes.GetHashCode(); if (this.StepConfigJson != null) hashCode = hashCode * 59 + this.StepConfigJson.GetHashCode(); if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// 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. // // Basic test for dependent handles. // // Note that though this test uses ConditionalWeakTable it is not a test for that class. This is a stress // test that utilizes ConditionalWeakTable features, which would be used heavily if Dynamic Language Runtime // catches on. // // Basic test overview: // * Allocate an array of objects (we call these Nodes) with finalizers. // * Create a set of dependent handles that reference these objects as primary and secondary members (this is // where ConditionalWeakTable comes in, adding a key/value pair to such a table creates a dependent handle // with the primary set to the key and the secondary set to the value). // * Null out selected objects from the array in various patterns. This removes the only normal strong root // for such objects (leaving only the dependent handles to provide additional roots). // * Perform a full GC and wait for it and finalization to complete. Each object which is collected will use // its finalizer to inform the test that it's been disposed of. // * Run our own reachability analysis (a simple mark array approach) to build a picture of which objects in // the array should have been collected or not. // * Validate that the actual set of live objects matches our computed live set exactly. // // Test variations include the number of objects allocated, the relationship between the primary and secondary // in each handle we allocate and the pattern with which we null out object references in the array. // // Additionally this test stresses substantially more complex code paths in the GC if server mode is enabled. // This can be achieved by setting the environment variable COMPlus_BuildFlavor=svr prior to executing the // test executable. // // Note that we don't go to any lengths to ensure that dependent handle ownership is spread over multiple cpus // on a server GC/MP test run. For large node counts (e.g. 100000) this happens naturally since initialization // takes a while with multiple thread/CPU switches involved. We could be more explicit here (allocate handles // using CPU affinitized threads) but if we do that we'd probably better look into different patterns of node // ownership to avoid unintentionally restricting our test coverage. // // Another area into which we could look deeper is trying to force mark stack overflows in the GC (presumably // by allocating complex object graphs with lots of interconnections, though I don't the specifics of the best // way to force this). Causing mark stack overflows should open up a class of bug the old dependent handle // implementation was subject to without requiring server GC mode or multiple CPUs. // using System; using System.Runtime.CompilerServices; // How we assign nodes to dependent handles. enum TableStyle { Unconnected, // The primary and secondary handles are assigned completely disjoint objects ForwardLinked, // The primary of each handle is the secondary of the previous handle BackwardLinked, // The primary of each handle is the secondary of the next handle Random // The primaries are each object in sequence, the secondaries are selected randomly from // the same set } // How we choose object references in the array to null out (and thus potentially become collected). enum CollectStyle { None, // Don't null out any (nothing should be collected) All, // Null them all out (any remaining live objects should be collected) Alternate, // Null out every second reference Random // Null out each entry with a 50% probability } // We report errors by throwing an exception. Define our own Exception subclass so we can identify these // errors unambiguously. class TestException : Exception { // We just supply a simple message string on error. public TestException(string message) : base(message) { } } // Class encapsulating test runs over a set of objects/handles allocated with the specified TableStyle. class TestSet { // Create a new test with the given table style and object count. public TestSet(TableStyle ts, int count) { // Use one random number generator for the life of the test. Could support explicit seeds for // reproducible tests here. m_rng = new Random(); // Remember our parameters. m_count = count; m_style = ts; // Various arrays. m_nodes = new Node[count]; // The array of objects m_collected = new bool[count]; // Records whether each object has been collected (entries are set by // the finalizer on Node) m_marks = new bool[count]; // Array used during individual test runs to calculate whether each // object should still be alive (allocated once here to avoid // injecting further garbage collections at run time) // Allocate each object (Node). Each knows its own unique ID (the index into the node array) and has a // back pointer to this test object (so it can phone home to report its own collection at finalization // time). for (int i = 0; i < count; i++) m_nodes[i] = new Node(this, i); // Determine how many handles we need to allocate given the number of nodes. This varies based on the // table style. switch (ts) { case TableStyle.Unconnected: // Primaries and secondaries are completely different objects so we split our nodes in half and // allocate that many handles. m_handleCount = count / 2; break; case TableStyle.ForwardLinked: // Nodes are primaries in one handle and secondary in another except one that falls off the end. // So we have as many handles as nodes - 1. m_handleCount = count - 1; break; case TableStyle.BackwardLinked: // Nodes are primaries in one handle and secondary in another except one that falls off the end. // So we have as many handles as nodes - 1. m_handleCount = count - 1; break; case TableStyle.Random: // Each node is a primary in some handle (secondaries are selected from amongst all the same nodes // randomly). So we have as many nodes as handles. m_handleCount = count; break; } // Allocate an array of HandleSpecs. These aren't the real handles, just structures that allow us // remember what's in each handle (in terms of the node index number for the primary and secondary). // We need to track this information separately because we can't access the real handles directly // (ConditionalWeakTable hides them) and we need to recall exactly what the primary and secondary of // each handle is so we can compute our own notion of object liveness later. m_handles = new HandleSpec[m_handleCount]; // Initialize the handle specs to assign objects to handles based on the table style. for (int i = 0; i < m_handleCount; i++) { int primary = -1, secondary = -1; switch (ts) { case TableStyle.Unconnected: // Assign adjacent nodes to the primary and secondary of each handle. primary = i * 2; secondary = (i * 2) + 1; break; case TableStyle.ForwardLinked: // Primary of each handle is the secondary of the last handle. primary = i; secondary = i + 1; break; case TableStyle.BackwardLinked: // Primary of each handle is the secondary of the next handle. primary = i + 1; secondary = i; break; case TableStyle.Random: // Primary is each node in sequence, secondary is any of the nodes randomly. primary = i; secondary = m_rng.Next(m_handleCount); break; } m_handles[i].Set(primary, secondary); } // Allocate a ConditionalWeakTable mapping Node keys to Node values. m_table = new ConditionalWeakTable<Node, Node>(); // Using our handle specs computed above add each primary/secondary node pair to the // ConditionalWeakTable in turn. This causes the ConditionalWeakTable to allocate a dependent handle // for each entry with the primary and secondary objects we specified as keys and values (note that // this scheme prevents us from creating multiple handles with the same primary though if this is // desired we could achieve it by allocating multiple ConditionalWeakTables). for (int i = 0; i < m_handleCount; i++) m_table.Add(m_nodes[m_handles[i].m_primary], m_nodes[m_handles[i].m_secondary]); } // Call this method to indicate a test error with a given message. This will terminate the test // immediately. void Error(string message) { throw new TestException(message); } // Run a single test pass on the node set. Null out node references according to the given CollectStyle, // run a garbage collection and then verify that each node is either live or dead as we predict. Take care // of the order in which test runs are made against a single TestSet: e.g. running a CollectStyle.All will // collect all nodes, rendering further runs relatively uninteresting. public void Run(CollectStyle cs) { Console.WriteLine("Running test TS:{0} CS:{1} {2} entries...", Enum.GetName(typeof(TableStyle), m_style), Enum.GetName(typeof(CollectStyle), cs), m_count); // Iterate over the array of nodes deciding for each whether to sever the reference (null out the // entry). for (int i = 0; i < m_count; i++) { bool sever = false; switch (cs) { case CollectStyle.All: // Sever all references. sever = true; break; case CollectStyle.None: // Don't sever any references. break; case CollectStyle.Alternate: // Sever every second reference (starting with the first). if ((i % 2) == 0) sever = true; break; case CollectStyle.Random: // Sever any reference with a 50% probability. if (m_rng.Next(100) > 50) sever = true; break; } if (sever) m_nodes[i] = null; } // Initialize a full GC and wait for all finalizers to complete (so we get an accurate picture of // which nodes were collected). GC.Collect(); GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers(); // the above call may correspond to a GC prior to the Collect above, call it again // Calculate our own view of which nodes should be alive or dead. Use a simple mark array for this. // Once the algorithm is complete a true value at a given index in the array indicates a node that // should still be alive, otherwise the node should have been collected. // Initialize the mark array. Set true for nodes we still have a strong reference to from the array // (these should definitely not have been collected yet). Set false for the other nodes (we assume // they must have been collected until we prove otherwise). for (int i = 0; i < m_count; i++) m_marks[i] = m_nodes[i] != null; // Perform multiple passes over the handles we allocated (or our recorded version of the handles at // least). If we find a handle with a marked (live) primary where the secondary is not yet marked then // go ahead and mark that secondary (dependent handles are defined to do this: primaries act as if // they have a strong reference to the secondary up until the point they are collected). Repeat this // until we manage a scan over the entire table without marking any additional nodes as live. At this // point the marks array should reflect which objects are still live. while (true) { // Assume we're not going any further nodes to mark as live. bool marked = false; // Look at each handle in turn. for (int i = 0; i < m_handleCount; i++) if (m_marks[m_handles[i].m_primary]) { // Primary is live. if (!m_marks[m_handles[i].m_secondary]) { // Secondary wasn't marked as live yet. Do so and remember that we marked at least // node as live this pass (so we need to loop again since this secondary could be the // same as a primary earlier in the table). m_marks[m_handles[i].m_secondary] = true; marked = true; } } // Terminate the loop if we scanned the entire table without marking any additional nodes as live // (since additional scans can't make any difference). if (!marked) break; } // Validate our view of node liveness (m_marks) correspond to reality (m_nodes and m_collected). for (int i = 0; i < m_count; i++) { // Catch nodes which still have strong references but have collected anyway. This is stricly a // subset of the next test but it would be a very interesting bug to call out. if (m_nodes[i] != null && m_collected[i]) Error(String.Format("Node {0} was collected while it still had a strong root", i)); // Catch nodes which we compute as alive but have been collected. if (m_marks[i] && m_collected[i]) Error(String.Format("Node {0} was collected while it was still reachable", i)); // Catch nodes which we compute as dead but haven't been collected. if (!m_marks[i] && !m_collected[i]) Error(String.Format("Node {0} wasn't collected even though it was unreachable", i)); } } // Method called by nodes when they're finalized (i.e. the node has been collected). public void Collected(int id) { // Catch nodes which are collected twice. if (m_collected[id]) Error(String.Format("Node {0} collected twice", id)); m_collected[id] = true; } // Structure used to record the primary and secondary nodes in every dependent handle we allocated. Nodes // are identified by ID (their index into the node array). struct HandleSpec { public int m_primary; public int m_secondary; public void Set(int primary, int secondary) { m_primary = primary; m_secondary = secondary; } } int m_count; // Count of nodes in array TableStyle m_style; // Style of handle creation Node[] m_nodes; // Array of nodes bool[] m_collected; // Array indicating which nodes have been collected bool[] m_marks; // Array indicating which nodes should be live ConditionalWeakTable<Node, Node> m_table; // Table that creates and holds our dependent handles int m_handleCount; // Number of handles we create HandleSpec[] m_handles; // Array of descriptions of each handle Random m_rng; // Random number generator } // The type of object we reference from our dependent handles. Doesn't do much except report its own garbage // collection to the owning TestSet. class Node { // Allocate a node and remember our owner (TestSet) and ID (index into node array). public Node(TestSet owner, int id) { m_owner = owner; m_id = id; } // On finalization report our collection to the owner TestSet. ~Node() { m_owner.Collected(m_id); } TestSet m_owner; // TestSet which created us int m_id; // Our index into above TestSet's node array } // The test class itself. class DhTest1 { // Entry point. public static int Main() { // The actual test runs are controlled from RunTest. True is returned if all succeeded, false // otherwise. if (new DhTest1().RunTest()) { Console.WriteLine("Test PASS"); return 100; } else { Console.WriteLine("Test FAIL"); return 999; } } // Run a series of tests with different table and collection styles. bool RunTest() { // Number of nodes we'll allocate in each run (we could take this as an argument instead). int numNodes = 10000; // Run everything under an exception handler since test errors are reported as exceptions. try { // Run a pass with each table style. For each style run through the collection styles in the order // None, Alternate, Random and All. This sequence is carefully selected to remove progressively // more nodes from the array (since, within a given TestSet instance, once a node has actually // been collected it won't be resurrected for future runs). TestSet ts1 = new TestSet(TableStyle.Unconnected, numNodes); ts1.Run(CollectStyle.None); ts1.Run(CollectStyle.Alternate); ts1.Run(CollectStyle.Random); ts1.Run(CollectStyle.All); TestSet ts2 = new TestSet(TableStyle.ForwardLinked, numNodes); ts2.Run(CollectStyle.None); ts2.Run(CollectStyle.Alternate); ts2.Run(CollectStyle.Random); ts2.Run(CollectStyle.All); TestSet ts3 = new TestSet(TableStyle.BackwardLinked, numNodes); ts3.Run(CollectStyle.None); ts3.Run(CollectStyle.Alternate); ts3.Run(CollectStyle.Random); ts3.Run(CollectStyle.All); TestSet ts4 = new TestSet(TableStyle.Random, numNodes); ts4.Run(CollectStyle.None); ts4.Run(CollectStyle.Alternate); ts4.Run(CollectStyle.Random); ts4.Run(CollectStyle.All); } catch (TestException te) { // "Expected" errors. Console.WriteLine("TestError: {0}", te.Message); return false; } catch (Exception e) { // Totally unexpected errors (probably shouldn't see these unless there's a test bug). Console.WriteLine("Unexpected exception: {0}", e.GetType().Name); return false; } // If we get as far as here the test succeeded. return true; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System { //Only contains static methods. Does not require serialization using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Security; [System.Runtime.InteropServices.ComVisible(true)] public static partial class Buffer { #if !MONO // Copies from one primitive array to another primitive array without // respecting types. This calls memmove internally. The count and // offset parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); #endif // A very simple and efficient memmove that assumes all of the // parameter validation has already been done. The count and offset // parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool InternalBlockCopy(Array src, int srcOffsetBytes, Array dst, int dstOffsetBytes, int byteCount); // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates // pretty good code here and this ends up being within a couple % of the CRT asm. // It is however cross platform as the CRT hasn't ported their fast version to 64-bit // platforms. // [System.Security.SecurityCritical] // auto-generated internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count) { Contract.Assert(src != null, "src should not be null"); byte* pByte = src + index; // Align up the pointer to sizeof(int). while (((int)pByte & 3) != 0) { if (count == 0) return -1; else if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // Fill comparer with value byte for comparisons // // comparer = 0/0/value/value uint comparer = (((uint)value << 8) + (uint)value); // comparer = value/value/value/value comparer = (comparer << 16) + comparer; // Run through buffer until we hit a 4-byte section which contains // the byte we're looking for or until we exhaust the buffer. while (count > 3) { // Test the buffer for presence of value. comparer contains the byte // replicated 4 times. uint t1 = *(uint*)pByte; t1 = t1 ^ comparer; uint t2 = 0x7efefeff + t1; t1 = t1 ^ 0xffffffff; t1 = t1 ^ t2; t1 = t1 & 0x81010100; // if t1 is zero then these 4-bytes don't contain a match if (t1 != 0) { // We've found a match for value, figure out which position it's in. int foundIndex = (int) (pByte - src); if (pByte[0] == value) return foundIndex; else if (pByte[1] == value) return foundIndex + 1; else if (pByte[2] == value) return foundIndex + 2; else if (pByte[3] == value) return foundIndex + 3; } count -= 4; pByte += 4; } // Catch any bytes that might be left at the tail of the buffer while (count > 0) { if (*pByte == value) return (int) (pByte - src); count--; pByte++; } // If we don't have a match return -1; return -1; } #if !MONO // Returns a bool to indicate if the array is of primitive data types // or not. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsPrimitiveTypeArray(Array array); #endif // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return ((byte*)array) + index. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern byte _GetByte(Array array, int index); #if !MONO [System.Security.SecuritySafeCritical] // auto-generated public static byte GetByte(Array array, int index) { // Is the array present? if (array == null) throw new ArgumentNullException("array"); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array"); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException("index"); return _GetByte(array, index); } #endif // Sets a particular byte in an the array. The array must be an // array of primitives. // // This essentially does the following: // *(((byte*)array) + index) = value. // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _SetByte(Array array, int index, byte value); #if !MONO [System.Security.SecuritySafeCritical] // auto-generated public static void SetByte(Array array, int index, byte value) { // Is the array present? if (array == null) throw new ArgumentNullException("array"); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array"); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException("index"); // Make the FCall to do the work _SetByte(array, index, value); } #endif // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return array.length * sizeof(array.UnderlyingElementType). // [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _ByteLength(Array array); #if !MONO [System.Security.SecuritySafeCritical] // auto-generated public static int ByteLength(Array array) { // Is the array present? if (array == null) throw new ArgumentNullException("array"); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), "array"); return _ByteLength(array); } #endif [System.Security.SecurityCritical] // auto-generated internal unsafe static void ZeroMemory(byte* src, long len) { while(len-- > 0) *(src + len) = 0; } #if !FEATURE_CORECLR [System.Runtime.ForceTokenStabilization] #endif //!FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Contract.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pDest = dest) { Memcpy(pDest + destIndex, src + srcIndex, len); } } #if !FEATURE_CORECLR [System.Runtime.ForceTokenStabilization] #endif //!FEATURE_CORECLR [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { Contract.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Contract.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len==0) return; fixed(byte* pSrc = src) { Memcpy(pDest + destIndex, pSrc + srcIndex, len); } } #if !MONO // This is tricky to get right AND fast, so lets make it useful for the whole Fx. // E.g. System.Runtime.WindowsRuntime!WindowsRuntimeBufferExtensions.MemCopy uses it. [FriendAccessAllowed] #if !FEATURE_CORECLR [System.Runtime.ForceTokenStabilization] #endif //!FEATURE_CORECLR [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if ARM [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern void Memcpy(byte* dest, byte* src, int len); #else // ARM internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Contract.Assert(len >= 0, "Negative length in memcopy!"); // // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. // // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as // possible yet and so we have this implementation here for now. // switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short *)dest = *(short *)src; return; case 3: *(short *)dest = *(short *)src; *(dest + 2) = *(src + 2); return; case 4: *(int *)dest = *(int *)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif return; case 9: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(dest + 8) = *(src + 8); return; case 10: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: #if WIN64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: #if WIN64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif return; default: break; } // P/Invoke into the native version for large lengths if (len >= 512) { _Memcpy(dest, src, len); return; } if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *dest = *src; src++; dest++; len--; if (((int)dest & 2) == 0) goto Aligned; } *(short *)dest = *(short *)src; src += 2; dest += 2; len -= 2; Aligned: ; } #if WIN64 if (((int)dest & 4) != 0) { *(int *)dest = *(int *)src; src += 4; dest += 4; len -= 4; } #endif int count = len / 16; while (count > 0) { #if WIN64 ((long*)dest)[0] = ((long*)src)[0]; ((long*)dest)[1] = ((long*)src)[1]; #else ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; ((int*)dest)[2] = ((int*)src)[2]; ((int*)dest)[3] = ((int*)src)[3]; #endif dest += 16; src += 16; count--; } if ((len & 8) != 0) { #if WIN64 ((long*)dest)[0] = ((long*)src)[0]; #else ((int*)dest)[0] = ((int*)src)[0]; ((int*)dest)[1] = ((int*)src)[1]; #endif dest += 8; src += 8; } if ((len & 4) != 0) { ((int*)dest)[0] = ((int*)src)[0]; dest += 4; src += 4; } if ((len & 2) != 0) { ((short*)dest)[0] = ((short*)src)[0]; dest += 2; src += 2; } if ((len & 1) != 0) *dest++ = *src++; } // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.NoInlining)] private unsafe static void _Memcpy(byte* dest, byte* src, int len) { __Memcpy(dest, src, len); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [SecurityCritical] [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] extern private unsafe static void __Memcpy(byte* dest, byte* src, int len); #endif // ARM #endif } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Dynamic; using IronPython.Runtime.Binding; using IronPython.Runtime.Types; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Operations { internal static class PythonTypeOps { private static readonly Dictionary<FieldInfo, PythonTypeSlot> _fieldCache = new Dictionary<FieldInfo, PythonTypeSlot>(); private static readonly Dictionary<BuiltinFunction, BuiltinMethodDescriptor> _methodCache = new Dictionary<BuiltinFunction, BuiltinMethodDescriptor>(); private static readonly Dictionary<BuiltinFunction, ClassMethodDescriptor> _classMethodCache = new Dictionary<BuiltinFunction, ClassMethodDescriptor>(); internal static readonly Dictionary<BuiltinFunctionKey, BuiltinFunction> _functions = new Dictionary<BuiltinFunctionKey, BuiltinFunction>(); private static readonly Dictionary<ReflectionCache.MethodBaseCache, ConstructorFunction> _ctors = new Dictionary<ReflectionCache.MethodBaseCache, ConstructorFunction>(); private static readonly Dictionary<EventTracker, ReflectedEvent> _eventCache = new Dictionary<EventTracker, ReflectedEvent>(); internal static readonly Dictionary<PropertyTracker, ReflectedGetterSetter> _propertyCache = new Dictionary<PropertyTracker, ReflectedGetterSetter>(); internal static PythonTuple MroToPython(IList<PythonType> types) { List<object> res = new List<object>(types.Count); foreach (PythonType dt in types) { if (dt.UnderlyingSystemType == typeof(ValueType)) continue; // hide value type res.Add(dt); } return PythonTuple.Make(res); } internal static string GetModuleName(CodeContext/*!*/ context, Type type) { Type curType = type; while (curType != null) { string moduleName; if (PythonContext.GetContext(context).BuiltinModuleNames.TryGetValue(curType, out moduleName)) { return moduleName; } curType = curType.DeclaringType; } FieldInfo modField = type.GetField("__module__"); if (modField != null && modField.IsLiteral && modField.FieldType == typeof(string)) { return (string)modField.GetRawConstantValue(); } return "builtins"; } internal static object CallParams(CodeContext/*!*/ context, PythonType cls, params object[] args\u03c4) { if (args\u03c4 == null) args\u03c4 = ArrayUtils.EmptyObjects; return CallWorker(context, cls, args\u03c4); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, object[] args) { object newObject = PythonOps.CallWithContext(context, GetTypeNew(context, dt), ArrayUtils.Insert<object>(dt, args)); if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Length)) { PythonOps.CallWithContext(context, GetInitMethod(context, dt, newObject), args); AddFinalizer(context, dt, newObject); } return newObject; } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, IDictionary<string, object> kwArgs, object[] args) { object[] allArgs = ArrayOps.CopyArray(args, kwArgs.Count + args.Length); string[] argNames = new string[kwArgs.Count]; int i = args.Length; foreach (KeyValuePair<string, object> kvp in kwArgs) { allArgs[i] = kvp.Value; argNames[i++ - args.Length] = kvp.Key; } return CallWorker(context, dt, new KwCallInfo(allArgs, argNames)); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, KwCallInfo args) { object[] clsArgs = ArrayUtils.Insert<object>(dt, args.Arguments); object newObject = PythonOps.CallWithKeywordArgs(context, GetTypeNew(context, dt), clsArgs, args.Names); if (newObject == null) return null; if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Arguments.Length)) { PythonOps.CallWithKeywordArgs(context, GetInitMethod(context, dt, newObject), args.Arguments, args.Names); AddFinalizer(context, dt, newObject); } return newObject; } /// <summary> /// Looks up __init__ avoiding calls to __getattribute__ and handling both /// new-style and old-style classes in the MRO. /// </summary> private static object GetInitMethod(CodeContext/*!*/ context, PythonType dt, object newObject) { // __init__ is never searched for w/ __getattribute__ for (int i = 0; i < dt.ResolutionOrder.Count; i++) { PythonType cdt = dt.ResolutionOrder[i]; PythonTypeSlot dts; object value; if (cdt.TryLookupSlot(context, "__init__", out dts) && dts.TryGetValue(context, newObject, dt, out value)) { return value; } } return null; } private static void AddFinalizer(CodeContext/*!*/ context, PythonType dt, object newObject) { // check if object has finalizer... PythonTypeSlot dummy; if (dt.TryResolveSlot(context, "__del__", out dummy)) { IWeakReferenceable iwr = context.GetPythonContext().ConvertToWeakReferenceable(newObject); Debug.Assert(iwr != null); InstanceFinalizer nif = new InstanceFinalizer(context, newObject); iwr.SetFinalizer(new WeakRefTracker(nif, nif)); } } private static object GetTypeNew(CodeContext/*!*/ context, PythonType dt) { PythonTypeSlot dts; if (!dt.TryResolveSlot(context, "__new__", out dts)) { throw PythonOps.TypeError("cannot create instances of {0}", dt.Name); } object newInst; bool res = dts.TryGetValue(context, dt, dt, out newInst); Debug.Assert(res); return newInst; } internal static bool IsRuntimeAssembly(Assembly assembly) { if (assembly == typeof(PythonOps).GetTypeInfo().Assembly || // IronPython.dll assembly == typeof(Microsoft.Scripting.Interpreter.LightCompiler).GetTypeInfo().Assembly || // Microsoft.Scripting.dll assembly == typeof(DynamicMetaObject).GetTypeInfo().Assembly) { // Microsoft.Scripting.Core.dll return true; } AssemblyName assemblyName = new AssemblyName(assembly.FullName); if (assemblyName.Name.Equals("IronPython.Modules")) { // IronPython.Modules.dll return true; } return false; } private static bool ShouldInvokeInit(PythonType cls, PythonType newObjectType, int argCnt) { // don't run __init__ if it's not a subclass of ourselves, // or if this is the user doing type(x), or if it's a standard // .NET type which doesn't have an __init__ method (this is a perf optimization) return (!cls.IsSystemType || cls.IsPythonType) && newObjectType.IsSubclassOf(cls) && (cls != TypeCache.PythonType || argCnt > 1); } // note: returns "instance" rather than type name if o is an OldInstance internal static string GetName(object o) { return DynamicHelpers.GetPythonType(o).Name; } internal static PythonType[] ObjectTypes(object[] args) { PythonType[] types = new PythonType[args.Length]; for (int i = 0; i < args.Length; i++) { types[i] = DynamicHelpers.GetPythonType(args[i]); } return types; } internal static Type[] ConvertToTypes(PythonType[] pythonTypes) { Type[] types = new Type[pythonTypes.Length]; for (int i = 0; i < pythonTypes.Length; i++) { types[i] = ConvertToType(pythonTypes[i]); } return types; } private static Type ConvertToType(PythonType pythonType) { if (pythonType.IsNull) { return typeof(DynamicNull); } else { return pythonType.UnderlyingSystemType; } } internal static TrackerTypes GetMemberType(MemberGroup members) { TrackerTypes memberType = TrackerTypes.All; for (int i = 0; i < members.Count; i++) { MemberTracker mi = members[i]; if (mi.MemberType != memberType) { if (memberType != TrackerTypes.All) { return TrackerTypes.All; } memberType = mi.MemberType; } } return memberType; } internal static PythonTypeSlot/*!*/ GetSlot(MemberGroup group, string name, bool privateBinding) { if (group.Count == 0) { return null; } group = FilterNewSlots(group); TrackerTypes tt = GetMemberType(group); switch(tt) { case TrackerTypes.Method: bool checkStatic = false; List<MemberInfo> mems = new List<MemberInfo>(); foreach (MemberTracker mt in group) { MethodTracker metht = (MethodTracker)mt; mems.Add(metht.Method); checkStatic |= metht.IsStatic; } Type declType = group[0].DeclaringType; MemberInfo[] memArray = mems.ToArray(); FunctionType ft = GetMethodFunctionType(declType, memArray, checkStatic); return GetFinalSlotForFunction(GetBuiltinFunction(declType, group[0].Name, name, ft, memArray)); case TrackerTypes.Field: return GetReflectedField(((FieldTracker)group[0]).Field); case TrackerTypes.Property: return GetReflectedProperty((PropertyTracker)group[0], group, privateBinding); case TrackerTypes.Event: return GetReflectedEvent(((EventTracker)group[0])); case TrackerTypes.Type: TypeTracker type = (TypeTracker)group[0]; for (int i = 1; i < group.Count; i++) { type = TypeGroup.UpdateTypeEntity(type, (TypeTracker)group[i]); } if (type is TypeGroup) { return new PythonTypeUserDescriptorSlot(type, true); } return new PythonTypeUserDescriptorSlot(DynamicHelpers.GetPythonTypeFromType(type.Type), true); case TrackerTypes.Constructor: return GetConstructor(group[0].DeclaringType, privateBinding); case TrackerTypes.Custom: return ((PythonCustomTracker)group[0]).GetSlot(); default: // if we have a new slot in the derived class filter out the // members from the base class. throw new InvalidOperationException(String.Format("Bad member type {0} on {1}.{2}", tt.ToString(), group[0].DeclaringType, name)); } } internal static MemberGroup FilterNewSlots(MemberGroup group) { if (GetMemberType(group) == TrackerTypes.All) { Type declType = group[0].DeclaringType; for (int i = 1; i < group.Count; i++) { if (group[i].DeclaringType != declType) { if (group[i].DeclaringType.IsSubclassOf(declType)) { declType = group[i].DeclaringType; } } } List<MemberTracker> trackers = new List<MemberTracker>(); for (int i = 0; i < group.Count; i++) { if (group[i].DeclaringType == declType) { trackers.Add(group[i]); } } if (trackers.Count != group.Count) { return new MemberGroup(trackers.ToArray()); } } return group; } private static BuiltinFunction GetConstructor(Type t, bool privateBinding) { BuiltinFunction ctorFunc = InstanceOps.NonDefaultNewInst; MethodBase[] ctors = CompilerHelpers.GetConstructors(t, privateBinding, true); return GetConstructor(t, ctorFunc, ctors); } internal static bool IsDefaultNew(MethodBase[] targets) { if (targets.Length == 1) { ParameterInfo[] pis = targets[0].GetParameters(); if (pis.Length == 0) { return true; } if (pis.Length == 1 && pis[0].ParameterType == typeof(CodeContext)) { return true; } } return false; } internal static BuiltinFunction GetConstructorFunction(Type type, string name) { List<MethodBase> methods = new List<MethodBase>(); bool hasDefaultConstructor = false; foreach (ConstructorInfo ci in type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { if (ci.IsPublic) { if (ci.GetParameters().Length == 0) { hasDefaultConstructor = true; } methods.Add(ci); } } if (type.IsValueType() && !hasDefaultConstructor && type != typeof(void)) { try { methods.Add(typeof(ScriptingRuntimeHelpers).GetMethod("CreateInstance", ReflectionUtils.EmptyTypes).MakeGenericMethod(type)); } catch (BadImageFormatException) { // certain types (e.g. ArgIterator) won't survive the above call. // we won't let you create instances of these types. } } if (methods.Count > 0) { return BuiltinFunction.MakeFunction(name, methods.ToArray(), type); } return null; } internal static ReflectedEvent GetReflectedEvent(EventTracker tracker) { ReflectedEvent res; lock (_eventCache) { if (!_eventCache.TryGetValue(tracker, out res)) { if (PythonBinder.IsExtendedType(tracker.DeclaringType)) { _eventCache[tracker] = res = new ReflectedEvent(tracker, true); } else { _eventCache[tracker] = res = new ReflectedEvent(tracker, false); } } } return res; } internal static PythonTypeSlot/*!*/ GetFinalSlotForFunction(BuiltinFunction/*!*/ func) { if ((func.FunctionType & FunctionType.Method) != 0) { BuiltinMethodDescriptor desc; lock (_methodCache) { if (!_methodCache.TryGetValue(func, out desc)) { _methodCache[func] = desc = new BuiltinMethodDescriptor(func); } return desc; } } if (func.Targets[0].IsDefined(typeof(ClassMethodAttribute), true)) { lock (_classMethodCache) { ClassMethodDescriptor desc; if (!_classMethodCache.TryGetValue(func, out desc)) { _classMethodCache[func] = desc = new ClassMethodDescriptor(func); } return desc; } } return func; } internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ name, MemberInfo/*!*/[]/*!*/ mems) { return GetBuiltinFunction(type, name, null, mems); } #pragma warning disable 414 // unused fields - they're used by GetHashCode() internal struct BuiltinFunctionKey { Type DeclaringType; ReflectionCache.MethodBaseCache Cache; FunctionType FunctionType; public BuiltinFunctionKey(Type declaringType, ReflectionCache.MethodBaseCache cache, FunctionType funcType) { Cache = cache; FunctionType = funcType; DeclaringType = declaringType; } } #pragma warning restore 169 public static MethodBase[] GetNonBaseHelperMethodInfos(MemberInfo[] members) { List<MethodBase> res = new List<MethodBase>(); foreach (MemberInfo mi in members) { MethodBase mb = mi as MethodBase; if (mb != null && !mb.Name.StartsWith(NewTypeMaker.BaseMethodPrefix)) { res.Add(mb); } } return res.ToArray(); } public static MemberInfo[] GetNonBaseHelperMemberInfos(MemberInfo[] members) { List<MemberInfo> res = new List<MemberInfo>(members.Length); foreach (MemberInfo mi in members) { MethodBase mb = mi as MethodBase; if (mb == null || !mb.Name.StartsWith(NewTypeMaker.BaseMethodPrefix)) { res.Add(mi); } } return res.ToArray(); } internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ name, FunctionType? funcType, params MemberInfo/*!*/[]/*!*/ mems) { return GetBuiltinFunction(type, name, name, funcType, mems); } /// <summary> /// Gets a builtin function for the given declaring type and member infos. /// /// Given the same inputs this always returns the same object ensuring there's only 1 builtinfunction /// for each .NET method. /// /// This method takes both a cacheName and a pythonName. The cache name is the real method name. The pythonName /// is the name of the method as exposed to Python. /// </summary> internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ cacheName, string/*!*/ pythonName, FunctionType? funcType, params MemberInfo/*!*/[]/*!*/ mems) { BuiltinFunction res = null; if (mems.Length != 0) { FunctionType ft = funcType ?? GetMethodFunctionType(type, mems); type = GetBaseDeclaringType(type, mems); BuiltinFunctionKey cache = new BuiltinFunctionKey(type, new ReflectionCache.MethodBaseCache(cacheName, GetNonBaseHelperMethodInfos(mems)), ft); lock (_functions) { if (!_functions.TryGetValue(cache, out res)) { if (PythonTypeOps.GetFinalSystemType(type) == type) { IList<MethodInfo> overriddenMethods = NewTypeMaker.GetOverriddenMethods(type, cacheName); if (overriddenMethods.Count > 0) { List<MemberInfo> newMems = new List<MemberInfo>(mems); foreach (MethodInfo mi in overriddenMethods) { newMems.Add(mi); } mems = newMems.ToArray(); } } _functions[cache] = res = BuiltinFunction.MakeMethod(pythonName, ReflectionUtils.GetMethodInfos(mems), type, ft); } } } return res; } private static Type GetCommonBaseType(Type xType, Type yType) { if (xType.IsSubclassOf(yType)) { return yType; } else if (yType.IsSubclassOf(xType)) { return xType; } else if (xType == yType) { return xType; } Type xBase = xType.GetBaseType(); Type yBase = yType.GetBaseType(); if (xBase != null) { Type res = GetCommonBaseType(xBase, yType); if (res != null) { return res; } } if (yBase != null) { Type res = GetCommonBaseType(xType, yBase); if (res != null) { return res; } } return null; } private static Type GetBaseDeclaringType(Type type, MemberInfo/*!*/[] mems) { // get the base most declaring type, first sort the list so that // the most derived class is at the beginning. Array.Sort<MemberInfo>(mems, delegate(MemberInfo x, MemberInfo y) { if (x.DeclaringType.IsSubclassOf(y.DeclaringType)) { return -1; } else if (y.DeclaringType.IsSubclassOf(x.DeclaringType)) { return 1; } else if (x.DeclaringType == y.DeclaringType) { return 0; } // no relationship between these types, they should be base helper // methods for two different types - for example object.MemberwiseClone for // ExtensibleInt & object. We need to reset our type to the common base type. type = GetCommonBaseType(x.DeclaringType, y.DeclaringType) ?? typeof(object); // generic type definitions will have a null name. if (x.DeclaringType.FullName == null) { return -1; } else if (y.DeclaringType.FullName == null) { return 1; } return x.DeclaringType.FullName.CompareTo(y.DeclaringType.FullName); }); // then if the provided type is a subclass of the most derived type // then our declaring type is the methods declaring type. foreach (MemberInfo mb in mems) { // skip extension methods if (mb.DeclaringType.IsAssignableFrom(type)) { if (type == mb.DeclaringType || type.IsSubclassOf(mb.DeclaringType)) { type = mb.DeclaringType; break; } } } return type; } internal static ConstructorFunction GetConstructor(Type type, BuiltinFunction realTarget, params MethodBase[] mems) { ConstructorFunction res = null; if (mems.Length != 0) { ReflectionCache.MethodBaseCache cache = new ReflectionCache.MethodBaseCache("__new__", mems); lock (_ctors) { if (!_ctors.TryGetValue(cache, out res)) { _ctors[cache] = res = new ConstructorFunction(realTarget, mems); } } } return res; } internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods) { return GetMethodFunctionType(type, methods, true); } internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods, bool checkStatic) { FunctionType ft = FunctionType.None; foreach (MethodInfo mi in methods) { if (mi.IsStatic && mi.IsSpecialName) { ParameterInfo[] pis = mi.GetParameters(); if ((pis.Length == 2 && pis[0].ParameterType != typeof(CodeContext)) || (pis.Length == 3 && pis[0].ParameterType == typeof(CodeContext))) { ft |= FunctionType.BinaryOperator; if (pis[pis.Length - 2].ParameterType != type && pis[pis.Length - 1].ParameterType == type) { ft |= FunctionType.ReversedOperator; } } } if (checkStatic && IsStaticFunction(type, mi)) { ft |= FunctionType.Function; } else { ft |= FunctionType.Method; } } if (IsMethodAlwaysVisible(type, methods)) { ft |= FunctionType.AlwaysVisible; } return ft; } /// <summary> /// Checks to see if the provided members are always visible for the given type. /// /// This filters out methods such as GetHashCode and Equals on standard .NET /// types that we expose directly as Python types (e.g. object, string, etc...). /// /// It also filters out the base helper overrides that are added for supporting /// super calls on user defined types. /// </summary> private static bool IsMethodAlwaysVisible(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods) { bool alwaysVisible = true; if (PythonBinder.IsPythonType(type)) { // only show methods defined outside of the system types (object, string) foreach (MethodInfo mi in methods) { if (PythonBinder.IsExtendedType(mi.DeclaringType) || PythonBinder.IsExtendedType(mi.GetBaseDefinition().DeclaringType) || mi.IsDefined(typeof(PythonHiddenAttribute), false)) { alwaysVisible = false; break; } } } else if (typeof(IPythonObject).IsAssignableFrom(type)) { // check if this is a virtual override helper, if so we // may need to filter it out. foreach (MethodInfo mi in methods) { if (PythonBinder.IsExtendedType(mi.DeclaringType)) { alwaysVisible = false; break; } } } return alwaysVisible; } /// <summary> /// a function is static if it's a static .NET method and it's defined on the type or is an extension method /// with StaticExtensionMethod decoration. /// </summary> private static bool IsStaticFunction(Type type, MethodInfo mi) { return mi.IsStatic && // method must be truly static !mi.IsDefined(typeof(WrapperDescriptorAttribute), false) && // wrapper descriptors are instance methods (mi.DeclaringType.IsAssignableFrom(type) || mi.IsDefined(typeof(StaticExtensionMethodAttribute), false)); // or it's not an extension method or it's a static extension method } internal static PythonTypeSlot GetReflectedField(FieldInfo info) { PythonTypeSlot res; NameType nt = NameType.Field; if (!PythonBinder.IsExtendedType(info.DeclaringType) && !info.IsDefined(typeof(PythonHiddenAttribute), false)) { nt |= NameType.PythonField; } lock (_fieldCache) { if (!_fieldCache.TryGetValue(info, out res)) { if (nt == NameType.PythonField && info.IsLiteral) { if (info.FieldType == typeof(int)) { res = new PythonTypeUserDescriptorSlot( ScriptingRuntimeHelpers.Int32ToObject((int)info.GetRawConstantValue()), true ); } else if (info.FieldType == typeof(bool)) { res = new PythonTypeUserDescriptorSlot( ScriptingRuntimeHelpers.BooleanToObject((bool)info.GetRawConstantValue()), true ); } else { res = new PythonTypeUserDescriptorSlot( info.GetValue(null), true ); } } else { res = new ReflectedField(info, nt); } _fieldCache[info] = res; } } return res; } internal static string GetDocumentation(Type type) { // Python documentation object[] docAttr = type.GetCustomAttributes(typeof(DocumentationAttribute), false); if (docAttr != null && docAttr.Length > 0) { return ((DocumentationAttribute)docAttr[0]).Documentation; } if (type == typeof(DynamicNull)) return null; // Auto Doc (XML or otherwise) string autoDoc = DocBuilder.CreateAutoDoc(type); if (autoDoc == null) { autoDoc = String.Empty; } else { autoDoc += Environment.NewLine + Environment.NewLine; } // Simple generated helpbased on ctor, if available. ConstructorInfo[] cis = type.GetConstructors(); foreach (ConstructorInfo ci in cis) { autoDoc += FixCtorDoc(type, DocBuilder.CreateAutoDoc(ci, DynamicHelpers.GetPythonTypeFromType(type).Name, 0)) + Environment.NewLine; } return autoDoc; } private static string FixCtorDoc(Type type, string autoDoc) { return autoDoc.Replace("__new__(cls)", DynamicHelpers.GetPythonTypeFromType(type).Name + "()"). Replace("__new__(cls, ", DynamicHelpers.GetPythonTypeFromType(type).Name + "("); } internal static ReflectedGetterSetter GetReflectedProperty(PropertyTracker pt, MemberGroup allProperties, bool privateBinding) { ReflectedGetterSetter rp; lock (_propertyCache) { if (_propertyCache.TryGetValue(pt, out rp)) { return rp; } NameType nt = NameType.PythonProperty; MethodInfo getter = FilterProtectedGetterOrSetter(pt.GetGetMethod(true), privateBinding); MethodInfo setter = FilterProtectedGetterOrSetter(pt.GetSetMethod(true), privateBinding); if ((getter != null && getter.IsDefined(typeof(PythonHiddenAttribute), true)) || setter != null && setter.IsDefined(typeof(PythonHiddenAttribute), true)) { nt = NameType.Property; } ExtensionPropertyTracker ept = pt as ExtensionPropertyTracker; if (ept == null) { ReflectedPropertyTracker rpt = pt as ReflectedPropertyTracker; Debug.Assert(rpt != null); if (PythonBinder.IsExtendedType(pt.DeclaringType) || rpt.Property.IsDefined(typeof(PythonHiddenAttribute), true)) { nt = NameType.Property; } if (pt.GetIndexParameters().Length == 0) { List<MethodInfo> getters = new List<MethodInfo>(); List<MethodInfo> setters = new List<MethodInfo>(); IList<ExtensionPropertyTracker> overriddenProperties = NewTypeMaker.GetOverriddenProperties((getter ?? setter).DeclaringType, pt.Name); foreach (ExtensionPropertyTracker tracker in overriddenProperties) { MethodInfo method = tracker.GetGetMethod(privateBinding); if (method != null) { getters.Add(method); } method = tracker.GetSetMethod(privateBinding); if (method != null) { setters.Add(method); } } foreach (PropertyTracker propTracker in allProperties) { MethodInfo method = propTracker.GetGetMethod(privateBinding); if (method != null) { getters.Add(method); } method = propTracker.GetSetMethod(privateBinding); if (method != null) { setters.Add(method); } } rp = new ReflectedProperty(rpt.Property, getters.ToArray(), setters.ToArray(), nt); } else { rp = new ReflectedIndexer(((ReflectedPropertyTracker)pt).Property, NameType.Property, privateBinding); } } else { rp = new ReflectedExtensionProperty(new ExtensionPropertyInfo(pt.DeclaringType, getter ?? setter), nt); } _propertyCache[pt] = rp; return rp; } } private static MethodInfo FilterProtectedGetterOrSetter(MethodInfo info, bool privateBinding) { if (info != null) { if (privateBinding || info.IsPublic) { return info; } if (info.IsProtected()) { return info; } } return null; } internal static bool TryInvokeUnaryOperator(CodeContext context, object o, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "UnaryOp " + CompilerHelpers.GetType(o).Name + " " + name); PythonTypeSlot pts; PythonType pt = DynamicHelpers.GetPythonType(o); object callable; if (pt.TryResolveMixedSlot(context, name, out pts) && pts.TryGetValue(context, o, pt, out callable)) { value = PythonCalls.Call(context, callable); return true; } value = null; return false; } internal static bool TryInvokeBinaryOperator(CodeContext context, object o, object arg1, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "BinaryOp " + CompilerHelpers.GetType(o).Name + " " + name); PythonTypeSlot pts; PythonType pt = DynamicHelpers.GetPythonType(o); object callable; if (pt.TryResolveMixedSlot(context, name, out pts) && pts.TryGetValue(context, o, pt, out callable)) { value = PythonCalls.Call(context, callable, arg1); return true; } value = null; return false; } internal static bool TryInvokeTernaryOperator(CodeContext context, object o, object arg1, object arg2, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "TernaryOp " + CompilerHelpers.GetType(o).Name + " " + name); PythonTypeSlot pts; PythonType pt = DynamicHelpers.GetPythonType(o); object callable; if (pt.TryResolveMixedSlot(context, name, out pts) && pts.TryGetValue(context, o, pt, out callable)) { value = PythonCalls.Call(context, callable, arg1, arg2); return true; } value = null; return false; } /// <summary> /// If we have only interfaces, we'll need to insert object's base /// </summary> internal static PythonTuple EnsureBaseType(PythonTuple bases) { bool hasInterface = false; foreach (object baseClass in bases) { PythonType dt = baseClass as PythonType; if (!dt.UnderlyingSystemType.IsInterface()) { return bases; } else { hasInterface = true; } } if (hasInterface || bases.Count == 0) { // We found only interfaces. We need do add System.Object to the bases return new PythonTuple(bases, TypeCache.Object); } throw PythonOps.TypeError("a new-style class can't have only classic bases"); } internal static Type GetFinalSystemType(Type type) { while (typeof(IPythonObject).IsAssignableFrom(type) && !type.GetTypeInfo().IsDefined(typeof(DynamicBaseTypeAttribute), false)) { type = type.GetBaseType(); } return type; } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using IdentityModel; using IdentityServer.UnitTests.Common; using IdentityServer4.Configuration; using IdentityServer4.Endpoints.Results; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.ResponseHandling; using IdentityServer4.Validation; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; using Xunit; namespace IdentityServer.UnitTests.Endpoints.Results { public class AuthorizeResultTests { private AuthorizeResult _subject; private AuthorizeResponse _response = new AuthorizeResponse(); private IdentityServerOptions _options = new IdentityServerOptions(); private MockUserSession _mockUserSession = new MockUserSession(); private MockMessageStore<IdentityServer4.Models.ErrorMessage> _mockErrorMessageStore = new MockMessageStore<IdentityServer4.Models.ErrorMessage>(); private DefaultHttpContext _context = new DefaultHttpContext(); public AuthorizeResultTests() { _context.SetIdentityServerOrigin("https://server"); _context.SetIdentityServerBasePath("/"); _context.Response.Body = new MemoryStream(); _options.UserInteraction.ErrorUrl = "~/error"; _options.UserInteraction.ErrorIdParameter = "errorId"; _subject = new AuthorizeResult(_response, _options, _mockUserSession, _mockErrorMessageStore, new StubClock()); } [Fact] public async Task error_should_redirect_to_error_page_and_passs_info() { _response.Error = "some_error"; await _subject.ExecuteAsync(_context); _mockErrorMessageStore.Messages.Count.Should().Be(1); _context.Response.StatusCode.Should().Be(302); var location = _context.Response.Headers["Location"].First(); location.Should().StartWith("https://server/error"); var query = QueryHelpers.ParseQuery(new Uri(location).Query); query["errorId"].First().Should().Be(_mockErrorMessageStore.Messages.First().Key); } [Theory] [InlineData(OidcConstants.AuthorizeErrors.AccountSelectionRequired)] [InlineData(OidcConstants.AuthorizeErrors.LoginRequired)] [InlineData(OidcConstants.AuthorizeErrors.ConsentRequired)] [InlineData(OidcConstants.AuthorizeErrors.InteractionRequired)] public async Task prompt_none_errors_should_return_to_client(string error) { _response.Error = error; _response.Request = new ValidatedAuthorizeRequest { ResponseMode = OidcConstants.ResponseModes.Query, RedirectUri = "http://client/callback", PromptMode = "none" }; await _subject.ExecuteAsync(_context); _mockUserSession.Clients.Count.Should().Be(0); _context.Response.StatusCode.Should().Be(302); var location = _context.Response.Headers["Location"].First(); location.Should().StartWith("http://client/callback"); } [Theory] [InlineData(OidcConstants.AuthorizeErrors.AccountSelectionRequired)] [InlineData(OidcConstants.AuthorizeErrors.LoginRequired)] [InlineData(OidcConstants.AuthorizeErrors.ConsentRequired)] [InlineData(OidcConstants.AuthorizeErrors.InteractionRequired)] public async Task prompt_none_errors_for_anonymous_users_should_include_session_state(string error) { _response.Error = error; _response.Request = new ValidatedAuthorizeRequest { ResponseMode = OidcConstants.ResponseModes.Query, RedirectUri = "http://client/callback", PromptMode = "none", }; _response.SessionState = "some_session_state"; await _subject.ExecuteAsync(_context); _mockUserSession.Clients.Count.Should().Be(0); _context.Response.StatusCode.Should().Be(302); var location = _context.Response.Headers["Location"].First(); location.Should().Contain("session_state=some_session_state"); } [Fact] public async Task access_denied_should_return_to_client() { const string errorDescription = "some error description"; _response.Error = OidcConstants.AuthorizeErrors.AccessDenied; _response.ErrorDescription = errorDescription; _response.Request = new ValidatedAuthorizeRequest { ResponseMode = OidcConstants.ResponseModes.Query, RedirectUri = "http://client/callback" }; await _subject.ExecuteAsync(_context); _mockUserSession.Clients.Count.Should().Be(0); _context.Response.StatusCode.Should().Be(302); var location = _context.Response.Headers["Location"].First(); location.Should().StartWith("http://client/callback"); var queryString = new Uri(location).Query; var queryParams = QueryHelpers.ParseQuery(queryString); queryParams["error"].Should().Equal(OidcConstants.AuthorizeErrors.AccessDenied); queryParams["error_description"].Should().Equal(errorDescription); } [Fact] public async Task success_should_add_client_to_client_list() { _response.Request = new ValidatedAuthorizeRequest { ClientId = "client", ResponseMode = OidcConstants.ResponseModes.Query, RedirectUri = "http://client/callback" }; await _subject.ExecuteAsync(_context); _mockUserSession.Clients.Should().Contain("client"); } [Fact] public async Task query_mode_should_pass_results_in_query() { _response.Request = new ValidatedAuthorizeRequest { ClientId = "client", ResponseMode = OidcConstants.ResponseModes.Query, RedirectUri = "http://client/callback", State = "state" }; await _subject.ExecuteAsync(_context); _context.Response.StatusCode.Should().Be(302); _context.Response.Headers["Cache-Control"].First().Should().Contain("no-store"); _context.Response.Headers["Cache-Control"].First().Should().Contain("no-cache"); _context.Response.Headers["Cache-Control"].First().Should().Contain("max-age=0"); var location = _context.Response.Headers["Location"].First(); location.Should().StartWith("http://client/callback"); location.Should().Contain("?state=state"); } [Fact] public async Task fragment_mode_should_pass_results_in_fragment() { _response.Request = new ValidatedAuthorizeRequest { ClientId = "client", ResponseMode = OidcConstants.ResponseModes.Fragment, RedirectUri = "http://client/callback", State = "state" }; await _subject.ExecuteAsync(_context); _context.Response.StatusCode.Should().Be(302); _context.Response.Headers["Cache-Control"].First().Should().Contain("no-store"); _context.Response.Headers["Cache-Control"].First().Should().Contain("no-cache"); _context.Response.Headers["Cache-Control"].First().Should().Contain("max-age=0"); var location = _context.Response.Headers["Location"].First(); location.Should().StartWith("http://client/callback"); location.Should().Contain("#state=state"); } [Fact] public async Task form_post_mode_should_pass_results_in_body() { _response.Request = new ValidatedAuthorizeRequest { ClientId = "client", ResponseMode = OidcConstants.ResponseModes.FormPost, RedirectUri = "http://client/callback", State = "state" }; await _subject.ExecuteAsync(_context); _context.Response.StatusCode.Should().Be(200); _context.Response.ContentType.Should().StartWith("text/html"); _context.Response.Headers["Cache-Control"].First().Should().Contain("no-store"); _context.Response.Headers["Cache-Control"].First().Should().Contain("no-cache"); _context.Response.Headers["Cache-Control"].First().Should().Contain("max-age=0"); _context.Response.Headers["Content-Security-Policy"].First().Should().Contain("default-src 'none';"); _context.Response.Headers["Content-Security-Policy"].First().Should().Contain("script-src 'sha256-orD0/VhH8hLqrLxKHD/HUEMdwqX6/0ve7c5hspX5VJ8='"); _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("default-src 'none';"); _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("script-src 'sha256-orD0/VhH8hLqrLxKHD/HUEMdwqX6/0ve7c5hspX5VJ8='"); _context.Response.Body.Seek(0, SeekOrigin.Begin); using (var rdr = new StreamReader(_context.Response.Body)) { var html = rdr.ReadToEnd(); html.Should().Contain("<base target='_self'/>"); html.Should().Contain("<form method='post' action='http://client/callback'>"); html.Should().Contain("<input type='hidden' name='state' value='state' />"); } } [Fact] public async Task form_post_mode_should_add_unsafe_inline_for_csp_level_1() { _response.Request = new ValidatedAuthorizeRequest { ClientId = "client", ResponseMode = OidcConstants.ResponseModes.FormPost, RedirectUri = "http://client/callback", State = "state" }; _options.Csp.Level = CspLevel.One; await _subject.ExecuteAsync(_context); _context.Response.Headers["Content-Security-Policy"].First().Should().Contain("script-src 'unsafe-inline' 'sha256-orD0/VhH8hLqrLxKHD/HUEMdwqX6/0ve7c5hspX5VJ8='"); _context.Response.Headers["X-Content-Security-Policy"].First().Should().Contain("script-src 'unsafe-inline' 'sha256-orD0/VhH8hLqrLxKHD/HUEMdwqX6/0ve7c5hspX5VJ8='"); } [Fact] public async Task form_post_mode_should_not_add_deprecated_header_when_it_is_disabled() { _response.Request = new ValidatedAuthorizeRequest { ClientId = "client", ResponseMode = OidcConstants.ResponseModes.FormPost, RedirectUri = "http://client/callback", State = "state" }; _options.Csp.AddDeprecatedHeader = false; await _subject.ExecuteAsync(_context); _context.Response.Headers["Content-Security-Policy"].First().Should().Contain("script-src 'sha256-orD0/VhH8hLqrLxKHD/HUEMdwqX6/0ve7c5hspX5VJ8='"); _context.Response.Headers["X-Content-Security-Policy"].Should().BeEmpty(); } } }
namespace PokerTell.PokerHand.Tests.Analyzation { using System; using Moq; using NUnit.Framework; using PokerTell.Infrastructure.Enumerations.PokerHand; using PokerTell.Infrastructure.Interfaces; using PokerTell.Infrastructure.Interfaces.PokerHand; using PokerTell.Infrastructure.Services; using PokerTell.PokerHand.Analyzation; using PokerTell.PokerHand.Aquisition; using PokerTell.PokerHand.Tests.Factories; using PokerTell.UnitTests; using PokerTell.UnitTests.Tools; [TestFixture] public class ConvertedPokerHandTests : TestWithLog { IConvertedPokerHand _convertedHand; IConstructor<IConvertedPokerPlayer> _convertedPlayerMake; IAquiredPokerHand _aquiredHand; StubBuilder _stub; [SetUp] public void _Init() { _stub = new StubBuilder(); _aquiredHand = new AquiredPokerHand().InitializeWith( _stub.Valid(For.Site, "site"), _stub.Out<ulong>(For.GameId), _stub.Out<DateTime>(For.TimeStamp), _stub.Valid(For.SB, 1.0), _stub.Valid(For.BB, 2.0), _stub.Valid(For.TotalPlayers, 2)); _convertedHand = new ConvertedPokerHand(_aquiredHand); _convertedPlayerMake = new Constructor<IConvertedPokerPlayer>(() => new ConvertedPokerPlayer()); } [Test] public void AddPlayersFrom_NoPlayers_AddsNoPlayers() { _convertedHand.AddPlayersFrom(_aquiredHand, _stub.Out<double>(For.StartingPot), _convertedPlayerMake); Assert.That(_convertedHand.Players.Count, Is.EqualTo(0)); } [Test] public void AddPlayersFrom_TwoPlayers_AddsTwoPlayers() { _stub.Value(For.HoleCards).Is(string.Empty); var player1Stub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player1") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)); var player2Stub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player2") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)); _aquiredHand .AddPlayer(player1Stub.Out) .AddPlayer(player2Stub.Out); _convertedHand.AddPlayersFrom(_aquiredHand, _stub.Out<double>(For.StartingPot), _convertedPlayerMake); Assert.That(_convertedHand.Players.Count, Is.EqualTo(2)); } [Test] public void AddPlayersFrom_ThreePlayers_AddsThreePlayersInSameOrder() { _stub.Value(For.HoleCards).Is(string.Empty); var player1Stub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player1") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)).Out; var player2Stub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player2") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)).Out; var player3Stub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player3") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)).Out; _aquiredHand .AddPlayer(player1Stub) .AddPlayer(player2Stub) .AddPlayer(player3Stub); _convertedHand .AddPlayersFrom(_aquiredHand, _stub.Out<double>(For.StartingPot), _convertedPlayerMake); var addedInSameOrder = _convertedHand[0].Name.Equals(_aquiredHand[0].Name) && _convertedHand[1].Name.Equals(_aquiredHand[1].Name) && _convertedHand[2].Name.Equals(_aquiredHand[2].Name); Assert.That(addedInSameOrder); } [Test] public void AddPlayersFrom_OnePlayer_CalculatesMBeforeCorrectly() { _stub .Value(For.HoleCards).Is(string.Empty) .Value(For.StartingPot).Is(5.0) .Value(For.StackBefore).Is(100.7); var playerStub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player1") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)) .Get(p => p.StackBefore).Returns(_stub.Out<double>(For.StackBefore)).Out; _aquiredHand .AddPlayer(playerStub); _convertedHand .AddPlayersFrom(_aquiredHand, _stub.Out<double>(For.StartingPot), _convertedPlayerMake); var expectedValue = (int)playerStub.StackBefore / _stub.Get<double>(For.StartingPot); Assert.That(_convertedHand[0].MBefore, Is.EqualTo(expectedValue)); } [Test] public void AddPlayersFrom_OnePlayer_CalculatesMAfterCorrectly() { _stub .Value(For.HoleCards).Is(string.Empty) .Value(For.StartingPot).Is(5.0) .Value(For.StackAfter).Is(75.0); var playerStub = _stub.Setup<IAquiredPokerPlayer>() .Get(p => p.Name).Returns("player1") .Get(p => p.Holecards).Returns(_stub.Out<string>(For.HoleCards)) .Get(p => p.StackAfter).Returns(_stub.Out<double>(For.StackAfter)).Out; _aquiredHand .AddPlayer(playerStub); _convertedHand .AddPlayersFrom(_aquiredHand, _stub.Out<double>(For.StartingPot), _convertedPlayerMake); var expectedValue = (int)playerStub.StackAfter / _stub.Get<double>(For.StartingPot); Assert.That(_convertedHand[0].MAfter, Is.EqualTo(expectedValue)); } [Test] public void RemoveInactivePlayers_PlayerHasNoRound_RemovesHim() { var convertedPlayer = new ConvertedPokerPlayer(); _convertedHand .AddPlayer(convertedPlayer) .RemoveInactivePlayers(); Assert.That(_convertedHand.Players.Count, Is.EqualTo(0)); } [Test] public void RemoveInactivePlayers_PlayerHasOneRoundWithoutActions_RemovesHim() { var convertedPlayer = new ConvertedPokerPlayer() .Add(); _convertedHand .AddPlayer(convertedPlayer) .RemoveInactivePlayers(); Assert.That(_convertedHand.Players.Count, Is.EqualTo(0)); } [Test] public void RemoveInactivePlayers_PlayerHasOneRoundWithOneAction_DoesntRemoveHim() { var convertedPlayer = new ConvertedPokerPlayer() .Add( new ConvertedPokerRound() .Add(new ConvertedPokerAction(ActionTypes.F, 1.0))); _convertedHand .AddPlayer(convertedPlayer) .RemoveInactivePlayers(); Assert.That(_convertedHand.Players.Count, Is.EqualTo(1)); } [Test] public void SetNumberOfPlayersInEachRound_ThreePreflopPlayers_SetsPlayersInPreflopRoundToThree() { _convertedHand .AddPlayer(new ConvertedPokerPlayer { Name = "player1" }.Add()) .AddPlayer(new ConvertedPokerPlayer { Name = "player2" }.Add()) .AddPlayer(new ConvertedPokerPlayer { Name = "player3" }.Add()) .SetNumOfPlayersInEachRound(); Assert.That(_convertedHand.PlayersInRound[(int)Streets.PreFlop], Is.EqualTo(3)); } [Test] public void SetNumberOfPlayersInEachRound_ThreePlayersTwoHaveFlopRound_SetsPlayersInFlopRoundToTwo() { _convertedHand .AddPlayer(new ConvertedPokerPlayer { Name = "player1" }.Add().Add()) .AddPlayer(new ConvertedPokerPlayer { Name = "player2" }.Add()) .AddPlayer(new ConvertedPokerPlayer { Name = "player3" }.Add().Add()) .SetNumOfPlayersInEachRound(); Assert.That(_convertedHand.PlayersInRound[(int)Streets.Flop], Is.EqualTo(2)); } [Test] public void SetWhoHasPositionInEachRound_TwoPlayersPreflop_SetsSecondPlayerInPositionPreflopToOne() { var player1 = new ConvertedPokerPlayer { Name = "player1" }.Add(); var player2 = new ConvertedPokerPlayer { Name = "player2" }.Add(); _convertedHand .AddPlayer(player1) .AddPlayer(player2) .SetWhoHasPositionInEachRound(); player2.InPosition[(int)Streets.PreFlop].ShouldBeTrue(); } [Test] public void SetWhoHasPositionInEachRound_TwoPlayersPreflop_SetsFirstPlayerInPositionPreflopToFalse() { var player1 = new ConvertedPokerPlayer { Name = "player1" }.Add(); var player2 = new ConvertedPokerPlayer { Name = "player2" }.Add(); _convertedHand .AddPlayer(player1) .AddPlayer(player2) .SetWhoHasPositionInEachRound(); player1.InPosition[(int)Streets.PreFlop].ShouldBeFalse(); } [Test] public void AffirmIsEqualTo_InitializedHandsAreEqual_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = InitializeConvertedHandWithSomeValidValues(); Affirm.That(hand1).IsEqualTo(hand2); } [Test] public void AffirmIsEqualTo_HandsWithSamePlayersAreEqual_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues() .AddPlayer(new ConvertedPokerPlayer { Name = "player1" }); var hand2 = InitializeConvertedHandWithSomeValidValues() .AddPlayer(new ConvertedPokerPlayer { Name = "player1" }); Affirm.That(hand1).IsEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsWithDifferentNumberOfPlayersAreEqual_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues() .AddPlayer(new ConvertedPokerPlayer { Name = "player1" }) .AddPlayer(new ConvertedPokerPlayer { Name = "player2" }); var hand2 = InitializeConvertedHandWithSomeValidValues() .AddPlayer(new ConvertedPokerPlayer { Name = "player1" }); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsWithDifferentPlayersAreEqual_Passes() { var player1 = ConvertedFactory.InitializeConvertedPokerPlayerWithSomeValidValues(); player1.Name = "player1"; var player2 = ConvertedFactory.InitializeConvertedPokerPlayerWithSomeValidValues(); player2.Name = player1.Name + "difference"; var hand1 = InitializeConvertedHandWithSomeValidValues() .AddPlayer(player1); var hand2 = InitializeConvertedHandWithSomeValidValues() .AddPlayer(player2); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsGameIdsAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = new ConvertedPokerHand( hand1.Site, hand1.GameId + 1, hand1.TimeStamp, hand1.BB, hand1.SB, hand1.TotalPlayers); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsSitesAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = new ConvertedPokerHand( hand1.Site + "different", hand1.GameId, hand1.TimeStamp, hand1.BB, hand1.SB, hand1.TotalPlayers); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsSmallBlindssAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = new ConvertedPokerHand( hand1.Site, hand1.GameId, hand1.TimeStamp, hand1.BB, hand1.SB + 1, hand1.TotalPlayers); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsTotalPlayerssAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = new ConvertedPokerHand( hand1.Site, hand1.GameId, hand1.TimeStamp, hand1.BB, hand1.SB, hand1.TotalPlayers + 1); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsBigBlindsAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = new ConvertedPokerHand( hand1.Site, hand1.GameId, hand1.TimeStamp, hand1.BB + 1, hand1.SB, hand1.TotalPlayers); Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsTableNamesAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = InitializeConvertedHandWithSomeValidValues(); hand2.TableName = hand1.TableName + "difference"; Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsTournamentIdsAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = InitializeConvertedHandWithSomeValidValues(); hand2.TournamentId = hand1.TournamentId + 1; Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void AffirmIsNotEqualTo_HandsAntesAreDifferent_Passes() { var hand1 = InitializeConvertedHandWithSomeValidValues(); var hand2 = InitializeConvertedHandWithSomeValidValues(); hand2.Ante = hand1.Ante + 1; Affirm.That(hand1).IsNotEqualTo(hand2); } [Test] public void BinaryDeserialize_UnInitializedConvertedHand_ReturnsSameHand() { Affirm.That(_convertedHand.BinaryDeserializedInMemory()).IsEqualTo(_convertedHand); } [Test] public void BinaryDeserialize_InitializedConvertedHand_ReturnsSameHand() { var convertedHand = InitializeConvertedHandWithSomeValidValues(); Affirm.That(convertedHand.BinaryDeserializedInMemory()).IsEqualTo(convertedHand); } [Test] public void BinaryDeserialize_ConvertedHandWithEmptyPlayer_ReturnsSameHand() { var convertedHand = InitializeConvertedHandWithSomeValidValues(); convertedHand.AddPlayer(new ConvertedPokerPlayer()); Affirm.That(convertedHand.BinaryDeserializedInMemory()).IsEqualTo(convertedHand); } [Test] public void BinaryDeserialize_ConvertedHandWithInitializedPlayer_ReturnsSameHand() { var convertedHand = InitializeConvertedHandWithSomeValidValues(); convertedHand.AddPlayer(ConvertedFactory.InitializeConvertedPokerPlayerWithSomeValidValues()); Affirm.That(convertedHand.BinaryDeserializedInMemory()).IsEqualTo(convertedHand); } [Test] public void BinaryDeserialize_ConvertedHandTwoInitializedPlayers_ReturnsSameHand() { var convertedHand = InitializeConvertedHandWithSomeValidValues(); convertedHand .AddPlayer(ConvertedFactory.InitializeConvertedPokerPlayerWithSomeValidValues()) .AddPlayer(ConvertedFactory.InitializeConvertedPokerPlayerWithSomeValidValues()); Affirm.That(convertedHand.BinaryDeserializedInMemory()).IsEqualTo(convertedHand); } static IConvertedPokerHand InitializeConvertedHandWithSomeValidValues() { return new ConvertedPokerHand().InitializeWith("someSite", 1, DateTime.MinValue, 2.0, 1.0, 6); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Data = Microsoft.PowerShell.CrossCompatibility.Data; namespace Microsoft.PowerShell.CrossCompatibility.Query { /// <summary> /// Readonly query object for collected data about commands and types available in a PowerShell runtime. /// </summary> public class RuntimeData { /// <summary> /// Create a new query object around collected PowerShell runtime data. /// </summary> /// <param name="runtimeData">The collected PowerShell runtime data object.</param> public RuntimeData(Data.RuntimeData runtimeData) { Types = new AvailableTypeData(runtimeData.Types); Common = new CommonPowerShellData(runtimeData.Common); Modules = CreateModuleTable(runtimeData.Modules); NonAliasCommands = CreateNonAliasCommandLookupTable(Modules); Aliases = CreateAliasLookupTable(runtimeData.Modules, NonAliasCommands); SetModuleAliases(runtimeData.Modules); Commands = new DualLookupTable<string, IReadOnlyList<CommandData>>(NonAliasCommands, Aliases); NativeCommands = NativeCommandLookupTable.Create(runtimeData.NativeCommands); } /// <summary> /// All the types and type accelerators available in the PowerShell runtime. /// </summary> public AvailableTypeData Types { get; } /// <summary> /// All the default modules available to the PowerShell runtime, keyed by module name and then version. /// </summary> /// <value></value> public IReadOnlyDictionary<string, IReadOnlyDictionary<Version, ModuleData>> Modules { get; } /// <summary> /// A lookup table for commands from modules. /// </summary> public IReadOnlyDictionary<string, IReadOnlyList<CommandData>> Commands { get; } /// <summary> /// All the native commands/applications available to PowerShell. /// </summary> public NativeCommandLookupTable NativeCommands { get; } /// <summary> /// PowerShell runtime data not confined to a module. /// </summary> public CommonPowerShellData Common { get; } internal IReadOnlyDictionary<string, IReadOnlyList<CommandData>> NonAliasCommands { get; } internal IReadOnlyDictionary<string, IReadOnlyList<CommandData>> Aliases { get; } private static IReadOnlyDictionary<string, IReadOnlyDictionary<Version, ModuleData>> CreateModuleTable(IDictionary<string, JsonDictionary<Version, Data.ModuleData>> modules) { var moduleDict = new Dictionary<string, IReadOnlyDictionary<Version, ModuleData>>(modules.Count, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, JsonDictionary<Version, Data.ModuleData>> moduleVersions in modules) { var moduleVersionDict = new Dictionary<Version, ModuleData>(moduleVersions.Value.Count); foreach (KeyValuePair<Version, Data.ModuleData> module in moduleVersions.Value) { moduleVersionDict[module.Key] = new ModuleData(name: moduleVersions.Key, version: module.Key, moduleData: module.Value); } moduleDict[moduleVersions.Key] = moduleVersionDict; } return moduleDict; } private void SetModuleAliases(JsonCaseInsensitiveStringDictionary<JsonDictionary<Version, Data.ModuleData>> moduleData) { foreach (KeyValuePair<string, IReadOnlyDictionary<Version, ModuleData>> moduleVersions in Modules) { foreach (KeyValuePair<Version, ModuleData> module in moduleVersions.Value) { module.Value.SetAliasTable(this, moduleData[moduleVersions.Key][module.Key].Aliases); } } } private static IReadOnlyDictionary<string, IReadOnlyList<CommandData>> CreateNonAliasCommandLookupTable( IReadOnlyDictionary<string, IReadOnlyDictionary<Version, ModuleData>> modules) { var commandTable = new Dictionary<string, IReadOnlyList<CommandData>>(StringComparer.OrdinalIgnoreCase); foreach (IReadOnlyDictionary<Version, ModuleData> moduleVersions in modules.Values) { foreach (ModuleData module in moduleVersions.Values) { if (module.Cmdlets != null) { foreach (KeyValuePair<string, CmdletData> cmdlet in module.Cmdlets) { if (!commandTable.ContainsKey(cmdlet.Key)) { commandTable.Add(cmdlet.Key, new List<CommandData>()); } ((List<CommandData>)commandTable[cmdlet.Key]).Add(cmdlet.Value); } } if (module.Functions != null) { foreach (KeyValuePair<string, FunctionData> function in module.Functions) { if (!commandTable.ContainsKey(function.Key)) { commandTable.Add(function.Key, new List<CommandData>()); } ((List<CommandData>)commandTable[function.Key]).Add(function.Value); } } } } return commandTable; } private static IReadOnlyDictionary<string, IReadOnlyList<CommandData>> CreateAliasLookupTable( IReadOnlyDictionary<string, JsonDictionary<Version, Data.ModuleData>> modules, IReadOnlyDictionary<string, IReadOnlyList<CommandData>> commands) { var aliasTable = new Dictionary<string, IReadOnlyList<CommandData>>(); foreach (KeyValuePair<string, JsonDictionary<Version, Data.ModuleData>> module in modules) { foreach (KeyValuePair<Version, Data.ModuleData> moduleVersion in module.Value) { if (moduleVersion.Value.Aliases == null) { continue; } foreach (KeyValuePair<string, string> alias in moduleVersion.Value.Aliases) { if (commands.TryGetValue(alias.Value, out IReadOnlyList<CommandData> aliasedCommands)) { aliasTable[alias.Key] = aliasedCommands; } } } } return aliasTable; } private class DualLookupTable<K, V> : IReadOnlyDictionary<K, V> { private readonly IReadOnlyDictionary<K, V> _firstTable; private readonly IReadOnlyDictionary<K, V> _secondTable; public DualLookupTable(IReadOnlyDictionary<K, V> firstTable, IReadOnlyDictionary<K, V> secondTable) { _firstTable = firstTable; _secondTable = secondTable; } public V this[K key] { get { if (_firstTable.TryGetValue(key, out V firstValue)) { return firstValue; } if (_secondTable.TryGetValue(key, out V secondValue)) { return secondValue; } throw new KeyNotFoundException(); } } public IEnumerable<K> Keys => _firstTable.Keys.Concat(_secondTable.Keys); public IEnumerable<V> Values => _firstTable.Values.Concat(_secondTable.Values); public int Count => _firstTable.Count + _secondTable.Count; public bool ContainsKey(K key) { return _firstTable.ContainsKey(key) || _secondTable.ContainsKey(key); } public IEnumerator<KeyValuePair<K, V>> GetEnumerator() { return _firstTable.Concat(_secondTable).GetEnumerator(); } public bool TryGetValue(K key, out V value) { return _firstTable.TryGetValue(key, out value) || _secondTable.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using EBE.Core.ExpressionIterators; using System.Text.RegularExpressions; namespace EBE.Core.Evaluation { /// <summary> /// Expression containing operators and values. /// </summary> /// <remarks> /// http://stackoverflow.com/questions/17568067/how-to-parse-a-boolean-expression-and-load-it-into-a-class/17572545#17572545 /// </remarks> public class Expression { private int _maxBits; private Dictionary<string, int> _variables; private List<string> _variableKeys; private ExpressionNode _root; private static Regex rgx = new Regex("[0-9]", RegexOptions.IgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="EBE.Core.Evaluation.Expression"/> class. /// </summary> /// <param name="maxBits">Max number of bits.</param> public Expression(int maxBits) { _variables = new Dictionary<string, int>(); _variableKeys = new List<string>(); _maxBits = maxBits; } /// <summary> /// Gets the root node of the expression. /// </summary> public ExpressionNode Root { get { return _root; } private set { _root = value; } } /// <summary> /// Map for variables to values. /// </summary> public Dictionary<string, int> Variables { get { return _variables; } } /// <summary> /// Gets the variable keys. /// </summary> /// <value>The variable keys.</value> public List<string> VariableKeys { get { return _variableKeys; } } /// <summary> /// Parses string into expression. /// </summary> /// <param name="expression">Expression to parse.</param> public void Parse(string expression) { List<Token> tokens = new List<Token>(); StringReader reader = new StringReader(expression); //Tokenize the expression Token t = null; do { t = new Token(reader); tokens.Add(t); } while (t.type != Token.TokenType.EXPR_END); //Use a minimal version of the Shunting Yard algorithm to transform the token list to polish notation List<Token> polishNotation = TransformToPolishNotation(tokens); var enumerator = polishNotation.GetEnumerator(); enumerator.MoveNext(); Root = Make(ref enumerator); } /// <summary> /// Parser helper. /// </summary> /// <param name="polishNotationTokensEnumerator">Polish notation tokens enumerator.</param> private ExpressionNode Make(ref List<Token>.Enumerator polishNotationTokensEnumerator) { if (polishNotationTokensEnumerator.Current.type == Token.TokenType.LITERAL) { ExpressionNode lit = new ExpressionNode(); lit.Value = polishNotationTokensEnumerator.Current.value; int intValue = 0; if (rgx.IsMatch(lit.Value)) { intValue = int.Parse(lit.Value); } if (!_variables.ContainsKey(lit.Value)) { _variables.Add(lit.Value, intValue); _variableKeys.Add(lit.Value); } polishNotationTokensEnumerator.MoveNext(); return lit; } else if (polishNotationTokensEnumerator.Current.type == Token.TokenType.BINARY_OP || polishNotationTokensEnumerator.Current.type == Token.TokenType.TBINARY_OP) { ExpressionNode node = new ExpressionNode(); node.Operator = OperatorBase.Parse(polishNotationTokensEnumerator.Current.value, _maxBits); polishNotationTokensEnumerator.MoveNext(); node.Left = Make(ref polishNotationTokensEnumerator); node.Right = Make(ref polishNotationTokensEnumerator); return node; } return null; } /// <summary> /// Helper functino to transform to polish notation. /// </summary> /// <returns>List of tokens in polish notation.</returns> /// <param name="infixTokenList">Infix token list.</param> private static List<Token> TransformToPolishNotation(List<Token> infixTokenList) { Queue<Token> outputQueue = new Queue<Token>(); Stack<Token> stack = new Stack<Token>(); int index = 0; while (infixTokenList.Count > index) { Token t = infixTokenList[index]; switch (t.type) { case Token.TokenType.LITERAL: outputQueue.Enqueue(t); break; case Token.TokenType.TBINARY_OP: case Token.TokenType.BINARY_OP: case Token.TokenType.UNARY_OP: case Token.TokenType.OPEN_PAREN: stack.Push(t); break; case Token.TokenType.CLOSE_PAREN: while (stack.Peek().type != Token.TokenType.OPEN_PAREN) { outputQueue.Enqueue(stack.Pop()); } stack.Pop(); if (stack.Count > 0 && stack.Peek().type == Token.TokenType.UNARY_OP) { outputQueue.Enqueue(stack.Pop()); } break; default: break; } ++index; } while (stack.Count > 0) { outputQueue.Enqueue(stack.Pop()); } return outputQueue.Reverse().ToList(); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// AddressInformationV2 /// </summary> [DataContract] public partial class AddressInformationV2 : IEquatable<AddressInformationV2>, IValidatableObject { public AddressInformationV2() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="AddressInformationV2" /> class. /// </summary> /// <param name="Address1">First Line of the address. Maximum length: 100 characters..</param> /// <param name="Address2">Second Line of the address. Maximum length: 100 characters..</param> /// <param name="City">.</param> /// <param name="Country">Specifies the country associated with the address..</param> /// <param name="Fax">.</param> /// <param name="Phone">.</param> /// <param name="PostalCode">.</param> /// <param name="StateOrProvince">The state or province associated with the address..</param> public AddressInformationV2(string Address1 = default(string), string Address2 = default(string), string City = default(string), string Country = default(string), string Fax = default(string), string Phone = default(string), string PostalCode = default(string), string StateOrProvince = default(string)) { this.Address1 = Address1; this.Address2 = Address2; this.City = City; this.Country = Country; this.Fax = Fax; this.Phone = Phone; this.PostalCode = PostalCode; this.StateOrProvince = StateOrProvince; } /// <summary> /// First Line of the address. Maximum length: 100 characters. /// </summary> /// <value>First Line of the address. Maximum length: 100 characters.</value> [DataMember(Name="address1", EmitDefaultValue=false)] public string Address1 { get; set; } /// <summary> /// Second Line of the address. Maximum length: 100 characters. /// </summary> /// <value>Second Line of the address. Maximum length: 100 characters.</value> [DataMember(Name="address2", EmitDefaultValue=false)] public string Address2 { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Specifies the country associated with the address. /// </summary> /// <value>Specifies the country associated with the address.</value> [DataMember(Name="country", EmitDefaultValue=false)] public string Country { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="fax", EmitDefaultValue=false)] public string Fax { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="postalCode", EmitDefaultValue=false)] public string PostalCode { get; set; } /// <summary> /// The state or province associated with the address. /// </summary> /// <value>The state or province associated with the address.</value> [DataMember(Name="stateOrProvince", EmitDefaultValue=false)] public string StateOrProvince { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AddressInformationV2 {\n"); sb.Append(" Address1: ").Append(Address1).Append("\n"); sb.Append(" Address2: ").Append(Address2).Append("\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" Fax: ").Append(Fax).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); sb.Append(" StateOrProvince: ").Append(StateOrProvince).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as AddressInformationV2); } /// <summary> /// Returns true if AddressInformationV2 instances are equal /// </summary> /// <param name="other">Instance of AddressInformationV2 to be compared</param> /// <returns>Boolean</returns> public bool Equals(AddressInformationV2 other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Address1 == other.Address1 || this.Address1 != null && this.Address1.Equals(other.Address1) ) && ( this.Address2 == other.Address2 || this.Address2 != null && this.Address2.Equals(other.Address2) ) && ( this.City == other.City || this.City != null && this.City.Equals(other.City) ) && ( this.Country == other.Country || this.Country != null && this.Country.Equals(other.Country) ) && ( this.Fax == other.Fax || this.Fax != null && this.Fax.Equals(other.Fax) ) && ( this.Phone == other.Phone || this.Phone != null && this.Phone.Equals(other.Phone) ) && ( this.PostalCode == other.PostalCode || this.PostalCode != null && this.PostalCode.Equals(other.PostalCode) ) && ( this.StateOrProvince == other.StateOrProvince || this.StateOrProvince != null && this.StateOrProvince.Equals(other.StateOrProvince) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Address1 != null) hash = hash * 59 + this.Address1.GetHashCode(); if (this.Address2 != null) hash = hash * 59 + this.Address2.GetHashCode(); if (this.City != null) hash = hash * 59 + this.City.GetHashCode(); if (this.Country != null) hash = hash * 59 + this.Country.GetHashCode(); if (this.Fax != null) hash = hash * 59 + this.Fax.GetHashCode(); if (this.Phone != null) hash = hash * 59 + this.Phone.GetHashCode(); if (this.PostalCode != null) hash = hash * 59 + this.PostalCode.GetHashCode(); if (this.StateOrProvince != null) hash = hash * 59 + this.StateOrProvince.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// BranchImpl /// </summary> [DataContract(Name = "BranchImpl")] public partial class BranchImpl : IEquatable<BranchImpl>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="BranchImpl" /> class. /// </summary> /// <param name="_class">_class.</param> /// <param name="displayName">displayName.</param> /// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param> /// <param name="fullDisplayName">fullDisplayName.</param> /// <param name="fullName">fullName.</param> /// <param name="name">name.</param> /// <param name="organization">organization.</param> /// <param name="parameters">parameters.</param> /// <param name="permissions">permissions.</param> /// <param name="weatherScore">weatherScore.</param> /// <param name="pullRequest">pullRequest.</param> /// <param name="links">links.</param> /// <param name="latestRun">latestRun.</param> public BranchImpl(string _class = default(string), string displayName = default(string), int estimatedDurationInMillis = default(int), string fullDisplayName = default(string), string fullName = default(string), string name = default(string), string organization = default(string), List<StringParameterDefinition> parameters = default(List<StringParameterDefinition>), BranchImplpermissions permissions = default(BranchImplpermissions), int weatherScore = default(int), string pullRequest = default(string), BranchImpllinks links = default(BranchImpllinks), PipelineRunImpl latestRun = default(PipelineRunImpl)) { this.Class = _class; this.DisplayName = displayName; this.EstimatedDurationInMillis = estimatedDurationInMillis; this.FullDisplayName = fullDisplayName; this.FullName = fullName; this.Name = name; this.Organization = organization; this.Parameters = parameters; this.Permissions = permissions; this.WeatherScore = weatherScore; this.PullRequest = pullRequest; this.Links = links; this.LatestRun = latestRun; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Gets or Sets DisplayName /// </summary> [DataMember(Name = "displayName", EmitDefaultValue = false)] public string DisplayName { get; set; } /// <summary> /// Gets or Sets EstimatedDurationInMillis /// </summary> [DataMember(Name = "estimatedDurationInMillis", EmitDefaultValue = false)] public int EstimatedDurationInMillis { get; set; } /// <summary> /// Gets or Sets FullDisplayName /// </summary> [DataMember(Name = "fullDisplayName", EmitDefaultValue = false)] public string FullDisplayName { get; set; } /// <summary> /// Gets or Sets FullName /// </summary> [DataMember(Name = "fullName", EmitDefaultValue = false)] public string FullName { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Gets or Sets Organization /// </summary> [DataMember(Name = "organization", EmitDefaultValue = false)] public string Organization { get; set; } /// <summary> /// Gets or Sets Parameters /// </summary> [DataMember(Name = "parameters", EmitDefaultValue = false)] public List<StringParameterDefinition> Parameters { get; set; } /// <summary> /// Gets or Sets Permissions /// </summary> [DataMember(Name = "permissions", EmitDefaultValue = false)] public BranchImplpermissions Permissions { get; set; } /// <summary> /// Gets or Sets WeatherScore /// </summary> [DataMember(Name = "weatherScore", EmitDefaultValue = false)] public int WeatherScore { get; set; } /// <summary> /// Gets or Sets PullRequest /// </summary> [DataMember(Name = "pullRequest", EmitDefaultValue = false)] public string PullRequest { get; set; } /// <summary> /// Gets or Sets Links /// </summary> [DataMember(Name = "_links", EmitDefaultValue = false)] public BranchImpllinks Links { get; set; } /// <summary> /// Gets or Sets LatestRun /// </summary> [DataMember(Name = "latestRun", EmitDefaultValue = false)] public PipelineRunImpl LatestRun { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class BranchImpl {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n"); sb.Append(" FullDisplayName: ").Append(FullDisplayName).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Organization: ").Append(Organization).Append("\n"); sb.Append(" Parameters: ").Append(Parameters).Append("\n"); sb.Append(" Permissions: ").Append(Permissions).Append("\n"); sb.Append(" WeatherScore: ").Append(WeatherScore).Append("\n"); sb.Append(" PullRequest: ").Append(PullRequest).Append("\n"); sb.Append(" Links: ").Append(Links).Append("\n"); sb.Append(" LatestRun: ").Append(LatestRun).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as BranchImpl); } /// <summary> /// Returns true if BranchImpl instances are equal /// </summary> /// <param name="input">Instance of BranchImpl to be compared</param> /// <returns>Boolean</returns> public bool Equals(BranchImpl input) { if (input == null) { return false; } return ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ) && ( this.DisplayName == input.DisplayName || (this.DisplayName != null && this.DisplayName.Equals(input.DisplayName)) ) && ( this.EstimatedDurationInMillis == input.EstimatedDurationInMillis || this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis) ) && ( this.FullDisplayName == input.FullDisplayName || (this.FullDisplayName != null && this.FullDisplayName.Equals(input.FullDisplayName)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Organization == input.Organization || (this.Organization != null && this.Organization.Equals(input.Organization)) ) && ( this.Parameters == input.Parameters || this.Parameters != null && input.Parameters != null && this.Parameters.SequenceEqual(input.Parameters) ) && ( this.Permissions == input.Permissions || (this.Permissions != null && this.Permissions.Equals(input.Permissions)) ) && ( this.WeatherScore == input.WeatherScore || this.WeatherScore.Equals(input.WeatherScore) ) && ( this.PullRequest == input.PullRequest || (this.PullRequest != null && this.PullRequest.Equals(input.PullRequest)) ) && ( this.Links == input.Links || (this.Links != null && this.Links.Equals(input.Links)) ) && ( this.LatestRun == input.LatestRun || (this.LatestRun != null && this.LatestRun.Equals(input.LatestRun)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } if (this.DisplayName != null) { hashCode = (hashCode * 59) + this.DisplayName.GetHashCode(); } hashCode = (hashCode * 59) + this.EstimatedDurationInMillis.GetHashCode(); if (this.FullDisplayName != null) { hashCode = (hashCode * 59) + this.FullDisplayName.GetHashCode(); } if (this.FullName != null) { hashCode = (hashCode * 59) + this.FullName.GetHashCode(); } if (this.Name != null) { hashCode = (hashCode * 59) + this.Name.GetHashCode(); } if (this.Organization != null) { hashCode = (hashCode * 59) + this.Organization.GetHashCode(); } if (this.Parameters != null) { hashCode = (hashCode * 59) + this.Parameters.GetHashCode(); } if (this.Permissions != null) { hashCode = (hashCode * 59) + this.Permissions.GetHashCode(); } hashCode = (hashCode * 59) + this.WeatherScore.GetHashCode(); if (this.PullRequest != null) { hashCode = (hashCode * 59) + this.PullRequest.GetHashCode(); } if (this.Links != null) { hashCode = (hashCode * 59) + this.Links.GetHashCode(); } if (this.LatestRun != null) { hashCode = (hashCode * 59) + this.LatestRun.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace System.Windows.Forms { public class RibbonProfesionalRendererColorTableHalloween : RibbonProfesionalRendererColorTable { public RibbonProfesionalRendererColorTableHalloween() { #region Fields OrbDropDownDarkBorder = ToGray(OrbDropDownDarkBorder); OrbDropDownLightBorder = ToGray(OrbDropDownLightBorder); OrbDropDownBack = ToGray(OrbDropDownBack); OrbDropDownNorthA = ToGray(OrbDropDownNorthA); OrbDropDownNorthB = ToGray(OrbDropDownNorthB); OrbDropDownNorthC = ToGray(OrbDropDownNorthC); OrbDropDownNorthD = ToGray(OrbDropDownNorthD); OrbDropDownSouthC = ToGray(OrbDropDownSouthC); OrbDropDownSouthD = ToGray(OrbDropDownSouthD); OrbDropDownContentbg = ToGray(OrbDropDownContentbg); OrbDropDownContentbglight = ToGray(OrbDropDownContentbglight); OrbDropDownSeparatorlight = ToGray(OrbDropDownSeparatorlight); OrbDropDownSeparatordark = ToGray(OrbDropDownSeparatordark); //################################################################################### //Top Border Background of the Ribbon. Bar is made of 4 rectangles height of each //is indicated below. //################################################################################### Caption1 = ToGray(Caption1); //4 Caption2 = ToGray(Caption2); Caption3 = ToGray(Caption3); //4 Caption4 = ToGray(Caption4); Caption5 = ToGray(Caption5); //23 Caption6 = ToGray(Caption6); Caption7 = ToGray(Caption7); //1 QuickAccessBorderDark = ToGray(QuickAccessBorderDark); QuickAccessBorderLight = ToGray(QuickAccessBorderLight); QuickAccessUpper = ToGray(QuickAccessUpper); QuickAccessLower = ToGray(QuickAccessLower); OrbOptionBorder = ToGray(OrbOptionBorder); OrbOptionBackground = ToGray(OrbOptionBackground); OrbOptionShine = ToGray(OrbOptionShine); Arrow = FromHex("#7C7C7C"); ArrowLight = FromHex("#EAF2F9"); ArrowDisabled = FromHex("#7C7C7C"); Text = FromHex("#000000"); //################################################################################### //Main backGround for the Ribbon. //################################################################################### RibbonBackground = FromHex("#535353");//For Theme change this //################################################################################### //Tab backGround for the Ribbon. //################################################################################### TabBorder = FromHex("#BEBEBE"); TabNorth = FromHex("#F1F2F2"); TabSouth = FromHex("#D6D9DF"); TabGlow = FromHex("#D1FBFF"); TabSelectedGlow = FromHex("#E1D2A5"); TabText = Color.White; TabActiveText = Color.Black; //################################################################################### //Tab Content backGround for the Ribbon. //################################################################################### TabContentNorth = FromHex("#B6BCC6"); TabContentSouth = FromHex("#E6F0F1"); //################################################################################### //Borders(Drop Shadow) for the Panels (Dark = Outer Edge) (Light = Inner Edge) //################################################################################### PanelDarkBorder = FromHex("#AEB0B4"); //Color.FromArgb(51, FromHex("#FF0000"));//For Theme change this PanelLightBorder = FromHex("#E7E9ED"); //Color.FromArgb(102, Color.White);//For Theme change this PanelTextBackground = FromHex("#ABAEAE"); PanelTextBackgroundSelected = FromHex("#949495"); PanelText = Color.White; PanelBackgroundSelected = FromHex("#F3F5F5"); // Color.FromArgb(102, FromHex("#E8FFFD"));//For Theme change this PanelOverflowBackground = FromHex("#B9D1F0"); PanelOverflowBackgroundPressed = FromHex("#AAAEB3"); PanelOverflowBackgroundSelectedNorth = Color.FromArgb(100, Color.White); PanelOverflowBackgroundSelectedSouth = Color.FromArgb(102, FromHex("#EBEBEB")); ButtonBgOut = FromHex("#B4B9C2"); // FromHex("#C1D5F1");//For Theme change this ButtonBgCenter = FromHex("#CDD2D8"); ButtonBorderOut = FromHex("#A9B1B8"); ButtonBorderIn = FromHex("#DFE2E6"); ButtonGlossyNorth = FromHex("#DBDFE4"); ButtonGlossySouth = FromHex("#DFE2E8"); ButtonDisabledBgOut = FromHex("#E0E4E8"); ButtonDisabledBgCenter = FromHex("#E8EBEF"); ButtonDisabledBorderOut = FromHex("#C5D1DE"); ButtonDisabledBorderIn = FromHex("#F1F3F5"); ButtonDisabledGlossyNorth = FromHex("#F0F3F6"); ButtonDisabledGlossySouth = FromHex("#EAEDF1"); ButtonSelectedBgOut = FromHex("#FFD646"); ButtonSelectedBgCenter = FromHex("#FFEAAC"); ButtonSelectedBorderOut = FromHex("#C2A978"); ButtonSelectedBorderIn = FromHex("#FFF2C7"); ButtonSelectedGlossyNorth = FromHex("#FFFDDB"); ButtonSelectedGlossySouth = FromHex("#FFE793"); ButtonPressedBgOut = FromHex("#F88F2C"); ButtonPressedBgCenter = FromHex("#FDF1B0"); ButtonPressedBorderOut = FromHex("#8E8165"); ButtonPressedBorderIn = FromHex("#F9C65A"); ButtonPressedGlossyNorth = FromHex("#FDD5A8"); ButtonPressedGlossySouth = FromHex("#FBB062"); ButtonCheckedBgOut = FromHex("#F9AA45"); ButtonCheckedBgCenter = FromHex("#FDEA9D"); ButtonCheckedBorderOut = FromHex("#8E8165"); ButtonCheckedBorderIn = FromHex("#F9C65A"); ButtonCheckedGlossyNorth = FromHex("#F8DBB7"); ButtonCheckedGlossySouth = FromHex("#FED18E"); ItemGroupOuterBorder = FromHex("#ADB7BB"); ItemGroupInnerBorder = Color.FromArgb(51, Color.White); ItemGroupSeparatorLight = Color.FromArgb(64, Color.White); ItemGroupSeparatorDark = Color.FromArgb(38, FromHex("#ADB7BB")); ItemGroupBgNorth = FromHex("#D9E0E1"); ItemGroupBgSouth = FromHex("#EDF0F1"); ItemGroupBgGlossy = FromHex("#D2D9DB"); ButtonListBorder = FromHex("#ACACAC"); ButtonListBg = FromHex("#DAE2E2"); ButtonListBgSelected = FromHex("#F7F7F7"); DropDownBg = FromHex("#FAFAFA"); DropDownImageBg = FromHex("#E9EEEE"); DropDownImageSeparator = FromHex("#C5C5C5"); DropDownBorder = FromHex("#868686"); DropDownGripNorth = FromHex("#FFFFFF"); DropDownGripSouth = FromHex("#DFE9EF"); DropDownGripBorder = FromHex("#DDE7EE"); DropDownGripDark = FromHex("#5574A7"); DropDownGripLight = FromHex("#FFFFFF"); SeparatorLight = FromHex("#E6E8EB"); SeparatorDark = FromHex("#C5C5C5"); SeparatorBg = FromHex("#EBEBEB"); SeparatorLine = FromHex("#C5C5C5"); TextBoxUnselectedBg = FromHex("#E8E8E8"); TextBoxBorder = FromHex("#898989"); ToolStripItemTextPressed = FromHex("#262626"); ToolStripItemTextSelected = FromHex("#262626"); ToolStripItemText = FromHex("#0072C6"); clrVerBG_Shadow = Color.FromArgb(255, 181, 190, 206); /// <summary> /// 2013 Colors /// Office 2013 Dark Theme /// </summary> ButtonPressed_2013 = FromHex("#92C0E0"); ButtonSelected_2013 = FromHex("#CDE6F7"); OrbButton_2013 = FromHex("#333333"); OrbButtonSelected_2013 = FromHex("#2A8AD4"); OrbButtonPressed_2013 = FromHex("#2A8AD4"); TabText_2013 = FromHex("#0072C6"); TabTextSelected_2013 = FromHex("#262626"); PanelBorder_2013 = FromHex("#15428B"); RibbonBackground_2013 = FromHex("#DEDEDE"); TabCompleteBackground_2013 = FromHex("#F3F3F3"); TabNormalBackground_2013 = FromHex("#DEDEDE"); TabActiveBackbround_2013 = FromHex("#F3F3F3"); TabBorder_2013 = FromHex("#ABABAB"); TabCompleteBorder_2013 = FromHex("#ABABAB"); TabActiveBorder_2013 = FromHex("#ABABAB"); OrbButtonText_2013 = FromHex("#FFFFFF"); PanelText_2013 = FromHex("#262626"); RibbonItemText_2013 = FromHex("#262626"); ToolTipText_2013 = FromHex("#262626"); ToolStripItemTextPressed_2013 = FromHex("#262626"); ToolStripItemTextSelected_2013 = FromHex("#262626"); ToolStripItemText_2013 = FromHex("#0072C6"); #endregion } } }
/* * Copyright 2012-2016 The Pkcs11Interop 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI81; using Net.Pkcs11Interop.LowLevelAPI81.MechanismParams; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.LowLevelAPI81 { /// <summary> /// C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_Decrypt, C_DecryptUpdate and C_DecryptFinish tests. /// </summary> [TestFixture()] public class _20_EncryptAndDecryptTest { /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test. /// </summary> [Test()] public void _01_EncryptAndDecryptSinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Get length of encrypted data in first call ulong encryptedDataLen = 0; rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call ulong decryptedDataLen = 0; rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_DecryptUpdate and C_DecryptFinish test. /// </summary> [Test()] public void _02_EncryptAndDecryptMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key ulong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption functions C_EncryptUpdate and C_EncryptFinal can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; ulong encryptedPartLen = Convert.ToUInt64(encryptedPart.Length); // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Encrypt each individual source data part encryptedPartLen = Convert.ToUInt64(encryptedPart.Length); rv = pkcs11.C_EncryptUpdate(session, part, Convert.ToUInt64(bytesRead), encryptedPart, ref encryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append encrypted data part to the output stream outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen)); } // Get the length of last encrypted data part in first call byte[] lastEncryptedPart = null; ulong lastEncryptedPartLen = 0; rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last encrypted data part lastEncryptedPart = new byte[lastEncryptedPartLen]; // Get the last encrypted data part in second call rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last encrypted data part to the output stream outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen)); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption functions C_DecryptUpdate and C_DecryptFinal can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; // Prepare buffer for decrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; ulong partLen = Convert.ToUInt64(part.Length); // Read input stream with encrypted data int bytesRead = 0; while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0) { // Decrypt each individual encrypted data part partLen = Convert.ToUInt64(part.Length); rv = pkcs11.C_DecryptUpdate(session, encryptedPart, Convert.ToUInt64(bytesRead), part, ref partLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append decrypted data part to the output stream outputStream.Write(part, 0, Convert.ToInt32(partLen)); } // Get the length of last decrypted data part in first call byte[] lastPart = null; ulong lastPartLen = 0; rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last decrypted data part lastPart = new byte[lastPartLen]; // Get the last decrypted data part in second call rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last decrypted data part to the output stream outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen)); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test with CKM_RSA_PKCS_OAEP mechanism. /// </summary> [Test()] public void _03_EncryptAndDecryptSinglePartOaepTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify mechanism parameters CK_RSA_PKCS_OAEP_PARAMS mechanismParams = new CK_RSA_PKCS_OAEP_PARAMS(); mechanismParams.HashAlg = (ulong)CKM.CKM_SHA_1; mechanismParams.Mgf = (ulong)CKG.CKG_MGF1_SHA1; mechanismParams.Source = (ulong)CKZ.CKZ_DATA_SPECIFIED; mechanismParams.SourceData = IntPtr.Zero; mechanismParams.SourceDataLen = 0; // Specify encryption mechanism with parameters // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); // Initialize encryption operation rv = pkcs11.C_EncryptInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of encrypted data in first call ulong encryptedDataLen = 0; rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt64(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11.C_DecryptInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call ulong decryptedDataLen = 0; rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt64(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Array may need to be shrinked if (decryptedData.Length != Convert.ToInt32(decryptedDataLen)) Array.Resize(ref decryptedData, Convert.ToInt32(decryptedDataLen)); // Do something interesting with decrypted data Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal sealed class WinHttpRequestState : IDisposable { #if DEBUG private static int s_dbg_allocated = 0; private static int s_dbg_pin = 0; private static int s_dbg_clearSendRequestState = 0; private static int s_dbg_callDispose = 0; private static int s_dbg_operationHandleFree = 0; private IntPtr s_dbg_requestHandle; #endif // A GCHandle for this operation object. // This is owned by the callback and will be deallocated when the sessionHandle has been closed. private GCHandle _operationHandle; private WinHttpTransportContext _transportContext; private volatile bool _disposed = false; // To detect redundant calls. public WinHttpRequestState() { #if DEBUG Interlocked.Increment(ref s_dbg_allocated); #endif } public void Pin() { if (!_operationHandle.IsAllocated) { #if DEBUG Interlocked.Increment(ref s_dbg_pin); #endif _operationHandle = GCHandle.Alloc(this); } } public static WinHttpRequestState FromIntPtr(IntPtr gcHandle) { GCHandle stateHandle = GCHandle.FromIntPtr(gcHandle); return (WinHttpRequestState)stateHandle.Target; } public IntPtr ToIntPtr() { return GCHandle.ToIntPtr(_operationHandle); } // TODO (Issue 2506): The current locking mechanism doesn't allow any two WinHttp functions executing at // the same time for the same handle. Enhance locking to prevent only WinHttpCloseHandle being called // during other API execution. E.g. using a Reader/Writer model or, even better, Interlocked functions. // The lock object must be used during the execution of any WinHttp function to ensure no race conditions with // calling WinHttpCloseHandle. public object Lock => this; public void ClearSendRequestState() { #if DEBUG Interlocked.Increment(ref s_dbg_clearSendRequestState); #endif // Since WinHttpRequestState has a self-referenced strong GCHandle, we // need to clear out object references to break cycles and prevent leaks. Tcs = null; TcsInternalWriteDataToRequestStream = null; CancellationToken = default(CancellationToken); RequestMessage = null; Handler = null; ServerCertificateValidationCallback = null; TransportContext = null; Proxy = null; ServerCredentials = null; DefaultProxyCredentials = null; if (RequestHandle != null) { RequestHandle.Dispose(); RequestHandle = null; } } public TaskCompletionSource<HttpResponseMessage> Tcs { get; set; } public CancellationToken CancellationToken { get; set; } public HttpRequestMessage RequestMessage { get; set; } public WinHttpHandler Handler { get; set; } private SafeWinHttpHandle _requestHandle; public SafeWinHttpHandle RequestHandle { get { return _requestHandle; } set { #if DEBUG if (value != null) { s_dbg_requestHandle = value.DangerousGetHandle(); } #endif _requestHandle = value; } } public Exception SavedException { get; set; } public bool CheckCertificateRevocationList { get; set; } public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get; set; } public WinHttpTransportContext TransportContext { get { return _transportContext ?? (_transportContext = new WinHttpTransportContext()); } set { _transportContext = value; } } public WindowsProxyUsePolicy WindowsProxyUsePolicy { get; set; } public IWebProxy Proxy { get; set; } public ICredentials ServerCredentials { get; set; } public ICredentials DefaultProxyCredentials { get; set; } public bool PreAuthenticate { get; set; } public HttpStatusCode LastStatusCode { get; set; } public bool RetryRequest { get; set; } public RendezvousAwaitable<int> LifecycleAwaitable { get; set; } = new RendezvousAwaitable<int>(); public TaskCompletionSource<bool> TcsInternalWriteDataToRequestStream { get; set; } public bool AsyncReadInProgress { get; set; } // WinHttpResponseStream state. public long? ExpectedBytesToRead { get; set; } public long CurrentBytesRead { get; set; } // TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache. private GCHandle _cachedReceivePinnedBuffer; public void PinReceiveBuffer(byte[] buffer) { if (!_cachedReceivePinnedBuffer.IsAllocated || _cachedReceivePinnedBuffer.Target != buffer) { if (_cachedReceivePinnedBuffer.IsAllocated) { _cachedReceivePinnedBuffer.Free(); } _cachedReceivePinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); } } #region IDisposable Members private void Dispose(bool disposing) { #if DEBUG Interlocked.Increment(ref s_dbg_callDispose); #endif if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"GCHandle=0x{ToIntPtr().ToString("X")}, disposed={_disposed}, disposing={disposing}"); // Since there is no finalizer and this class is sealed, the disposing parameter should be TRUE. Debug.Assert(disposing, "WinHttpRequestState.Dispose() should have disposing=TRUE"); if (_disposed) { return; } _disposed = true; if (_operationHandle.IsAllocated) { // This method only gets called when the WinHTTP request handle is fully closed and thus all // async operations are done. So, it is safe at this point to unpin the buffers and release // the strong GCHandle for this object. if (_cachedReceivePinnedBuffer.IsAllocated) { _cachedReceivePinnedBuffer.Free(); _cachedReceivePinnedBuffer = default(GCHandle); } #if DEBUG Interlocked.Increment(ref s_dbg_operationHandleFree); #endif _operationHandle.Free(); _operationHandle = default(GCHandle); } } public void Dispose() { // No need to suppress finalization since the finalizer is not overridden and the class is sealed. Dispose(true); } #endregion } }
#region Apache License // // 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. // #endregion using System; using System.IO; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Sends logging events to a <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// An Appender that writes to a <see cref="TextWriter"/>. /// </para> /// <para> /// This appender may be used stand alone if initialized with an appropriate /// writer, however it is typically used as a base class for an appender that /// can open a <see cref="TextWriter"/> to write to. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Douglas de la Torre</author> public class TextWriterAppender : AppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="TextWriterAppender" /> class. /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public TextWriterAppender() { } /// <summary> /// Initializes a new instance of the <see cref="TextWriterAppender" /> class and /// sets the output destination to a new <see cref="StreamWriter"/> initialized /// with the specified <see cref="Stream"/>. /// </summary> /// <param name="layout">The layout to use with this appender.</param> /// <param name="os">The <see cref="Stream"/> to output to.</param> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & Writer properties")] public TextWriterAppender(ILayout layout, Stream os) : this(layout, new StreamWriter(os)) { } /// <summary> /// Initializes a new instance of the <see cref="TextWriterAppender" /> class and sets /// the output destination to the specified <see cref="StreamWriter" />. /// </summary> /// <param name="layout">The layout to use with this appender</param> /// <param name="writer">The <see cref="TextWriter" /> to output to</param> /// <remarks> /// The <see cref="TextWriter" /> must have been previously opened. /// </remarks> /// <remarks> /// <para> /// Obsolete constructor. /// </para> /// </remarks> [Obsolete("Instead use the default constructor and set the Layout & Writer properties")] public TextWriterAppender(ILayout layout, TextWriter writer) { Layout = layout; Writer = writer; } #endregion #region Public Instance Properties /// <summary> /// Gets or set whether the appender will flush at the end /// of each append operation. /// </summary> /// <value> /// <para> /// The default behavior is to flush at the end of each /// append operation. /// </para> /// <para> /// If this option is set to <c>false</c>, then the underlying /// stream can defer persisting the logging event to a later /// time. /// </para> /// </value> /// <remarks> /// Avoiding the flush operation at the end of each append results in /// a performance gain of 10 to 20 percent. However, there is safety /// trade-off involved in skipping flushing. Indeed, when flushing is /// skipped, then it is likely that the last few log events will not /// be recorded on disk when the application exits. This is a high /// price to pay even for a 20% performance gain. /// </remarks> public bool ImmediateFlush { get { return m_immediateFlush; } set { m_immediateFlush = value; } } /// <summary> /// Sets the <see cref="TextWriter"/> where the log output will go. /// </summary> /// <remarks> /// <para> /// The specified <see cref="TextWriter"/> must be open and writable. /// </para> /// <para> /// The <see cref="TextWriter"/> will be closed when the appender /// instance is closed. /// </para> /// <para> /// <b>Note:</b> Logging to an unopened <see cref="TextWriter"/> will fail. /// </para> /// </remarks> virtual public TextWriter Writer { get { return m_qtw; } set { lock(this) { Reset(); if (value != null) { m_qtw = new QuietTextWriter(value, ErrorHandler); WriteHeader(); } } } } #endregion Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// This method determines if there is a sense in attempting to append. /// </summary> /// <remarks> /// <para> /// This method checks if an output target has been set and if a /// layout has been set. /// </para> /// </remarks> /// <returns><c>false</c> if any of the preconditions fail.</returns> override protected bool PreAppendCheck() { if (!base.PreAppendCheck()) { return false; } if (m_qtw == null) { // Allow subclass to lazily create the writer PrepareWriter(); if (m_qtw == null) { ErrorHandler.Error("No output stream or file set for the appender named ["+ Name +"]."); return false; } } if (m_qtw.Closed) { ErrorHandler.Error("Output stream for appender named ["+ Name +"] has been closed."); return false; } return true; } /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes a log statement to the output stream if the output stream exists /// and is writable. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { RenderLoggingEvent(m_qtw, loggingEvent); if (m_immediateFlush) { m_qtw.Flush(); } } /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent[])"/> /// method. /// </summary> /// <param name="loggingEvents">The array of events to log.</param> /// <remarks> /// <para> /// This method writes all the bulk logged events to the output writer /// before flushing the stream. /// </para> /// </remarks> override protected void Append(LoggingEvent[] loggingEvents) { foreach(LoggingEvent loggingEvent in loggingEvents) { RenderLoggingEvent(m_qtw, loggingEvent); } if (m_immediateFlush) { m_qtw.Flush(); } } /// <summary> /// Close this appender instance. The underlying stream or writer is also closed. /// </summary> /// <remarks> /// Closed appenders cannot be reused. /// </remarks> override protected void OnClose() { lock(this) { Reset(); } } /// <summary> /// Gets or set the <see cref="IErrorHandler"/> and the underlying /// <see cref="QuietTextWriter"/>, if any, for this appender. /// </summary> /// <value> /// The <see cref="IErrorHandler"/> for this appender. /// </value> override public IErrorHandler ErrorHandler { get { return base.ErrorHandler; } set { lock(this) { if (value == null) { LogLog.Warn(declaringType, "TextWriterAppender: You have tried to set a null error-handler."); } else { base.ErrorHandler = value; if (m_qtw != null) { m_qtw.ErrorHandler = value; } } } } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion Override implementation of AppenderSkeleton #region Protected Instance Methods /// <summary> /// Writes the footer and closes the underlying <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// Writes the footer and closes the underlying <see cref="TextWriter"/>. /// </para> /// </remarks> virtual protected void WriteFooterAndCloseWriter() { WriteFooter(); CloseWriter(); } /// <summary> /// Closes the underlying <see cref="TextWriter"/>. /// </summary> /// <remarks> /// <para> /// Closes the underlying <see cref="TextWriter"/>. /// </para> /// </remarks> virtual protected void CloseWriter() { if (m_qtw != null) { try { m_qtw.Close(); } catch(Exception e) { ErrorHandler.Error("Could not close writer ["+m_qtw+"]", e); // do need to invoke an error handler // at this late stage } } } /// <summary> /// Clears internal references to the underlying <see cref="TextWriter" /> /// and other variables. /// </summary> /// <remarks> /// <para> /// Subclasses can override this method for an alternate closing behavior. /// </para> /// </remarks> virtual protected void Reset() { WriteFooterAndCloseWriter(); m_qtw = null; } /// <summary> /// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property. /// </summary> /// <remarks> /// <para> /// Writes a footer as produced by the embedded layout's <see cref="ILayout.Footer"/> property. /// </para> /// </remarks> virtual protected void WriteFooter() { if (Layout != null && m_qtw != null && !m_qtw.Closed) { string f = Layout.Footer; if (f != null) { m_qtw.Write(f); } } } /// <summary> /// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property. /// </summary> /// <remarks> /// <para> /// Writes a header produced by the embedded layout's <see cref="ILayout.Header"/> property. /// </para> /// </remarks> virtual protected void WriteHeader() { if (Layout != null && m_qtw != null && !m_qtw.Closed) { string h = Layout.Header; if (h != null) { m_qtw.Write(h); } } } /// <summary> /// Called to allow a subclass to lazily initialize the writer /// </summary> /// <remarks> /// <para> /// This method is called when an event is logged and the <see cref="Writer"/> or /// <see cref="QuietWriter"/> have not been set. This allows a subclass to /// attempt to initialize the writer multiple times. /// </para> /// </remarks> virtual protected void PrepareWriter() { } /// <summary> /// Gets or sets the <see cref="log4net.Util.QuietTextWriter"/> where logging events /// will be written to. /// </summary> /// <value> /// The <see cref="log4net.Util.QuietTextWriter"/> where logging events are written. /// </value> /// <remarks> /// <para> /// This is the <see cref="log4net.Util.QuietTextWriter"/> where logging events /// will be written to. /// </para> /// </remarks> protected QuietTextWriter QuietWriter { get { return m_qtw; } set { m_qtw = value; } } #endregion Protected Instance Methods #region Private Instance Fields /// <summary> /// This is the <see cref="log4net.Util.QuietTextWriter"/> where logging events /// will be written to. /// </summary> private QuietTextWriter m_qtw; /// <summary> /// Immediate flush means that the underlying <see cref="TextWriter" /> /// or output stream will be flushed at the end of each append operation. /// </summary> /// <remarks> /// <para> /// Immediate flush is slower but ensures that each append request is /// actually written. If <see cref="ImmediateFlush"/> is set to /// <c>false</c>, then there is a good chance that the last few /// logging events are not actually persisted if and when the application /// crashes. /// </para> /// <para> /// The default value is <c>true</c>. /// </para> /// </remarks> private bool m_immediateFlush = true; #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the TextWriterAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(TextWriterAppender); #endregion Private Static Fields } }
using System.ComponentModel; using System.EDTF.Internal.Converters; using System.EDTF.Internal.Parsers; using System.EDTF.Internal.Serializers; using System.Runtime.Serialization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.EDTF { [Serializable] [TypeConverter(typeof(ExtendedDateTimeConverter))] public class ExtendedDateTime : ISingleExtendedDateTimeType, IComparable, IComparable<ExtendedDateTime>, IEquatable<ExtendedDateTime>, ISerializable, IXmlSerializable, ICloneable { public static readonly ExtendedDateTime Maximum = new ExtendedDateTime(9999, 12, 31, 23, 59, 59, 14); public static readonly ExtendedDateTime Minimum = new ExtendedDateTime(-9999, 1, 1, 0, 0, 0, -12); public static readonly ExtendedDateTime Open = new ExtendedDateTime { _isOpen = true }; public static readonly ExtendedDateTime Unknown = new ExtendedDateTime { _isUnknown = true }; private static ExtendedDateTimeComparer _comparer; private int _day; private DayFlags _dayFlags; private int _hour; private bool _isLongYear; private bool _isOpen; private bool _isUnknown; private int _minute; private int _month; private MonthFlags _monthFlags; private ExtendedDateTimePrecision _precision; private Season _season; private SeasonFlags _seasonFlags; private string _seasonQualifier; private int _second; private TimeSpan _utcOffset; private int _year; private int? _yearExponent; private YearFlags _yearFlags; private int? _yearPrecision; public ExtendedDateTime(int year, int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int utcHourOffset = 0, int utcMinuteOffset = 0) { if (year < -9999 || year > 9999) { throw new ArgumentOutOfRangeException(nameof(year), year, $"The argument \"{nameof(year)}\" must be a value from -9999 to 9999"); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), month, $"The argument \"{nameof(month)}\" must be a value from 1 to 12"); } if (day < 1 || day > ExtendedDateTimeCalculator.DaysInMonth(year, month)) { throw new ArgumentOutOfRangeException(nameof(day), day, $"The argument \"{nameof(day)}\" must be a value from 1 to {ExtendedDateTimeCalculator.DaysInMonth(year, month)}"); } if (hour < 0 || hour > 23) { throw new ArgumentOutOfRangeException(nameof(hour), hour, $"The argument \"{nameof(hour)}\" must be a value from 0 to 23"); } if (minute < 0 || minute > 59) { throw new ArgumentOutOfRangeException(nameof(minute), minute, $"The argument \"{nameof(minute)}\" must be a value from 0 to 59"); } if (second < 0 || second > 59) { throw new ArgumentOutOfRangeException(nameof(second), second, $"The argument \"{nameof(second)}\" must be a value from 0 to 59"); } _year = year; _month = month; _day = day; _hour = hour; _minute = minute; _second = second; _utcOffset = new TimeSpan(utcHourOffset, utcMinuteOffset, 0); } internal ExtendedDateTime() { _month = 1; _day = 1; } protected ExtendedDateTime(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } Parse((string)info.GetValue("edtStr", typeof(string)), this); } public static ExtendedDateTimeComparer Comparer { get { if (_comparer == null) { _comparer = new ExtendedDateTimeComparer(); } return _comparer; } } public static ExtendedDateTime Now { get { return DateTimeOffset.Now.ToExtendedDateTime(); } } public int Day { get { if (_isOpen) { return Now.Day; } return _day; } internal set { _day = value; } } public DayFlags DayFlags { get { return _dayFlags; } set { _dayFlags = value; } } public DayOfWeek DayOfWeek { get { if (Precision > ExtendedDateTimePrecision.Day) { throw new InvalidOperationException("Day of the Week can only be calculated when the precision is of the day or greater."); } return ExtendedDateTimeCalculator.DayOfWeek(this); } } public int Hour { get { if (_isOpen) { return Now.Hour; } return _hour; } internal set { _hour = value; } } public bool IsLongYear { get { return _isLongYear; } set { _isLongYear = value; } } public bool IsOpen { get { return _isOpen; } internal set { _isOpen = value; } } public bool IsUnknown { get { return _isUnknown; } internal set { _isUnknown = value; } } public int Minute { get { if (_isOpen) { return Now.Minute; } return _minute; } internal set { _minute = value; } } public int Month { get { if (_isOpen) { return Now.Month; } return _month; } internal set { _month = value; } } public MonthFlags MonthFlags { get { return _monthFlags; } set { _monthFlags = value; } } public ExtendedDateTimePrecision Precision { get { return _precision; } set { _precision = value; } } public Season Season { get { return _season; } internal set { _season = value; } } public SeasonFlags SeasonFlags { get { return _seasonFlags; } set { _seasonFlags = value; } } public string SeasonQualifier { get { return _seasonQualifier; } internal set { _seasonQualifier = value; } } public int Second { get { if (_isOpen) { return Now.Second; } return _second; } internal set { _second = value; } } public TimeSpan UtcOffset { get { return _utcOffset; } internal set { _utcOffset = value; } } public int Year { get { if (_isOpen) { return Now.Year; } return _year; } internal set { _year = value; } } public int? YearExponent { get { return _yearExponent; } internal set { _yearExponent = value; } } public YearFlags YearFlags { get { return _yearFlags; } set { _yearFlags = value; } } public int? YearPrecision { get { return _yearPrecision; } internal set { _yearPrecision = value; } } public static ExtendedDateTime FromLongYear(int year) { return new ExtendedDateTime { _year = year, _isLongYear = true }; } public static ExtendedDateTime FromScientificNotation(int significand, int? exponent = null, int? precision = null) { if (significand == 0) { throw new ArgumentException("significand", "The significand must be nonzero."); } if (exponent < 1) { throw new ArgumentOutOfRangeException("exponent", "An exponent must be positive."); } if (precision < 1) { throw new ArgumentOutOfRangeException("precision", "A precision must be positive."); } return new ExtendedDateTime { _year = significand, _yearExponent = exponent, _yearPrecision = precision }; } public static ExtendedDateTime FromSeason(int year, Season season, string seasonQualifier = null) { if (season == Season.Undefined) { throw new ArgumentException("A season cannot be input as undefined."); } return new ExtendedDateTime { _year = year, _season = season, _seasonQualifier = seasonQualifier }; } public static ExtendedDateTime operator -(ExtendedDateTime e, TimeSpan t) { return ExtendedDateTimeCalculator.Subtract(e, t); } public static TimeSpan operator -(ExtendedDateTime e2, ExtendedDateTime e1) { return ExtendedDateTimeCalculator.Subtract(e2, e1); } public static bool operator !=(ExtendedDateTime e1, ExtendedDateTime e2) { return Comparer.Compare(e1, e2) != 0; } public static ExtendedDateTime operator +(ExtendedDateTime e, TimeSpan t) { return ExtendedDateTimeCalculator.Add(e, t); } public static bool operator <(ExtendedDateTime e1, ExtendedDateTime e2) { return Comparer.Compare(e1, e2) < 0; } public static bool operator <=(ExtendedDateTime e1, ExtendedDateTime e2) { return Comparer.Compare(e1, e2) <= 0; } public static bool operator ==(ExtendedDateTime e1, ExtendedDateTime e2) { return Comparer.Compare(e1, e2) == 0; } public static bool operator >(ExtendedDateTime e1, ExtendedDateTime e2) { return Comparer.Compare(e1, e2) > 0; } public static bool operator >=(ExtendedDateTime e1, ExtendedDateTime e2) { return Comparer.Compare(e1, e2) >= 0; } public static ExtendedDateTime Parse(string extendedDateTimeString) { if (string.IsNullOrWhiteSpace(extendedDateTimeString)) { return new ExtendedDateTime(); } return ExtendedDateTimeParser.Parse(extendedDateTimeString); } public ExtendedDateTime AddMonths(int count, DayExceedsDaysInMonthStrategy dayExceedsDaysInMonthStrategy = DayExceedsDaysInMonthStrategy.RoundDown) { return ExtendedDateTimeCalculator.AddMonths(this, count, dayExceedsDaysInMonthStrategy); } public ExtendedDateTime AddYears(int count) { return ExtendedDateTimeCalculator.AddYears(this, count); } public object Clone() { return MemberwiseClone(); } public int CompareTo(ExtendedDateTime other) { return Comparer.Compare(this, other); } public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is ExtendedDateTime)) { throw new ArgumentException("An extended datetime can only be compared with another extended datetime."); } return Comparer.Compare(this, (ExtendedDateTime)obj); } public ExtendedDateTime Earliest() { return this; } public override bool Equals(object obj) { if (obj == null || obj.GetType() != typeof(ExtendedDateTime)) { return false; } return Comparer.Compare(this, (ExtendedDateTime)obj) == 0; } public bool Equals(ExtendedDateTime other) { return Comparer.Compare(this, other) == 0; } public override int GetHashCode() { return Year ^ (Month << 28) ^ (Day << 22) ^ (Hour << 14) ^ (Minute << 8) ^ (Second << 6) ^ UtcOffset.GetHashCode(); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("edtStr", ToString()); } public XmlSchema GetSchema() { return null; } public ExtendedDateTime Latest() { return this; } public void ReadXml(XmlReader reader) { Parse(reader.ReadString(), this); } public ExtendedDateTime SubtractMonths(int count) { return ExtendedDateTimeCalculator.SubtractMonths(this, count); } public ExtendedDateTime SubtractYears(int count) { return ExtendedDateTimeCalculator.SubtractYears(this, count); } public ExtendedDateTime ToRoundedPrecision(ExtendedDateTimePrecision p, bool roundUp = false) { return ExtendedDateTimeCalculator.ToRoundedPrecision(this, p, roundUp); } public override string ToString() { return ExtendedDateTimeSerializer.Serialize(this); } public void WriteXml(XmlWriter writer) { writer.WriteString(ToString()); } internal static ExtendedDateTime Parse(string extendedDateTimeString, ExtendedDateTime container) { if (string.IsNullOrWhiteSpace(extendedDateTimeString)) { return new ExtendedDateTime(); } return ExtendedDateTimeParser.Parse(extendedDateTimeString, container); } } }
// // SaslMechanism.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Net; using System.Text; namespace MailKit.Security { /// <summary> /// A SASL authentication mechanism. /// </summary> /// <remarks> /// Authenticating via a SASL mechanism may be a multi-step process. /// To determine if the mechanism has completed the necessary steps /// to authentication, check the <see cref="IsAuthenticated"/> after /// each call to <see cref="Challenge(string)"/>. /// </remarks> public abstract class SaslMechanism { /// <summary> /// The supported authentication mechanisms in order of strongest to weakest. /// </summary> /// <remarks> /// Used by the various clients when authenticating via SASL to determine /// which order the SASL mechanisms supported by the server should be tried. /// </remarks> public static readonly string[] AuthMechanismRank = { "XOAUTH2", "SCRAM-SHA-1", "NTLM", "CRAM-MD5", "DIGEST-MD5", "PLAIN", "LOGIN" }; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanism"/> class. /// </summary> /// <remarks> /// Creates a new SASL context. /// </remarks> /// <param name="uri">The URI of the service.</param> /// <param name="credentials">The user's credentials.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="uri"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="credentials"/> is <c>null</c>.</para> /// </exception> protected SaslMechanism (Uri uri, ICredentials credentials) { if (uri == null) throw new ArgumentNullException ("uri"); if (credentials == null) throw new ArgumentNullException ("credentials"); Credentials = credentials; Uri = uri; } /// <summary> /// Gets the name of the mechanism. /// </summary> /// <remarks> /// Gets the name of the mechanism. /// </remarks> /// <value>The name of the mechanism.</value> public abstract string MechanismName { get; } /// <summary> /// Gets the user's credentials. /// </summary> /// <remarks> /// Gets the user's credentials. /// </remarks> /// <value>The user's credentials.</value> public ICredentials Credentials { get; private set; } /// <summary> /// Gets whether or not the mechanism supports an initial response (SASL-IR). /// </summary> /// <remarks> /// SASL mechanisms that support sending an initial client response to the server /// should return <value>true</value>. /// </remarks> /// <value><c>true</c> if the mechanism supports an initial response; otherwise, <c>false</c>.</value> public virtual bool SupportsInitialResponse { get { return false; } } /// <summary> /// Gets or sets whether the SASL mechanism has finished authenticating. /// </summary> /// <remarks> /// Gets or sets whether the SASL mechanism has finished authenticating. /// </remarks> /// <value><c>true</c> if the SASL mechanism has finished authenticating; otherwise, <c>false</c>.</value> public bool IsAuthenticated { get; protected set; } /// <summary> /// Gets or sets the URI of the service. /// </summary> /// <remarks> /// Gets or sets the URI of the service. /// </remarks> /// <value>The URI of the service.</value> public Uri Uri { get; protected set; } /// <summary> /// Parses the server's challenge token and returns the next challenge response. /// </summary> /// <remarks> /// Parses the server's challenge token and returns the next challenge response. /// </remarks> /// <returns>The next challenge response.</returns> /// <param name="token">The server's challenge token.</param> /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param> /// <param name="length">The length of the server's challenge.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> protected abstract byte[] Challenge (byte[] token, int startIndex, int length); /// <summary> /// Decodes the base64-encoded server challenge and returns the next challenge response encoded in base64. /// </summary> /// <remarks> /// Decodes the base64-encoded server challenge and returns the next challenge response encoded in base64. /// </remarks> /// <returns>The next base64-encoded challenge response.</returns> /// <param name="token">The server's base64-encoded challenge token.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> public string Challenge (string token) { byte[] decoded; int length; if (token != null) { decoded = Convert.FromBase64String (token); length = decoded.Length; } else { decoded = null; length = 0; } var challenge = Challenge (decoded, 0, length); if (challenge == null) return null; return Convert.ToBase64String (challenge); } /// <summary> /// Resets the state of the SASL mechanism. /// </summary> /// <remarks> /// Resets the state of the SASL mechanism. /// </remarks> public virtual void Reset () { IsAuthenticated = false; } /// <summary> /// Determines if the specified SASL mechanism is supported by MailKit. /// </summary> /// <remarks> /// Use this method to make sure that a SASL mechanism is supported before calling /// <see cref="Create"/>. /// </remarks> /// <returns><c>true</c> if the specified SASL mechanism is supported; otherwise, <c>false</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="mechanism"/> is <c>null</c>. /// </exception> public static bool IsSupported (string mechanism) { if (mechanism == null) throw new ArgumentNullException ("mechanism"); switch (mechanism) { case "SCRAM-SHA-1": return true; case "DIGEST-MD5": return true; case "CRAM-MD5": return true; case "XOAUTH2": return true; case "PLAIN": return true; case "LOGIN": return true; case "NTLM": return true; default: return false; } } /// <summary> /// Create an instance of the specified SASL mechanism using the uri and credentials. /// </summary> /// <remarks> /// If unsure that a particular SASL mechanism is supported, you should first call /// <see cref="IsSupported"/>. /// </remarks> /// <returns>An instance of the requested SASL mechanism if supported; otherwise <c>null</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <param name="uri">The URI of the service to authenticate against.</param> /// <param name="credentials">The user's credentials.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mechanism"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="uri"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="credentials"/> is <c>null</c>.</para> /// </exception> public static SaslMechanism Create (string mechanism, Uri uri, ICredentials credentials) { if (mechanism == null) throw new ArgumentNullException ("mechanism"); if (uri == null) throw new ArgumentNullException ("uri"); if (credentials == null) throw new ArgumentNullException ("credentials"); switch (mechanism) { //case "KERBEROS_V4": return null; case "SCRAM-SHA-1": return new SaslMechanismScramSha1 (uri, credentials); case "DIGEST-MD5": return new SaslMechanismDigestMd5 (uri, credentials); case "CRAM-MD5": return new SaslMechanismCramMd5 (uri, credentials); //case "GSSAPI": return null; case "XOAUTH2": return new SaslMechanismOAuth2 (uri, credentials); case "PLAIN": return new SaslMechanismPlain (uri, credentials); case "LOGIN": return new SaslMechanismLogin (uri, credentials); case "NTLM": return new SaslMechanismNtlm (uri, credentials); default: return null; } } /// <summary> /// Determines if the character is a non-ASCII space. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-C.1.2 /// </remarks> /// <returns><c>true</c> if the character is a non-ASCII space; otherwise, <c>false</c>.</returns> /// <param name="c">The character.</param> static bool IsNonAsciiSpace (char c) { switch (c) { case '\u00A0': // NO-BREAK SPACE case '\u1680': // OGHAM SPACE MARK case '\u2000': // EN QUAD case '\u2001': // EM QUAD case '\u2002': // EN SPACE case '\u2003': // EM SPACE case '\u2004': // THREE-PER-EM SPACE case '\u2005': // FOUR-PER-EM SPACE case '\u2006': // SIX-PER-EM SPACE case '\u2007': // FIGURE SPACE case '\u2008': // PUNCTUATION SPACE case '\u2009': // THIN SPACE case '\u200A': // HAIR SPACE case '\u200B': // ZERO WIDTH SPACE case '\u202F': // NARROW NO-BREAK SPACE case '\u205F': // MEDIUM MATHEMATICAL SPACE case '\u3000': // IDEOGRAPHIC SPACE return true; default: return false; } } /// <summary> /// Determines if the character is commonly mapped to nothing. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-B.1 /// </remarks> /// <returns><c>true</c> if the character is commonly mapped to nothing; otherwise, <c>false</c>.</returns> /// <param name="c">The character.</param> static bool IsCommonlyMappedToNothing (char c) { switch (c) { case '\u00AD': case '\u034F': case '\u1806': case '\u180B': case '\u180C': case '\u180D': case '\u200B': case '\u200C': case '\u200D': case '\u2060': case '\uFE00': case '\uFE01': case '\uFE02': case '\uFE03': case '\uFE04': case '\uFE05': case '\uFE06': case '\uFE07': case '\uFE08': case '\uFE09': case '\uFE0A': case '\uFE0B': case '\uFE0C': case '\uFE0D': case '\uFE0E': case '\uFE0F': case '\uFEFF': return true; default: return false; } } /// <summary> /// Determines if the character is prohibited. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-C.3 /// </remarks> /// <returns><c>true</c> if the character is prohibited; otherwise, <c>false</c>.</returns> /// <param name="s">The string.</param> /// <param name="index">The character index.</param> static bool IsProhibited (string s, int index) { int u = char.ConvertToUtf32 (s, index); // Private Use characters: http://tools.ietf.org/html/rfc3454#appendix-C.3 if ((u >= 0xE000 && u <= 0xF8FF) || (u >= 0xF0000 && u <= 0xFFFFD) || (u >= 0x100000 && u <= 0x10FFFD)) return true; // Non-character code points: http://tools.ietf.org/html/rfc3454#appendix-C.4 if ((u >= 0xFDD0 && u <= 0xFDEF) || (u >= 0xFFFE && u <= 0xFFFF) || (u >= 0x1FFFE & u <= 0x1FFFF) || (u >= 0x2FFFE & u <= 0x2FFFF) || (u >= 0x3FFFE & u <= 0x3FFFF) || (u >= 0x4FFFE & u <= 0x4FFFF) || (u >= 0x5FFFE & u <= 0x5FFFF) || (u >= 0x6FFFE & u <= 0x6FFFF) || (u >= 0x7FFFE & u <= 0x7FFFF) || (u >= 0x8FFFE & u <= 0x8FFFF) || (u >= 0x9FFFE & u <= 0x9FFFF) || (u >= 0xAFFFE & u <= 0xAFFFF) || (u >= 0xBFFFE & u <= 0xBFFFF) || (u >= 0xCFFFE & u <= 0xCFFFF) || (u >= 0xDFFFE & u <= 0xDFFFF) || (u >= 0xEFFFE & u <= 0xEFFFF) || (u >= 0xFFFFE & u <= 0xFFFFF) || (u >= 0x10FFFE & u <= 0x10FFFF)) return true; // Surrogate code points: http://tools.ietf.org/html/rfc3454#appendix-C.5 if (u >= 0xD800 && u <= 0xDFFF) return true; // Inappropriate for plain text characters: http://tools.ietf.org/html/rfc3454#appendix-C.6 switch (u) { case 0xFFF9: // INTERLINEAR ANNOTATION ANCHOR case 0xFFFA: // INTERLINEAR ANNOTATION SEPARATOR case 0xFFFB: // INTERLINEAR ANNOTATION TERMINATOR case 0xFFFC: // OBJECT REPLACEMENT CHARACTER case 0xFFFD: // REPLACEMENT CHARACTER return true; } // Inappropriate for canonical representation: http://tools.ietf.org/html/rfc3454#appendix-C.7 if (u >= 0x2FF0 && u <= 0x2FFB) return true; // Change display properties or are deprecated: http://tools.ietf.org/html/rfc3454#appendix-C.8 switch (u) { case 0x0340: // COMBINING GRAVE TONE MARK case 0x0341: // COMBINING ACUTE TONE MARK case 0x200E: // LEFT-TO-RIGHT MARK case 0x200F: // RIGHT-TO-LEFT MARK case 0x202A: // LEFT-TO-RIGHT EMBEDDING case 0x202B: // RIGHT-TO-LEFT EMBEDDING case 0x202C: // POP DIRECTIONAL FORMATTING case 0x202D: // LEFT-TO-RIGHT OVERRIDE case 0x202E: // RIGHT-TO-LEFT OVERRIDE case 0x206A: // INHIBIT SYMMETRIC SWAPPING case 0x206B: // ACTIVATE SYMMETRIC SWAPPING case 0x206C: // INHIBIT ARABIC FORM SHAPING case 0x206D: // ACTIVATE ARABIC FORM SHAPING case 0x206E: // NATIONAL DIGIT SHAPES case 0x206F: // NOMINAL DIGIT SHAPES return true; } // Tagging characters: http://tools.ietf.org/html/rfc3454#appendix-C.9 if (u == 0xE0001 || (u >= 0xE0020 & u <= 0xE007F)) return true; return false; } /// <summary> /// Prepares the user name or password string. /// </summary> /// <remarks> /// Prepares a user name or password string according to the rules of rfc4013. /// </remarks> /// <returns>The prepared string.</returns> /// <param name="s">The string to prepare.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="s"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="s"/> contains prohibited characters. /// </exception> public static string SaslPrep (string s) { if (s == null) throw new ArgumentNullException ("s"); if (s.Length == 0) return s; var builder = new StringBuilder (s.Length); for (int i = 0; i < s.Length; i++) { if (IsNonAsciiSpace (s[i])) { // non-ASII space characters [StringPrep, C.1.2] that can be // mapped to SPACE (U+0020). builder.Append (' '); } else if (IsCommonlyMappedToNothing (s[i])) { // the "commonly mapped to nothing" characters [StringPrep, B.1] // that can be mapped to nothing. } else if (char.IsControl (s[i])) { throw new ArgumentException ("Control characters are prohibited.", "s"); } else if (IsProhibited (s, i)) { throw new ArgumentException ("One or more characters in the string are prohibited.", "s"); } else { builder.Append (s[i]); } } #if !NETFX_CORE return builder.ToString ().Normalize (NormalizationForm.FormKC); #else return builder.ToString (); #endif } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.DataMatrix.Internal { /// <summary> /// The Version object encapsulates attributes about a particular /// size Data Matrix Code. /// /// <author>[email protected] (Brian Brown)</author> /// </summary> public sealed class Version { private static readonly Version[] VERSIONS = buildVersions(); private readonly int versionNumber; private readonly int symbolSizeRows; private readonly int symbolSizeColumns; private readonly int dataRegionSizeRows; private readonly int dataRegionSizeColumns; private readonly ECBlocks ecBlocks; private readonly int totalCodewords; internal Version(int versionNumber, int symbolSizeRows, int symbolSizeColumns, int dataRegionSizeRows, int dataRegionSizeColumns, ECBlocks ecBlocks) { this.versionNumber = versionNumber; this.symbolSizeRows = symbolSizeRows; this.symbolSizeColumns = symbolSizeColumns; this.dataRegionSizeRows = dataRegionSizeRows; this.dataRegionSizeColumns = dataRegionSizeColumns; this.ecBlocks = ecBlocks; // Calculate the total number of codewords int total = 0; int ecCodewords = ecBlocks.ECCodewords; ECB[] ecbArray = ecBlocks.ECBlocksValue; foreach (ECB ecBlock in ecbArray) { total += ecBlock.Count * (ecBlock.DataCodewords + ecCodewords); } this.totalCodewords = total; } public int getVersionNumber() { return versionNumber; } public int getSymbolSizeRows() { return symbolSizeRows; } public int getSymbolSizeColumns() { return symbolSizeColumns; } public int getDataRegionSizeRows() { return dataRegionSizeRows; } public int getDataRegionSizeColumns() { return dataRegionSizeColumns; } public int getTotalCodewords() { return totalCodewords; } internal ECBlocks getECBlocks() { return ecBlocks; } /// <summary> /// <p>Deduces version information from Data Matrix dimensions.</p> /// /// <param name="numRows">Number of rows in modules</param> /// <param name="numColumns">Number of columns in modules</param> /// <returns>Version for a Data Matrix Code of those dimensions</returns> /// <exception cref="FormatException">if dimensions do correspond to a valid Data Matrix size</exception> /// </summary> public static Version getVersionForDimensions(int numRows, int numColumns) { if ((numRows & 0x01) != 0 || (numColumns & 0x01) != 0) { return null; } foreach (var version in VERSIONS) { if (version.symbolSizeRows == numRows && version.symbolSizeColumns == numColumns) { return version; } } return null; } /// <summary> /// <p>Encapsulates a set of error-correction blocks in one symbol version. Most versions will /// use blocks of differing sizes within one version, so, this encapsulates the parameters for /// each set of blocks. It also holds the number of error-correction codewords per block since it /// will be the same across all blocks within one version.</p> /// </summary> internal sealed class ECBlocks { private readonly int ecCodewords; private readonly ECB[] _ecBlocksValue; internal ECBlocks(int ecCodewords, ECB ecBlocks) { this.ecCodewords = ecCodewords; this._ecBlocksValue = new ECB[] { ecBlocks }; } internal ECBlocks(int ecCodewords, ECB ecBlocks1, ECB ecBlocks2) { this.ecCodewords = ecCodewords; this._ecBlocksValue = new ECB[] { ecBlocks1, ecBlocks2 }; } internal int ECCodewords { get { return ecCodewords; } } internal ECB[] ECBlocksValue { get { return _ecBlocksValue; } } } /// <summary> /// <p>Encapsualtes the parameters for one error-correction block in one symbol version. /// This includes the number of data codewords, and the number of times a block with these /// parameters is used consecutively in the Data Matrix code version's format.</p> /// </summary> internal sealed class ECB { private readonly int count; private readonly int dataCodewords; internal ECB(int count, int dataCodewords) { this.count = count; this.dataCodewords = dataCodewords; } internal int Count { get { return count; } } internal int DataCodewords { get { return dataCodewords; } } } override public String ToString() { return versionNumber.ToString(); } /// <summary> /// See ISO 16022:2006 5.5.1 Table 7 /// </summary> private static Version[] buildVersions() { return new Version[] { new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))), new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))), new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))), new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))), new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))), new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))), new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))), new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))), new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))), new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))), new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))), new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))), new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))), new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))), new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))), new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))), new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))), new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))), new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))), new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))), new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))), new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))), new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))), new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))), new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))), new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))), new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))), new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))), new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))), new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49))) }; } } }
using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace CodeGenerator { class ImguiDefinitions { public EnumDefinition[] Enums; public TypeDefinition[] Types; public FunctionDefinition[] Functions; public Dictionary<string, MethodVariant> Variants; static int GetInt(JToken token, string key) { var v = token[key]; if (v == null) return 0; return v.ToObject<int>(); } public void LoadFrom(string directory) { JObject typesJson; using (StreamReader fs = File.OpenText(Path.Combine(directory, "structs_and_enums.json"))) using (JsonTextReader jr = new JsonTextReader(fs)) { typesJson = JObject.Load(jr); } JObject functionsJson; using (StreamReader fs = File.OpenText(Path.Combine(directory, "definitions.json"))) using (JsonTextReader jr = new JsonTextReader(fs)) { functionsJson = JObject.Load(jr); } JObject variantsJson = null; if (File.Exists(Path.Combine(directory, "variants.json"))) { using (StreamReader fs = File.OpenText(Path.Combine(directory, "variants.json"))) using (JsonTextReader jr = new JsonTextReader(fs)) { variantsJson = JObject.Load(jr); } } Variants = new Dictionary<string, MethodVariant>(); foreach (var jt in variantsJson.Children()) { JProperty jp = (JProperty)jt; ParameterVariant[] methodVariants = jp.Values().Select(jv => { return new ParameterVariant(jv["name"].ToString(), jv["type"].ToString(), jv["variants"].Select(s => s.ToString()).ToArray()); }).ToArray(); Variants.Add(jp.Name, new MethodVariant(jp.Name, methodVariants)); } var typeLocations = typesJson["locations"]; Enums = typesJson["enums"].Select(jt => { JProperty jp = (JProperty)jt; string name = jp.Name; if (typeLocations?[jp.Name]?.Value<string>().Contains("internal") ?? false) { return null; } EnumMember[] elements = jp.Values().Select(v => { return new EnumMember(v["name"].ToString(), v["calc_value"].ToString()); }).ToArray(); return new EnumDefinition(name, elements); }).Where(x => x != null).ToArray(); Types = typesJson["structs"].Select(jt => { JProperty jp = (JProperty)jt; string name = jp.Name; if (typeLocations?[jp.Name]?.Value<string>().Contains("internal") ?? false) { return null; } TypeReference[] fields = jp.Values().Select(v => { if (v["type"].ToString().Contains("static")) { return null; } return new TypeReference( v["name"].ToString(), v["type"].ToString(), GetInt(v, "size"), v["template_type"]?.ToString(), Enums); }).Where(tr => tr != null).ToArray(); return new TypeDefinition(name, fields); }).Where(x => x != null).ToArray(); Functions = functionsJson.Children().Select(jt => { JProperty jp = (JProperty)jt; string name = jp.Name; bool hasNonUdtVariants = jp.Values().Any(val => val["ov_cimguiname"]?.ToString().EndsWith("nonUDT") ?? false); OverloadDefinition[] overloads = jp.Values().Select(val => { string ov_cimguiname = val["ov_cimguiname"]?.ToString(); string cimguiname = val["cimguiname"].ToString(); string friendlyName = val["funcname"]?.ToString(); if (cimguiname.EndsWith("_destroy")) { friendlyName = "Destroy"; } //skip internal functions var typename = val["stname"]?.ToString(); if (!string.IsNullOrEmpty(typename)) { if (!Types.Any(x => x.Name == val["stname"]?.ToString())) { return null; } } if (friendlyName == null) { return null; } if (val["location"]?.ToString().Contains("internal") ?? false) return null; string exportedName = ov_cimguiname; if (exportedName == null) { exportedName = cimguiname; } if (hasNonUdtVariants && !exportedName.EndsWith("nonUDT2")) { return null; } string selfTypeName = null; int underscoreIndex = exportedName.IndexOf('_'); if (underscoreIndex > 0 && !exportedName.StartsWith("ig")) // Hack to exclude some weirdly-named non-instance functions. { selfTypeName = exportedName.Substring(0, underscoreIndex); } List<TypeReference> parameters = new List<TypeReference>(); // find any variants that can be applied to the parameters of this method based on the method name MethodVariant methodVariants = null; Variants.TryGetValue(jp.Name, out methodVariants); foreach (JToken p in val["argsT"]) { string pType = p["type"].ToString(); string pName = p["name"].ToString(); // if there are possible variants for this method then try to match them based on the parameter name and expected type ParameterVariant matchingVariant = methodVariants?.Parameters.Where(pv => pv.Name == pName && pv.OriginalType == pType).FirstOrDefault() ?? null; if (matchingVariant != null) matchingVariant.Used = true; parameters.Add(new TypeReference(pName, pType, 0, Enums, matchingVariant?.VariantTypes)); } Dictionary<string, string> defaultValues = new Dictionary<string, string>(); foreach (JToken dv in val["defaults"]) { JProperty dvProp = (JProperty)dv; defaultValues.Add(dvProp.Name, dvProp.Value.ToString()); } string returnType = val["ret"]?.ToString() ?? "void"; string comment = null; string structName = val["stname"].ToString(); bool isConstructor = val.Value<bool>("constructor"); bool isDestructor = val.Value<bool>("destructor"); if (isConstructor) { returnType = structName + "*"; } return new OverloadDefinition( exportedName, friendlyName, parameters.ToArray(), defaultValues, returnType, structName, comment, isConstructor, isDestructor); }).Where(od => od != null).ToArray(); if(overloads.Length == 0) return null; return new FunctionDefinition(name, overloads, Enums); }).Where(x => x != null).OrderBy(fd => fd.Name).ToArray(); } } class MethodVariant { public string Name { get; } public ParameterVariant[] Parameters { get; } public MethodVariant(string name, ParameterVariant[] parameters) { Name = name; Parameters = parameters; } } class ParameterVariant { public string Name { get; } public string OriginalType { get; } public string[] VariantTypes { get; } public bool Used { get; set; } public ParameterVariant(string name, string originalType, string[] variantTypes) { Name = name; OriginalType = originalType; VariantTypes = variantTypes; Used = false; } } class EnumDefinition { private readonly Dictionary<string, string> _sanitizedNames; public string Name { get; } public string FriendlyName { get; } public EnumMember[] Members { get; } public EnumDefinition(string name, EnumMember[] elements) { Name = name; if (Name.EndsWith('_')) { FriendlyName = Name.Substring(0, Name.Length - 1); } else { FriendlyName = Name; } Members = elements; _sanitizedNames = new Dictionary<string, string>(); foreach (EnumMember el in elements) { _sanitizedNames.Add(el.Name, SanitizeMemberName(el.Name)); } } public string SanitizeNames(string text) { foreach (KeyValuePair<string, string> kvp in _sanitizedNames) { text = text.Replace(kvp.Key, kvp.Value); } return text; } private string SanitizeMemberName(string memberName) { string ret = memberName; if (memberName.StartsWith(Name)) { ret = memberName.Substring(Name.Length); if (ret.StartsWith("_")) { ret = ret.Substring(1); } } if (ret.EndsWith('_')) { ret = ret.Substring(0, ret.Length - 1); } if (Char.IsDigit(ret.First())) ret = "_" + ret; return ret; } } class EnumMember { public EnumMember(string name, string value) { Name = name; Value = value; } public string Name { get; } public string Value { get; } } class TypeDefinition { public string Name { get; } public TypeReference[] Fields { get; } public TypeDefinition(string name, TypeReference[] fields) { Name = name; Fields = fields; } } class TypeReference { public string Name { get; } public string Type { get; } public string TemplateType { get; } public int ArraySize { get; } public bool IsFunctionPointer { get; } public string[] TypeVariants { get; } public bool IsEnum { get; } public TypeReference(string name, string type, int asize, EnumDefinition[] enums) : this(name, type, asize, null, enums, null) { } public TypeReference(string name, string type, int asize, EnumDefinition[] enums, string[] typeVariants) : this(name, type, asize, null, enums, typeVariants) { } public TypeReference(string name, string type, int asize, string templateType, EnumDefinition[] enums) : this(name, type, asize, templateType, enums, null) { } public TypeReference(string name, string type, int asize, string templateType, EnumDefinition[] enums, string[] typeVariants) { Name = name; Type = type.Replace("const", string.Empty).Trim(); if (Type.StartsWith("ImVector_")) { if (Type.EndsWith("*")) { Type = "ImVector*"; } else { Type = "ImVector"; } } if (Type.StartsWith("ImChunkStream_")) { if (Type.EndsWith("*")) { Type = "ImChunkStream*"; } else { Type = "ImChunkStream"; } } TemplateType = templateType; ArraySize = asize; int startBracket = name.IndexOf('['); if (startBracket != -1) { //This is only for older cimgui binding jsons int endBracket = name.IndexOf(']'); string sizePart = name.Substring(startBracket + 1, endBracket - startBracket - 1); if(ArraySize == 0) ArraySize = ParseSizeString(sizePart, enums); Name = Name.Substring(0, startBracket); } IsFunctionPointer = Type.IndexOf('(') != -1; TypeVariants = typeVariants; IsEnum = enums.Any(t => t.Name == type || t.FriendlyName == type || TypeInfo.WellKnownEnums.Contains(type)); } private int ParseSizeString(string sizePart, EnumDefinition[] enums) { int plusStart = sizePart.IndexOf('+'); if (plusStart != -1) { string first = sizePart.Substring(0, plusStart); string second = sizePart.Substring(plusStart, sizePart.Length - plusStart); int firstVal = int.Parse(first); int secondVal = int.Parse(second); return firstVal + secondVal; } if (!int.TryParse(sizePart, out int ret)) { foreach (EnumDefinition ed in enums) { if (sizePart.StartsWith(ed.Name)) { foreach (EnumMember member in ed.Members) { if (member.Name == sizePart) { return int.Parse(member.Value); } } } } ret = -1; } return ret; } public TypeReference WithVariant(int variantIndex, EnumDefinition[] enums) { if (variantIndex == 0) return this; else return new TypeReference(Name, TypeVariants[variantIndex - 1], ArraySize, TemplateType, enums); } } class FunctionDefinition { public string Name { get; } public OverloadDefinition[] Overloads { get; } public FunctionDefinition(string name, OverloadDefinition[] overloads, EnumDefinition[] enums) { Name = name; Overloads = ExpandOverloadVariants(overloads, enums); } private OverloadDefinition[] ExpandOverloadVariants(OverloadDefinition[] overloads, EnumDefinition[] enums) { List<OverloadDefinition> newDefinitions = new List<OverloadDefinition>(); foreach (OverloadDefinition overload in overloads) { bool hasVariants = false; int[] variantCounts = new int[overload.Parameters.Length]; for (int i = 0; i < overload.Parameters.Length; i++) { if (overload.Parameters[i].TypeVariants != null) { hasVariants = true; variantCounts[i] = overload.Parameters[i].TypeVariants.Length + 1; } else { variantCounts[i] = 1; } } if (hasVariants) { int totalVariants = variantCounts[0]; for (int i = 1; i < variantCounts.Length; i++) totalVariants *= variantCounts[i]; for (int i = 0; i < totalVariants; i++) { TypeReference[] parameters = new TypeReference[overload.Parameters.Length]; int div = 1; for (int j = 0; j < parameters.Length; j++) { int k = (i / div) % variantCounts[j]; parameters[j] = overload.Parameters[j].WithVariant(k, enums); if (j > 0) div *= variantCounts[j]; } newDefinitions.Add(overload.WithParameters(parameters)); } } else { newDefinitions.Add(overload); } } return newDefinitions.ToArray(); } } class OverloadDefinition { public string ExportedName { get; } public string FriendlyName { get; } public TypeReference[] Parameters { get; } public Dictionary<string, string> DefaultValues { get; } public string ReturnType { get; } public string StructName { get; } public bool IsMemberFunction { get; } public string Comment { get; } public bool IsConstructor { get; } public bool IsDestructor { get; } public OverloadDefinition( string exportedName, string friendlyName, TypeReference[] parameters, Dictionary<string, string> defaultValues, string returnType, string structName, string comment, bool isConstructor, bool isDestructor) { ExportedName = exportedName; FriendlyName = friendlyName; Parameters = parameters; DefaultValues = defaultValues; ReturnType = returnType.Replace("const", string.Empty).Replace("inline", string.Empty).Trim(); StructName = structName; IsMemberFunction = !string.IsNullOrEmpty(structName); Comment = comment; IsConstructor = isConstructor; IsDestructor = isDestructor; } public OverloadDefinition WithParameters(TypeReference[] parameters) { return new OverloadDefinition(ExportedName, FriendlyName, parameters, DefaultValues, ReturnType, StructName, Comment, IsConstructor, IsDestructor); } } }
// --------------------------------------------------------------------------- // <copyright file="Key.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- // --------------------------------------------------------------------- // <summary> // </summary> // --------------------------------------------------------------------- namespace Microsoft.Database.Isam { using System; using System.Collections; /// <summary> /// This collection is used to construct keys using generic values for each /// key segment comprising the key. Each key is NOT tied to any specific /// schema so the same key could be used with different indices. However, /// the key must be compatible with the index with which it is used or else /// an argument exception will be thrown. Type coercion will be performed /// as appropriate for each key segment when the key is used with an index /// based on the type of each key segment in the key versus the type of each /// key column in that index. If type coercion fails, an invalid cast /// exception will be thrown when the key is used. /// </summary> public class Key : CollectionBase { /// <summary> /// The prefix /// </summary> private bool prefix = false; /// <summary> /// The wildcard /// </summary> private bool wildcard = false; /// <summary> /// Gets a key that can be used to represent the start of an index. /// </summary> public static Key Start { get { return new Key(); } } /// <summary> /// Gets a key that can be used to represent the end of an index. /// </summary> public static Key End { get { return new Key(); } } /// <summary> /// Gets a value indicating whether [has prefix]. /// </summary> /// <value> /// <c>true</c> if [has prefix]; otherwise, <c>false</c>. /// </value> internal bool HasPrefix { get { return this.prefix; } } /// <summary> /// Gets a value indicating whether [has wildcard]. /// </summary> /// <value> /// <c>true</c> if [has wildcard]; otherwise, <c>false</c>. /// </value> internal bool HasWildcard { get { return this.wildcard == true || List.Count == 0; } } /// <summary> /// Returns a key containing one ordinary key segment per given value. /// </summary> /// <param name="values">the values for each key column that will be used to compose the key</param> /// <returns>A key containing one ordinary key segment per given value.</returns> /// <seealso cref="ComposeWildcard"/> /// <seealso cref="ComposePrefix"/> public static Key Compose(params object[] values) { Key key = new Key(); foreach (object value in values) { key.Add(value); } return key; } /// <summary> /// Returns a key containing one ordinary key segment per given value /// except that the last given value becomes a prefix key segment. /// </summary> /// <param name="values">the values for each key column that will be used to compose the key</param> /// <returns>A key containing one ordinary key segment per given value /// except that the last given value becomes a prefix key segment.</returns> /// <seealso cref="Compose"/> /// <seealso cref="ComposeWildcard"/> public static Key ComposePrefix(params object[] values) { Key key = new Key(); for (int i = 0; i < values.Length - 1; i++) { key.Add(values[i]); } key.AddPrefix(values[values.Length - 1]); return key; } /// <summary> /// Returns a key containing one ordinary key segment per given value /// and one wildcard key segment. /// </summary> /// <param name="values">the values for each key column that will be used to compose the key</param> /// <returns>A key containing one ordinary key segment per given value /// and one wildcard key segment.</returns> /// <seealso cref="Compose"/> /// <seealso cref="ComposePrefix"/> public static Key ComposeWildcard(params object[] values) { Key key = new Key(); foreach (object value in values) { key.Add(value); } key.AddWildcard(); return key; } /// <summary> /// Sets the next key segment of the key to the given value. /// </summary> /// <param name="value">the value for the next key column that will be used to compose the key</param> public void Add(object value) { List.Add(new KeySegment(value, false, false, false)); } /// <summary> /// Sets the next key segment of the key to the given value as a /// prefix. A prefix key segment will match any column value that /// has a prefix that matches the given value. /// </summary> /// <param name="value">the value for the next key column that will be used to compose the key</param> /// <remarks> /// Prefix key segments only make sense in the context of a variable /// length column. Any other use will result in an argument exception /// when the key is used. /// <para> /// A key may contain only one prefix key segment. Further, a prefix /// key segment may not be followed by an ordinary key segment. /// </para> /// </remarks> public void AddPrefix(object value) { List.Add(new KeySegment(value, true, false, false)); this.prefix = true; } /// <summary> /// Sets the next key segment of the key to the given value as a /// wildcard. A wildcard key segment will match any column value. /// </summary> /// <remarks> /// A key may contain any number of wildcard key segments. Further, a /// wildcard key segment may be followed only by other wildcard key /// segments. Finally, extra wildcard key segments will be ignored /// when the key is used. /// <para> /// A key with no key segments acts as if it contains a single wildcard /// key segment. /// </para> /// </remarks> public void AddWildcard() { // flag current last key segment as saying that the next key segment // will be a wildcard if (List.Count > 0) { KeySegment segment = (KeySegment)List[List.Count - 1]; this.List[List.Count - 1] = new KeySegment(segment.Value, segment.Prefix, segment.Wildcard, true); } try { // add a wildcard key segment List.Add(new KeySegment(null, false, true, false)); this.wildcard = true; } finally { // flag the new last key segment as saying that the next key segment // will not be a wildcard. this will handle the case where the // insertion of the new wildcard fails if (List.Count > 0) { KeySegment segment = (KeySegment)List[List.Count - 1]; this.List[List.Count - 1] = new KeySegment(segment.Value, segment.Prefix, segment.Wildcard, false); } } } /// <summary> /// Performs additional custom processes when validating a value. /// </summary> /// <param name="value">The object to validate.</param> /// <exception cref="System.ArgumentException"> /// value must be of type KeySegment;value /// or /// value cannot be a prefix if the key already contains a prefix;value /// or /// value cannot be a prefix if the key already contains a wildcard;value /// or /// value must be a wildcard if the key already contains a prefix;value /// or /// value must be a wildcard if the key already contains a wildcard;value /// </exception> protected override void OnValidate(object value) { bool sawPrefix = false; bool sawWildcard = false; foreach (KeySegment segment in this) { sawPrefix = sawPrefix || segment.Prefix == true; sawWildcard = sawWildcard || segment.Wildcard == true; } if (!(value is KeySegment)) { throw new ArgumentException("value must be of type KeySegment", "value"); } if (((KeySegment)value).Prefix == true && sawPrefix == true) { throw new ArgumentException("value cannot be a prefix if the key already contains a prefix", "value"); } if (((KeySegment)value).Prefix == true && sawWildcard == true) { throw new ArgumentException("value cannot be a prefix if the key already contains a wildcard", "value"); } if (((KeySegment)value).Prefix == false && ((KeySegment)value).Wildcard == false && sawPrefix == true) { throw new ArgumentException("value must be a wildcard if the key already contains a prefix", "value"); } if (((KeySegment)value).Prefix == false && ((KeySegment)value).Wildcard == false && sawWildcard == true) { throw new ArgumentException("value must be a wildcard if the key already contains a wildcard", "value"); } } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using Google.Apis.Download; using Google.Apis.Storage.v1.Data; using Google.Apis.Upload; using Google.Cloud.ClientTesting; using Google.Cloud.Iam.V1; using Google.Cloud.PubSub.V1; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Xunit; using Policy = Google.Apis.Storage.v1.Data.Policy; namespace Google.Cloud.Storage.V1.Snippets { [SnippetOutputCollector] [Collection(nameof(StorageSnippetFixture))] public class StorageClientSnippets { private readonly StorageSnippetFixture _fixture; public StorageClientSnippets(StorageSnippetFixture fixture) { _fixture = fixture; } [Fact] public void Overview() { var projectId = _fixture.ProjectId; // Sample: Overview var client = StorageClient.Create(); // Create a bucket var bucketName = Guid.NewGuid().ToString(); // must be globally unique var bucket = client.CreateBucket(projectId, bucketName); // Upload some files var content = Encoding.UTF8.GetBytes("hello, world"); var obj1 = client.UploadObject(bucketName, "file1.txt", "text/plain", new MemoryStream(content)); var obj2 = client.UploadObject(bucketName, "folder1/file2.txt", "text/plain", new MemoryStream(content)); // List objects foreach (var obj in client.ListObjects(bucketName, "")) { Console.WriteLine(obj.Name); } // Download file using (var stream = File.OpenWrite("file1.txt")) { client.DownloadObject(bucketName, "file1.txt", stream); } // End sample StorageSnippetFixture.SleepAfterBucketCreateDelete(); _fixture.RegisterLocalFileToDelete("file1.txt"); _fixture.RegisterBucketToDelete(bucketName); StorageSnippetFixture.SleepAfterBucketCreateDelete(); Assert.Equal(content, File.ReadAllBytes("file1.txt")); var objects = client.ListObjects(bucketName, "").ToList(); Assert.Contains(objects, o => o.Name == "file1.txt"); Assert.Contains(objects, o => o.Name == "folder1/file2.txt"); Assert.Contains(client.ListBuckets(projectId), b => b.Name == bucketName); } [Fact] public void CustomerSuppliedEncryptionKeys() { var bucketName = _fixture.BucketName; // Sample: CustomerSuppliedEncryptionKeys // Use EncryptionKey.Create if you already have a key. EncryptionKey key = EncryptionKey.Generate(); // This will affect all relevant object-based operations by default. var client = StorageClient.Create(encryptionKey: key); var content = Encoding.UTF8.GetBytes("hello, world"); client.UploadObject(bucketName, "encrypted.txt", "text/plain", new MemoryStream(content)); // When downloading, either use a client with the same key... client.DownloadObject(bucketName, "encrypted.txt", new MemoryStream()); // Or specify a key just for that operation. var client2 = StorageClient.Create(); client2.DownloadObject(bucketName, "encrypted.txt", new MemoryStream(), new DownloadObjectOptions { EncryptionKey = key }); // End sample } [Fact] public void ListBuckets() { var projectId = _fixture.ProjectId; // Snippet: ListBuckets var client = StorageClient.Create(); // List all buckets associated with a project var buckets = client.ListBuckets(projectId); // End snippet Assert.Contains(buckets, b => _fixture.BucketName == b.Name); } // See-also: ListBuckets // Member: ListBucketsAsync // See [ListBuckets](ref) for a synchronous example. // End see-also [Fact] public void CreateBucket() { var projectId = _fixture.ProjectId; // Snippet: CreateBucket(string,string,*) var client = StorageClient.Create(); // GCS bucket names must be globally unique var bucketName = Guid.NewGuid().ToString(); // Bucket defined in Google.Apis.Storage.v1.Data namespace var bucket = client.CreateBucket(projectId, bucketName); // End snippet _fixture.RegisterBucketToDelete(bucketName); StorageSnippetFixture.SleepAfterBucketCreateDelete(); Assert.Equal(bucketName, bucket.Name); Assert.True(!string.IsNullOrWhiteSpace(bucket.Id)); } // See-also: CreateBucket(string,string,*) // Member: CreateBucket(string,Bucket,*) // See [CreateBucket](ref) for an example using an alternative overload. // End see-also // See-also: CreateBucket(string,string,*) // Member: CreateBucketAsync(string,Bucket,*,*) // Member: CreateBucketAsync(string,string,*,*) // See [CreateBucket](ref) for a synchronous example. // End see-also [Fact] public void UpdateBucket() { var projectId = _fixture.ProjectId; var setupClient = StorageClient.Create(); // GCS bucket names must be globally unique var bucketName = Guid.NewGuid().ToString(); setupClient.CreateBucket(projectId, bucketName); StorageSnippetFixture.SleepAfterBucketCreateDelete(); _fixture.RegisterBucketToDelete(bucketName); // Snippet: UpdateBucket var client = StorageClient.Create(); var bucket = client.GetBucket(bucketName); bucket.Website = new Bucket.WebsiteData { MainPageSuffix = "index.html", NotFoundPage = "404.html" }; client.UpdateBucket(bucket); // End snippet // Fetch the bucket again to check that the change "stuck" var fetchedBucket = client.GetBucket(bucketName); Assert.Equal(bucketName, fetchedBucket.Name); Assert.Equal(bucket.Website.MainPageSuffix, fetchedBucket.Website.MainPageSuffix); } // See-also: UpdateBucket // Member: UpdateBucketAsync // See [UpdateBucket](ref) for a synchronous example. // End see-also [Fact] public void PatchBucket() { var projectId = _fixture.ProjectId; var setupClient = StorageClient.Create(); // GCS bucket names must be globally unique var bucketName = Guid.NewGuid().ToString(); setupClient.CreateBucket(projectId, bucketName); StorageSnippetFixture.SleepAfterBucketCreateDelete(); _fixture.RegisterBucketToDelete(bucketName); // Snippet: PatchBucket var client = StorageClient.Create(); // Note: no fetching of the bucket beforehand. We only specify the values we want // to change. var bucket = new Bucket { Name = bucketName, Website = new Bucket.WebsiteData { MainPageSuffix = "index.html", NotFoundPage = "404.html" } }; client.PatchBucket(bucket); // End snippet // Fetch the bucket to check that the change "stuck" var fetchedBucket = client.GetBucket(bucketName); Assert.Equal(bucketName, fetchedBucket.Name); Assert.Equal(bucket.Website.MainPageSuffix, fetchedBucket.Website.MainPageSuffix); } // See-also: PatchBucket // Member: PatchBucketAsync // See [PatchBucket](ref) for a synchronous example. // End see-also [Fact] public void ListObjects() { var bucketName = _fixture.BucketName; // Snippet: ListObjects var client = StorageClient.Create(); // List only objects with a name starting with "greet" var objects = client.ListObjects(bucketName, "greet"); // End snippet Assert.Contains(objects, o => _fixture.HelloStorageObjectName == o.Name); } // See-also: ListObjects // Member: ListObjectsAsync // See [ListObjects](ref) for a synchronous example. // End see-also [Fact] public void DownloadObject() { var bucketName = _fixture.BucketName; var projectId = _fixture.ProjectId; // Snippet: DownloadObject(string,string,*,*,*) var client = StorageClient.Create(); var source = "greetings/hello.txt"; var destination = "hello.txt"; using (var stream = File.Create(destination)) { // IDownloadProgress defined in Google.Apis.Download namespace var progress = new Progress<IDownloadProgress>( p => Console.WriteLine($"bytes: {p.BytesDownloaded}, status: {p.Status}") ); // Download source object from bucket to local file system client.DownloadObject(bucketName, source, stream, null, progress); } // End snippet _fixture.RegisterLocalFileToDelete(destination); // want to show the source in the snippet, but also // want to make sure it matches the one in the fixture Assert.Equal(source, _fixture.HelloStorageObjectName); Assert.Equal(_fixture.HelloWorldContent, File.ReadAllText(destination)); } // See-also: DownloadObject(string,string,*,*,*) // Member: DownloadObject(Object,*,*,*) // See [DownloadObject](ref) for an example using an alternative overload. // End see-also // See-also: DownloadObject(string,string,*,*,*) // Member: DownloadObjectAsync(string,string,*,*,*,*) // Member: DownloadObjectAsync(Object,*,*,*,*) // See [DownloadObject](ref) for a synchronous example. // End see-also [Fact] public void UploadObject() { var bucketName = _fixture.BucketName; // Snippet: UploadObject(string,string,*,*,*,*) var client = StorageClient.Create(); var source = "world.txt"; var destination = "places/world.txt"; var contentType = "text/plain"; using (var stream = File.OpenRead(source)) { // IUploadProgress defined in Google.Apis.Upload namespace var progress = new Progress<IUploadProgress>( p => Console.WriteLine($"bytes: {p.BytesSent}, status: {p.Status}") ); // var acl = PredefinedAcl.PublicRead // public var acl = PredefinedObjectAcl.AuthenticatedRead; // private var options = new UploadObjectOptions { PredefinedAcl = acl }; var obj = client.UploadObject(bucketName, destination, contentType, stream, options, progress); } // End snippet // want to show the source in the snippet, but also // want to make sure it matches the one in the fixture Assert.Equal(source, _fixture.WorldLocalFileName); } // See-also: UploadObject(string,string,*,*,*,*) // Member: UploadObject(Object,*,*,*) // See [UploadObject](ref) for an example using an alternative overload. // End see-also // See-also: UploadObject(string,string,*,*,*,*) // Member: UploadObjectAsync(string,string,*,*,*,*,*) // Member: UploadObjectAsync(Object,*,*,*,*) // See [UploadObject](ref) for a synchronous example. // End see-also [Fact] public async Task UploadObjectWithSessionUri() { var bucketName = _fixture.BucketName; // Sample: UploadObjectWithSessionUri var client = StorageClient.Create(); var source = "world.txt"; var destination = "places/world.txt"; var contentType = "text/plain"; // var acl = PredefinedAcl.PublicRead // public var acl = PredefinedObjectAcl.AuthenticatedRead; // private var options = new UploadObjectOptions { PredefinedAcl = acl }; // Create a temporary uploader so the upload session can be manually initiated without actually uploading. var tempUploader = client.CreateObjectUploader(bucketName, destination, contentType, new MemoryStream(), options); var uploadUri = await tempUploader.InitiateSessionAsync(); // Send uploadUri to (unauthenticated) client application, so it can perform the upload: using (var stream = File.OpenRead(source)) { // IUploadProgress defined in Google.Apis.Upload namespace IProgress<IUploadProgress> progress = new Progress<IUploadProgress>( p => Console.WriteLine($"bytes: {p.BytesSent}, status: {p.Status}") ); var actualUploader = ResumableUpload.CreateFromUploadUri(uploadUri, stream); actualUploader.ProgressChanged += progress.Report; await actualUploader.UploadAsync(); } // End sample // want to show the source in the snippet, but also // want to make sure it matches the one in the fixture Assert.Equal(source, _fixture.WorldLocalFileName); } [Fact] public void GetObject() { var bucketName = _fixture.BucketName; // Snippet: GetObject var client = StorageClient.Create(); var name = "greetings/hello.txt"; var obj = client.GetObject(bucketName, name); Console.WriteLine($"Name: {obj.Name}"); Console.WriteLine($"Size: {obj.Size}"); Console.WriteLine($"ContentType: {obj.ContentType}"); Console.WriteLine($"TimeCreated: {obj.TimeCreated}"); // End snippet } // See-also: GetObject // Member: GetObjectAsync // See [GetObject](ref) for a synchronous example. // End see-also [Fact] public void UpdateObject() { var bucketName = _fixture.BucketName; // Snippet: UpdateObject var client = StorageClient.Create(); var name = "update-example.txt"; var content = Encoding.UTF8.GetBytes("hello, world"); var obj = new Apis.Storage.v1.Data.Object { Bucket = bucketName, Name = name, ContentType = "text/json", Metadata = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } } }; obj = client.UploadObject(obj, new MemoryStream(content)); obj.Metadata.Remove("key1"); obj.Metadata["key2"] = "updated-value2"; obj.Metadata["key3"] = "value3"; obj.ContentType = "text/plain"; client.UpdateObject(obj); // End snippet var fetchedObject = client.GetObject(bucketName, name); Assert.Equal(name, fetchedObject.Name); Assert.False(fetchedObject.Metadata.ContainsKey("key1")); Assert.Equal("text/plain", fetchedObject.ContentType); Assert.Equal("updated-value2", fetchedObject.Metadata["key2"]); Assert.Equal("value3", fetchedObject.Metadata["key3"]); } // See-also: UpdateObject // Member: UpdateObjectAsync // See [UpdateObject](ref) for a synchronous example. // End see-also [Fact] public void PatchObject() { var bucketName = _fixture.BucketName; // Snippet: PatchObject var client = StorageClient.Create(); var name = "patch-example.txt"; var content = Encoding.UTF8.GetBytes("hello, world"); var obj = new Apis.Storage.v1.Data.Object { Bucket = bucketName, Name = name, ContentType = "text/json", // Deliberately incorrect Metadata = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } } }; client.UploadObject(obj, new MemoryStream(content)); var patchObject = new Apis.Storage.v1.Data.Object { // The bucket and name are required; everything else is optional. // Only specified properties will be updated. Bucket = bucketName, Name = name, ContentType = "text/plain", Metadata = new Dictionary<string, string> { { "key2", "updated-value2" }, { "key3", "value3" } } }; client.PatchObject(patchObject); // End snippet var fetchedObject = client.GetObject(bucketName, name); Assert.Equal(name, fetchedObject.Name); Assert.Equal("text/plain", fetchedObject.ContentType); // key1=value1 still exists, because the patch didn't remove it Assert.Equal("value1", fetchedObject.Metadata["key1"]); Assert.Equal("updated-value2", fetchedObject.Metadata["key2"]); Assert.Equal("value3", fetchedObject.Metadata["key3"]); } // See-also: PatchObject // Member: PatchObjectAsync // See [PatchObject](ref) for a synchronous example. // End see-also [Fact] public void CopyObject() { var projectId = _fixture.ProjectId; var sourceBucket = _fixture.BucketName; var destinationBucket = Guid.NewGuid().ToString(); StorageClient.Create().CreateBucket(projectId, destinationBucket); StorageSnippetFixture.SleepAfterBucketCreateDelete(); _fixture.RegisterBucketToDelete(destinationBucket); // Snippet: CopyObject var client = StorageClient.Create(); var sourceName = "greetings/hello.txt"; var destinationName = "copy.txt"; // This method actually uses the "rewrite" API operation, for added reliability // when copying large objects across locations, storage classes or encryption keys. client.CopyObject(sourceBucket, sourceName, destinationBucket, destinationName); // End snippet var obj = client.GetObject(destinationBucket, destinationName); Assert.Equal((ulong)Encoding.UTF8.GetByteCount(_fixture.HelloWorldContent), obj.Size.Value); } // See-also: CopyObject // Member: CopyObjectAsync // See [CopyObject](ref) for a synchronous example. // End see-also // TODO: // - ComposeObject? (or ConcatenateObjects?) // - MoveObject? (Copy then delete, as per node) // - DeleteFiles (on a bucket) - or an option on DeleteBucket? // - ACLs? // - WatchAll and stop watching? (Need an HTTPS site for testing.) [Fact] public void GetBucket() { var bucketName = _fixture.BucketName; // Snippet: GetBucket var client = StorageClient.Create(); var bucket = client.GetBucket(bucketName); Console.WriteLine($"Name: {bucket.Name}"); Console.WriteLine($"TimeCreated: {bucket.TimeCreated}"); // End snippet } // See-also: GetBucket // Member: GetBucketAsync // See [GetBucket](ref) for a synchronous example. // End see-also // TODO: Flag to delete all versions of an object? [Fact] public void DeleteObject() { // create a temp object to delete in the test var bucketName = _fixture.BucketName; var tempObjectName = "places/deleteme.txt"; StorageClient.Create().UploadObject(bucketName, tempObjectName, "", Stream.Null); // Snippet: DeleteObject(string,string,*) var client = StorageClient.Create(); var objectName = "places/deleteme.txt"; client.DeleteObject(bucketName, objectName); // End snippet // want to show the name in the snippet, but also // want to make sure it matches the one in the test Assert.Equal(objectName, tempObjectName); Assert.DoesNotContain(client.ListObjects(bucketName, ""), o => o.Name == objectName); } // See-also: DeleteObject(string,string,*) // Member: DeleteObject(Object,*) // See [DeleteObject](ref) for an example using an alternative overload. // End see-also // See-also: DeleteObject(string,string,*) // Member: DeleteObjectAsync(Object,*,*) // Member: DeleteObjectAsync(string,string,*,*) // See [DeleteObject](ref) for a synchronous example. // End see-also [Fact] public void DeleteBucket() { var bucketName = Guid.NewGuid().ToString(); StorageClient.Create().CreateBucket(_fixture.ProjectId, bucketName); StorageSnippetFixture.SleepAfterBucketCreateDelete(); // Snippet: DeleteBucket(string,*) var client = StorageClient.Create(); client.DeleteBucket(bucketName); // End snippet StorageSnippetFixture.SleepAfterBucketCreateDelete(); Assert.DoesNotContain(client.ListBuckets(_fixture.ProjectId), b => b.Name == bucketName); } // See-also: DeleteBucket(string,*) // Member: DeleteBucket(Bucket,*) // See [DeleteBucket](ref) for an example using an alternative overload. // End see-also // See-also: DeleteBucket(string,*) // Member: DeleteBucketAsync(Bucket,*,*) // Member: DeleteBucketAsync(string,*,*) // See [DeleteBucket](ref) for a synchronous example. // End see-also [Fact] public void GetBucketIamPolicy() { var bucketName = _fixture.BucketName; // Snippet: GetBucketIamPolicy(string,*) StorageClient client = StorageClient.Create(); Policy policy = client.GetBucketIamPolicy(bucketName); foreach (Policy.BindingsData binding in policy.Bindings) { Console.WriteLine($"Role: {binding.Role}"); foreach (var permission in binding.Members) { Console.WriteLine($" {permission}"); } } // End snippet } // See-also: GetBucketIamPolicy(string,*) // Member: GetBucketIamPolicyAsync(string,*,*) // See [GetBucketIamPolicy](ref) for a synchronous example. // End see-also [Fact] public async Task SetBucketIamPolicy() { var projectId = _fixture.ProjectId; var bucketName = Guid.NewGuid().ToString(); _fixture.RegisterBucketToDelete(bucketName); // Snippet: SetBucketIamPolicy(string, *, *) // Create a new bucket and an empty file within it StorageClient client = StorageClient.Create(); Bucket bucket = client.CreateBucket(projectId, bucketName); var obj = client.UploadObject(bucketName, "empty.txt", "text/plain", new MemoryStream()); // Demonstrate that without authentication, we can't download the object HttpClient httpClient = new HttpClient(); HttpResponseMessage response1 = await httpClient.GetAsync(obj.MediaLink); Console.WriteLine($"Response code before setting policy: {response1.StatusCode}"); // Fetch the current IAM policy, and modify it in memory to allow all users // to view objects. Policy policy = client.GetBucketIamPolicy(bucketName); string role = "roles/storage.objectViewer"; Policy.BindingsData binding = policy.Bindings .Where(b => b.Role == role) .FirstOrDefault(); if (binding == null) { binding = new Policy.BindingsData { Role = role, Members = new List<string>() }; policy.Bindings.Add(binding); } binding.Members.Add("allUsers"); // Update the IAM policy on the bucket. client.SetBucketIamPolicy(bucketName, policy); // Download the object again: this time the response should be OK HttpResponseMessage response2 = await httpClient.GetAsync(obj.MediaLink); Console.WriteLine($"Response code after setting policy: {response2.StatusCode}"); // End snippet StorageSnippetFixture.SleepAfterBucketCreateDelete(); Assert.Equal(HttpStatusCode.Unauthorized, response1.StatusCode); Assert.Equal(HttpStatusCode.OK, response2.StatusCode); } // See-also: SetBucketIamPolicy(string, *, *) // Member: SetBucketIamPolicyAsync(string,*,*,*) // See [SetBucketIamPolicy](ref) for a synchronous example. // End see-also [Fact] public void TestBucketIamPermissions() { var bucketName = _fixture.BucketName; // Snippet: TestBucketIamPermissions(string,*,*) StorageClient client = StorageClient.Create(); IList<string> permissions = client.TestBucketIamPermissions(bucketName, new[] { "storage.buckets.get", "storage.objects.list" }); Console.WriteLine("Permissions held:"); foreach (string permission in permissions) { Console.WriteLine($" {permission}"); } // End snippet } // See-also: TestBucketIamPermissions(string,*,*) // Member: TestBucketIamPermissionsAsync(string,*,*,*) // See [TestBucketIamPermissions](ref) for a synchronous example. // End see-also [Fact] public void SetBucketLabel() { var bucketName = _fixture.BucketName; // Snippet: SetBucketLabel(string, string, string, *) StorageClient client = StorageClient.Create(); string now = DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture); string newValue = "new_value_" + now; string oldValue = client.SetBucketLabel(bucketName, "label", newValue); Console.WriteLine($"Old value: {oldValue}"); // Verify the label is now correct... Bucket bucket = client.GetBucket(bucketName); string fetchedValue = bucket.Labels?["label"]; Console.WriteLine($"Fetched value: {fetchedValue}"); // End snippet Assert.Equal(newValue, fetchedValue); } // See-also: SetBucketLabel(string, string, string, *) // Member: SetBucketLabelAsync(string, string, string, *, *) // See [SetBucketLabel](ref) for a synchronous example. // End see-also [Fact] public void RemoveBucketLabel() { var bucketName = _fixture.BucketName; // Snippet: RemoveBucketLabel(string, string, *) StorageClient client = StorageClient.Create(); string oldValue = client.RemoveBucketLabel(bucketName, "label"); Console.WriteLine($"Old value: {oldValue}"); // Verify the label is now gone... Bucket bucket = client.GetBucket(bucketName); string fetchedValue = null; bucket.Labels?.TryGetValue("label", out fetchedValue); Console.WriteLine($"Fetched value: {fetchedValue}"); // End snippet Assert.Null(fetchedValue); } // See-also: RemoveBucketLabel(string, string, *) // Member: RemoveBucketLabelAsync(string, string, *, *) // See [RemoveBucketLabel](ref) for a synchronous example. // End see-also [Fact] public void ClearBucketLabels() { var bucketName = _fixture.BucketName; // Snippet: ClearBucketLabels(string, *) StorageClient client = StorageClient.Create(); IDictionary<string, string> oldLabels = client.ClearBucketLabels(bucketName); Console.WriteLine($"Number of labels before clearing: {oldLabels.Count}"); // End snippet Assert.Null(client.GetBucket(bucketName).Labels); } // See-also: ClearBucketLabels(string, *) // Member: ClearBucketLabelsAsync(string, *, *) // See [ClearBucketLabels](ref) for a synchronous example. // End see-also [Fact] public void ModifyBucketLabels() { var bucketName = _fixture.BucketName; // Snippet: ModifyBucketLabels(string, *, *) StorageClient client = StorageClient.Create(); string now = DateTime.UtcNow.ToString("yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture); IDictionary<string, string> labelChanges = new Dictionary<string, string> { { "label1", "new_value_1_" + now }, { "label2", "new_value_2_" + now }, }; IDictionary<string, string> oldValues = client.ModifyBucketLabels(bucketName, labelChanges); Console.WriteLine("Old values for changed labels:"); foreach (KeyValuePair<string, string> entry in oldValues) { Console.WriteLine($" {entry.Key}: {entry.Value}"); } Console.WriteLine("All labels:"); IDictionary<string, string> allLabels = client.GetBucket(bucketName).Labels ?? new Dictionary<string, string>(); foreach (KeyValuePair<string, string> entry in allLabels) { Console.WriteLine($" {entry.Key}: {entry.Value}"); } // End snippet } // See-also: ModifyBucketLabels(string, *, *) // Member: ModifyBucketLabelsAsync(string, *, *, *) // See [ModifyBucketLabels](ref) for a synchronous example. // End see-also [Fact] public void GetStorageServiceAccountEmail() { var projectId = _fixture.ProjectId; // Snippet: GetStorageServiceAccountEmail(string, *) StorageClient client = StorageClient.Create(); string serviceAccountEmail = client.GetStorageServiceAccountEmail(projectId); Console.WriteLine(serviceAccountEmail); // End snippet } // See-also: GetStorageServiceAccountEmail(string, *) // Member: GetStorageServiceAccountEmailAsync(string, *, *) // See [GetStorageServiceAccountEmail](ref) for a synchronous example. // End see-also [Fact] public void GetNotification() { var projectId = _fixture.ProjectId; string bucket = _fixture.BucketName; var created = _fixture.CreateNotification("prefix1"); string notificationId = created.Id; // Snippet: GetNotification(string, string, *) StorageClient client = StorageClient.Create(); Notification notification = client.GetNotification(bucket, notificationId); Console.WriteLine($"ID: {notification.Id}"); Console.WriteLine($"Payload format: {notification.PayloadFormat}"); Console.WriteLine($"Topic: {notification.Topic}"); Console.WriteLine($"Prefix: {notification.ObjectNamePrefix}"); Console.WriteLine($"Event types: {string.Join(",", notification.EventTypes ?? new string[0])}"); // End snippet } // See-also: GetNotification(string, string, *) // Member: GetNotificationAsync(string, string, *, *) // See [GetNotification](ref) for a synchronous example. // End see-also [Fact] public void CreateNotification() { var projectId = _fixture.ProjectId; string bucket = _fixture.BucketName; // This creates the topic, which is most of the work... var created = _fixture.CreateNotification("prefix2"); var topicId = created.Topic.Split('/').Last(); // Snippet: CreateNotification(string, Notification, *) TopicName topicName = new TopicName(projectId, topicId); StorageClient client = StorageClient.Create(); Notification notification = new Notification { Topic = $"//pubsub.googleapis.com/{topicName}", PayloadFormat = "JSON_API_V1" }; notification = client.CreateNotification(bucket, notification); Console.WriteLine($"Created notification ID: {notification.Id}"); // End snippet } // See-also: CreateNotification(string, Notification, *) // Member: CreateNotificationAsync(string, Notification, *, *) // See [CreateNotification](ref) for a synchronous example. // End see-also [Fact] public void DeleteNotification() { var projectId = _fixture.ProjectId; string bucket = _fixture.BucketName; var notificationId = _fixture.CreateNotification("prefix3").Id; // Snippet: DeleteNotification(string, string, *) StorageClient client = StorageClient.Create(); client.DeleteNotification(bucket, notificationId); // End snippet } // See-also: DeleteNotification(string, string, *) // Member: DeleteNotificationAsync(string, string, *, *) // See [DeleteNotification](ref) for a synchronous example. // End see-also [Fact] public void ListNotifications() { var projectId = _fixture.ProjectId; string bucket = _fixture.BucketName; // Snippet: ListNotifications(string, *) StorageClient client = StorageClient.Create(); IReadOnlyList<Notification> notifications = client.ListNotifications(bucket); foreach (Notification notification in notifications) { Console.WriteLine($"{notification.Id}: Topic={notification.Topic}; Prefix={notification.ObjectNamePrefix}"); } // End snippet } // See-also: ListNotifications(string, *) // Member: ListNotificationsAsync(string, *, *) // See [ListNotifications](ref) for a synchronous example. // End see-also [Fact] public void NotificationsOverview() { string projectId = _fixture.ProjectId; string bucket = _fixture.BucketName; string topicId = "topic-" + Guid.NewGuid().ToString().ToLowerInvariant(); // Sample: NotificationsOverview // First create a Pub/Sub topic. PublisherServiceApiClient publisherClient = PublisherServiceApiClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisherClient.CreateTopic(topicName); // Prepare the topic for Storage notifications. The Storage Service Account must have Publish permission // for the topic. The code below adds the service account into the "roles/pubsub.publisher" role for the topic. // Determine the Storage Service Account name to use in IAM operations. StorageClient storageClient = StorageClient.Create(); string storageServiceAccount = $"serviceAccount:{storageClient.GetStorageServiceAccountEmail(projectId)}"; // Fetch the IAM policy for the topic. Iam.V1.Policy policy = publisherClient.GetIamPolicy(topicName.ToString()); var role = "roles/pubsub.publisher"; // Ensure the Storage Service Account is in the publisher role, setting the IAM policy for the topic // on the server if necessary. if (policy.AddRoleMember(role, storageServiceAccount)) { publisherClient.SetIamPolicy(topicName.ToString(), policy); } // Now that the topic is ready, we can create a notification configuration for Storage Notification notification = new Notification { Topic = $"//pubsub.googleapis.com/{topicName}", PayloadFormat = "JSON_API_V1" }; notification = storageClient.CreateNotification(bucket, notification); Console.WriteLine($"Created notification ID: {notification.Id}"); // End sample _fixture.RegisterTopicToDelete(topicName); } } }
/*=============================================================================================== Load from memory example Copyright (c), Firelight Technologies Pty, Ltd 2004-2011. This example is simply a variant of the play sound example, but it loads the data into memory then uses the 'load from memory' feature of System::createSound. ===============================================================================================*/ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Runtime.InteropServices; using System.IO; namespace loadfrommemory { public class Form1 : System.Windows.Forms.Form { private FMOD.System system = null; private FMOD.Sound sound = null; private FMOD.Channel channel = null; private byte[] audiodata; private System.Windows.Forms.Label label; private System.Windows.Forms.Button playButton; private System.Windows.Forms.Button pauseButton; private System.Windows.Forms.Button exit_button; private System.Windows.Forms.StatusBar statusBar; private System.Windows.Forms.Timer timer; private System.ComponentModel.IContainer components; public Form1() { InitializeComponent(); } protected override void Dispose( bool disposing ) { if( disposing ) { FMOD.RESULT result; /* Shut down */ if (sound != null) { result = sound.release(); ERRCHECK(result); } if (system != null) { result = system.close(); ERRCHECK(result); result = system.release(); ERRCHECK(result); } if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.label = new System.Windows.Forms.Label(); this.playButton = new System.Windows.Forms.Button(); this.pauseButton = new System.Windows.Forms.Button(); this.exit_button = new System.Windows.Forms.Button(); this.statusBar = new System.Windows.Forms.StatusBar(); this.timer = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // label // this.label.Location = new System.Drawing.Point(16, 16); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(264, 32); this.label.TabIndex = 10; this.label.Text = "Copyright (c) Firelight Technologies 2004-2011"; this.label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // playButton // this.playButton.Location = new System.Drawing.Point(8, 56); this.playButton.Name = "playButton"; this.playButton.Size = new System.Drawing.Size(136, 32); this.playButton.TabIndex = 25; this.playButton.Text = "Play"; this.playButton.Click += new System.EventHandler(this.playButton_Click); // // pauseButton // this.pauseButton.Location = new System.Drawing.Point(152, 56); this.pauseButton.Name = "pauseButton"; this.pauseButton.Size = new System.Drawing.Size(136, 32); this.pauseButton.TabIndex = 26; this.pauseButton.Text = "Pause/Resume"; this.pauseButton.Click += new System.EventHandler(this.pauseButton_Click); // // exit_button // this.exit_button.Location = new System.Drawing.Point(110, 96); this.exit_button.Name = "exit_button"; this.exit_button.Size = new System.Drawing.Size(72, 24); this.exit_button.TabIndex = 27; this.exit_button.Text = "Exit"; this.exit_button.Click += new System.EventHandler(this.exit_button_Click); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 123); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(292, 24); this.statusBar.TabIndex = 28; // // timer // this.timer.Enabled = true; this.timer.Interval = 10; this.timer.Tick += new System.EventHandler(this.timer_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 147); this.Controls.Add(this.statusBar); this.Controls.Add(this.exit_button); this.Controls.Add(this.pauseButton); this.Controls.Add(this.playButton); this.Controls.Add(this.label); this.Name = "Form1"; this.Text = "Load From Memory Example"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion [STAThread] static void Main() { Application.Run(new Form1()); } private void Form1_Load(object sender, System.EventArgs e) { uint version = 0; FMOD.RESULT result; int length; FMOD.CREATESOUNDEXINFO exinfo = new FMOD.CREATESOUNDEXINFO(); /* Global Settings */ result = FMOD.Factory.System_Create(ref system); ERRCHECK(result); result = system.getVersion(ref version); ERRCHECK(result); if (version < FMOD.VERSION.number) { MessageBox.Show("Error! You are using an old version of FMOD " + version.ToString("X") + ". This program requires " + FMOD.VERSION.number.ToString("X") + "."); Application.Exit(); } result = system.init(1, FMOD.INITFLAGS.NORMAL, (IntPtr)null); ERRCHECK(result); length = LoadFileIntoMemory("../../../../../examples/media/wave.mp3"); exinfo.cbsize = Marshal.SizeOf(exinfo); exinfo.length = (uint)length; result = system.createSound(audiodata, (FMOD.MODE.HARDWARE | FMOD.MODE.OPENMEMORY), ref exinfo, ref sound); ERRCHECK(result); } private void playButton_Click(object sender, System.EventArgs e) { FMOD.RESULT result; result = system.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel); ERRCHECK(result); } private void pauseButton_Click(object sender, System.EventArgs e) { FMOD.RESULT result; bool paused = false; if (channel != null) { result = channel.getPaused(ref paused); ERRCHECK(result); result = channel.setPaused(!paused); ERRCHECK(result); } } private void exit_button_Click(object sender, System.EventArgs e) { Application.Exit(); } private void timer_Tick(object sender, System.EventArgs e) { FMOD.RESULT result; uint ms = 0; uint lenms = 0; bool playing = false; bool paused = false; if (channel != null) { result = channel.isPlaying(ref playing); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = channel.getPaused(ref paused); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = channel.getPosition(ref ms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = sound.getLength(ref lenms, FMOD.TIMEUNIT.MS); if ((result != FMOD.RESULT.OK) && (result != FMOD.RESULT.ERR_INVALID_HANDLE)) { ERRCHECK(result); } } statusBar.Text = "Time " + (ms / 1000 / 60) + ":" + (ms / 1000 % 60) + ":" + (ms / 10 % 100) + "/" + (lenms / 1000 / 60) + ":" + (lenms / 1000 % 60) + ":" + (lenms / 10 % 100) + " : " + (paused ? "Paused " : playing ? "Playing" : "Stopped"); if (system != null) { system.update(); } } private int LoadFileIntoMemory(string filename) { int length; FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); audiodata = new byte[fs.Length]; length = (int)fs.Length; fs.Read(audiodata, 0, length); fs.Close(); return length; } private void ERRCHECK(FMOD.RESULT result) { if (result != FMOD.RESULT.OK) { timer.Stop(); MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result)); Environment.Exit(-1); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace RelationOneToManySelf.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }