context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//----------------------------------------------------------------------- // <copyright file="SimpleDataPortal.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Implements the server-side DataPortal as discussed</summary> //----------------------------------------------------------------------- using System; using System.Threading.Tasks; using Csla.Properties; using Csla.Reflection; namespace Csla.Server { /// <summary> /// Implements the server-side DataPortal as discussed /// in Chapter 4. /// </summary> public class SimpleDataPortal : IDataPortalServer { /// <summary> /// Create a new business object. /// </summary> /// <param name="objectType">Type of business object to create.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public async Task<DataPortalResult> Create( Type objectType, object criteria, DataPortalContext context, bool isSync) { DataPortalTarget obj = null; var eventArgs = new DataPortalEventArgs(context, objectType, criteria, DataPortalOperations.Create); try { obj = new DataPortalTarget(ApplicationContext.DataPortalActivator.CreateInstance(objectType)); ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance); obj.OnDataPortalInvoke(eventArgs); obj.MarkNew(); await obj.CreateAsync(criteria, isSync); obj.ThrowIfBusy(); obj.OnDataPortalInvokeComplete(eventArgs); return new DataPortalResult(obj.Instance); } catch (Exception ex) { try { if (obj != null) obj.OnDataPortalException(eventArgs, ex); } catch { // ignore exceptions from the exception handler } object outval = null; if (obj != null) outval = obj.Instance; throw DataPortal.NewDataPortalException( "DataPortal.Create " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, outval, criteria, "DataPortal.Create", ex), outval); } finally { object reference = null; if (obj != null) reference = obj.Instance; ApplicationContext.DataPortalActivator.FinalizeInstance(reference); } } /// <summary> /// Get an existing business object. /// </summary> /// <param name="objectType">Type of business object to retrieve.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public async Task<DataPortalResult> Fetch(Type objectType, object criteria, DataPortalContext context, bool isSync) { DataPortalTarget obj = null; var eventArgs = new DataPortalEventArgs(context, objectType, criteria, DataPortalOperations.Fetch); try { obj = new DataPortalTarget(ApplicationContext.DataPortalActivator.CreateInstance(objectType)); ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance); obj.OnDataPortalInvoke(eventArgs); obj.MarkOld(); await obj.FetchAsync(criteria, isSync); obj.ThrowIfBusy(); obj.OnDataPortalInvokeComplete(eventArgs); return new DataPortalResult(obj.Instance); } catch (Exception ex) { try { if (obj != null) obj.OnDataPortalException(eventArgs, ex); } catch { // ignore exceptions from the exception handler } object outval = null; if (obj != null) outval = obj.Instance; throw DataPortal.NewDataPortalException( "DataPortal.Fetch " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, outval, criteria, "DataPortal.Fetch", ex), outval); } finally { object reference = null; if (obj != null) reference = obj.Instance; ApplicationContext.DataPortalActivator.FinalizeInstance(reference); } } /// <summary> /// Update a business object. /// </summary> /// <param name="obj">Business object to update.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")] public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync) { DataPortalOperations operation = DataPortalOperations.Update; Type objectType = obj.GetType(); var lb = new DataPortalTarget(obj); if (lb.Instance is Core.ICommandObject) return await Execute(lb, context, isSync); var eventArgs = new DataPortalEventArgs(context, objectType, obj, operation); try { ApplicationContext.DataPortalActivator.InitializeInstance(lb.Instance); lb.OnDataPortalInvoke(eventArgs); await lb.UpdateAsync(isSync); lb.ThrowIfBusy(); lb.OnDataPortalInvokeComplete(eventArgs); return new DataPortalResult(lb.Instance); } catch (Exception ex) { try { lb.OnDataPortalException(eventArgs, ex); } catch { // ignore exceptions from the exception handler } throw DataPortal.NewDataPortalException( "DataPortal.Update " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(obj.GetType(), obj, null, "DataPortal.Update", ex), obj); } finally { object reference = null; if (lb != null) reference = lb.Instance; ApplicationContext.DataPortalActivator.FinalizeInstance(reference); } } private async Task<DataPortalResult> Execute(DataPortalTarget obj, DataPortalContext context, bool isSync) { DataPortalOperations operation = DataPortalOperations.Execute; Type objectType = obj.Instance.GetType(); var eventArgs = new DataPortalEventArgs(context, objectType, obj, operation); try { ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance); obj.OnDataPortalInvoke(eventArgs); await obj.ExecuteAsync(isSync); obj.ThrowIfBusy(); obj.OnDataPortalInvokeComplete(eventArgs); return new DataPortalResult(obj.Instance); } catch (Exception ex) { try { obj.OnDataPortalException(eventArgs, ex); } catch { // ignore exceptions from the exception handler } object reference = null; reference = obj.Instance ?? obj; throw DataPortal.NewDataPortalException( "DataPortal.Execute " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(reference.GetType(), reference, null, "DataPortal.Execute", ex), reference); } finally { object reference = null; if (obj != null) reference = obj.Instance; ApplicationContext.DataPortalActivator.FinalizeInstance(reference); } } /// <summary> /// Delete a business object. /// </summary> /// <param name="objectType">Type of business object to create.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "Csla.Server.DataPortalException.#ctor(System.String,System.Exception,Csla.Server.DataPortalResult)")] public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync) { DataPortalTarget obj = null; var eventArgs = new DataPortalEventArgs(context, objectType, criteria, DataPortalOperations.Delete); try { obj = new DataPortalTarget(ApplicationContext.DataPortalActivator.CreateInstance(objectType)); ApplicationContext.DataPortalActivator.InitializeInstance(obj.Instance); obj.OnDataPortalInvoke(eventArgs); await obj.DeleteAsync(criteria, isSync); obj.ThrowIfBusy(); obj.OnDataPortalInvokeComplete(eventArgs); return new DataPortalResult(); } catch (Exception ex) { try { obj.OnDataPortalException(eventArgs, ex); } catch { // ignore exceptions from the exception handler } throw DataPortal.NewDataPortalException( "DataPortal.Delete " + Resources.FailedOnServer, new DataPortalExceptionHandler().InspectException(objectType, obj, null, "DataPortal.Delete", ex), null); } finally { object reference = null; if (obj != null) reference = obj.Instance; ApplicationContext.DataPortalActivator.FinalizeInstance(reference); } } } }
// 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\Engine\Classes\Camera\CameraComponent.h:21 namespace UnrealEngine { [ManageType("ManageCameraComponent")] public partial class ManageCameraComponent : UCameraComponent, IManageWrapper { public ManageCameraComponent(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_NotifyCameraCut(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SetFieldOfView(IntPtr self, float inFieldOfView); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnAttachmentChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnHiddenInGameChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnVisibilityChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PropagateLightingScenarioChange(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_UpdateBounds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_Activate(IntPtr self, bool bReset); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_CreateRenderState_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_Deactivate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_DestroyComponent(IntPtr self, bool bPromoteChildren); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_DestroyRenderState_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_InitializeComponent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnActorEnableCollisionChanged(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnComponentCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnCreatePhysicsState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnDestroyPhysicsState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnRegister(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnRep_IsActive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnUnregister(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SendRenderDynamicData_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SendRenderTransform_Concurrent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SetActive(IntPtr self, bool bNewActive, bool bReset); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_ToggleActive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_UninitializeComponent(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UCameraComponent_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// Can be called from external code to notify that this camera was cut to, so it can update /// <para>things like interpolation if necessary. </para> /// </summary> public override void NotifyCameraCut() => E__Supper__UCameraComponent_NotifyCameraCut(this); public override void SetFieldOfView(float inFieldOfView) => E__Supper__UCameraComponent_SetFieldOfView(this, inFieldOfView); /// <summary> /// DEPRECATED - Use DetachFromComponent() instead /// </summary> public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify) => E__Supper__UCameraComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify); /// <summary> /// Called when AttachParent changes, to allow the scene to update its attachment state. /// </summary> public override void OnAttachmentChanged() => E__Supper__UCameraComponent_OnAttachmentChanged(this); /// <summary> /// Overridable internal function to respond to changes in the hidden in game value of the component. /// </summary> protected override void OnHiddenInGameChanged() => E__Supper__UCameraComponent_OnHiddenInGameChanged(this); /// <summary> /// Overridable internal function to respond to changes in the visibility of the component. /// </summary> protected override void OnVisibilityChanged() => E__Supper__UCameraComponent_OnVisibilityChanged(this); /// <summary> /// Updates any visuals after the lighting has changed /// </summary> public override void PropagateLightingScenarioChange() => E__Supper__UCameraComponent_PropagateLightingScenarioChange(this); /// <summary> /// Update the Bounds of the component. /// </summary> public override void UpdateBounds() => E__Supper__UCameraComponent_UpdateBounds(this); /// <summary> /// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true. /// </summary> /// <param name="bTriggerNotifiers">if true, send zone/volume change events</param> public override void UpdatePhysicsVolume(bool bTriggerNotifiers) => E__Supper__UCameraComponent_UpdatePhysicsVolume(this, bTriggerNotifiers); /// <summary> /// Activates the SceneComponent, should be overridden by native child classes. /// </summary> /// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param> public override void Activate(bool bReset) => E__Supper__UCameraComponent_Activate(this, bReset); /// <summary> /// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component). /// <para>All Components (that want initialization) in the level will be Initialized on load before any </para> /// Actor/Component gets BeginPlay. /// <para>Requires component to be registered and initialized. </para> /// </summary> public override void BeginPlay() => E__Supper__UCameraComponent_BeginPlay(this); /// <summary> /// Used to create any rendering thread information for this component /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void CreateRenderState_Concurrent() => E__Supper__UCameraComponent_CreateRenderState_Concurrent(this); /// <summary> /// Deactivates the SceneComponent. /// </summary> public override void Deactivate() => E__Supper__UCameraComponent_Deactivate(this); /// <summary> /// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill. /// </summary> public override void DestroyComponent(bool bPromoteChildren) => E__Supper__UCameraComponent_DestroyComponent(this, bPromoteChildren); /// <summary> /// Used to shut down any rendering thread structure for this component /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void DestroyRenderState_Concurrent() => E__Supper__UCameraComponent_DestroyRenderState_Concurrent(this); /// <summary> /// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component). /// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para> /// Requires component to be registered, and bWantsInitializeComponent to be true. /// </summary> public override void InitializeComponent() => E__Supper__UCameraComponent_InitializeComponent(this); /// <summary> /// Called when this actor component has moved, allowing it to discard statically cached lighting information. /// </summary> public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly) => E__Supper__UCameraComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly); /// <summary> /// Called on each component when the Actor's bEnableCollisionChanged flag changes /// </summary> public override void OnActorEnableCollisionChanged() => E__Supper__UCameraComponent_OnActorEnableCollisionChanged(this); /// <summary> /// Called when a component is created (not loaded). This can happen in the editor or during gameplay /// </summary> public override void OnComponentCreated() => E__Supper__UCameraComponent_OnComponentCreated(this); /// <summary> /// Called when a component is destroyed /// </summary> /// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param> public override void OnComponentDestroyed(bool bDestroyingHierarchy) => E__Supper__UCameraComponent_OnComponentDestroyed(this, bDestroyingHierarchy); /// <summary> /// Used to create any physics engine information for this component /// </summary> protected override void OnCreatePhysicsState() => E__Supper__UCameraComponent_OnCreatePhysicsState(this); /// <summary> /// Used to shut down and physics engine structure for this component /// </summary> protected override void OnDestroyPhysicsState() => E__Supper__UCameraComponent_OnDestroyPhysicsState(this); /// <summary> /// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called. /// </summary> protected override void OnRegister() => E__Supper__UCameraComponent_OnRegister(this); public override void OnRep_IsActive() => E__Supper__UCameraComponent_OnRep_IsActive(this); /// <summary> /// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called. /// </summary> protected override void OnUnregister() => E__Supper__UCameraComponent_OnUnregister(this); /// <summary> /// Virtual call chain to register all tick functions /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterComponentTickFunctions(bool bRegister) => E__Supper__UCameraComponent_RegisterComponentTickFunctions(this, bRegister); /// <summary> /// Called to send dynamic data for this component to the rendering thread /// </summary> protected override void SendRenderDynamicData_Concurrent() => E__Supper__UCameraComponent_SendRenderDynamicData_Concurrent(this); /// <summary> /// Called to send a transform update for this component to the rendering thread /// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para> /// </summary> protected override void SendRenderTransform_Concurrent() => E__Supper__UCameraComponent_SendRenderTransform_Concurrent(this); /// <summary> /// Sets whether the component is active or not /// </summary> /// <param name="bNewActive">The new active state of the component</param> /// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param> public override void SetActive(bool bNewActive, bool bReset) => E__Supper__UCameraComponent_SetActive(this, bNewActive, bReset); /// <summary> /// Sets whether the component should be auto activate or not. Only safe during construction scripts. /// </summary> /// <param name="bNewAutoActivate">The new auto activate state of the component</param> public override void SetAutoActivate(bool bNewAutoActivate) => E__Supper__UCameraComponent_SetAutoActivate(this, bNewAutoActivate); /// <summary> /// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered /// </summary> /// <param name="bEnabled">Whether it should be enabled or not</param> public override void SetComponentTickEnabled(bool bEnabled) => E__Supper__UCameraComponent_SetComponentTickEnabled(this, bEnabled); /// <summary> /// Spawns a task on GameThread that will call SetComponentTickEnabled /// </summary> /// <param name="bEnabled">Whether it should be enabled or not</param> public override void SetComponentTickEnabledAsync(bool bEnabled) => E__Supper__UCameraComponent_SetComponentTickEnabledAsync(this, bEnabled); /// <summary> /// Toggles the active state of the component /// </summary> public override void ToggleActive() => E__Supper__UCameraComponent_ToggleActive(this); /// <summary> /// Handle this component being Uninitialized. /// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para> /// </summary> public override void UninitializeComponent() => E__Supper__UCameraComponent_UninitializeComponent(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__UCameraComponent_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__UCameraComponent_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__UCameraComponent_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__UCameraComponent_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__UCameraComponent_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__UCameraComponent_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__UCameraComponent_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UCameraComponent_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UCameraComponent_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__UCameraComponent_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UCameraComponent_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UCameraComponent_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__UCameraComponent_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UCameraComponent_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__UCameraComponent_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageCameraComponent self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageCameraComponent(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageCameraComponent>(PtrDesc); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Xml.Xsl.Qil; using System.Xml.Xsl.IlGen; using System.ComponentModel; using MS.Internal.Xml.XPath; using System.Runtime.Versioning; namespace System.Xml.Xsl.Runtime { /// <summary> /// XmlQueryRuntime is passed as the first parameter to all generated query methods. /// /// XmlQueryRuntime contains runtime support for generated ILGen queries: /// 1. Stack of output writers (stack handles nested document construction) /// 2. Manages list of all xml types that are used within the query /// 3. Manages list of all atomized names that are used within the query /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class XmlQueryRuntime { // Early-Bound Library Objects private XmlQueryContext _ctxt; private XsltLibrary _xsltLib; private EarlyBoundInfo[] _earlyInfo; private object[] _earlyObjects; // Global variables and parameters private string[] _globalNames; private object[] _globalValues; // Names, prefix mappings, and name filters private XmlNameTable _nameTableQuery; private string[] _atomizedNames; // Names after atomization private XmlNavigatorFilter[] _filters; // Name filters (contain atomized names) private StringPair[][] _prefixMappingsList; // Lists of prefix mappings (used to resolve computed names) // Xml types private XmlQueryType[] _types; // Collations private XmlCollation[] _collations; // Document ordering private DocumentOrderComparer _docOrderCmp; // Indexes private ArrayList[] _indexes; // Output construction private XmlQueryOutput _output; private Stack<XmlQueryOutput> _stkOutput; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately). /// </summary> internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) { Debug.Assert(data != null); string[] names = data.Names; Int32Pair[] filters = data.Filters; WhitespaceRuleLookup wsRules; int i; // Early-Bound Library Objects wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null; _ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules); _xsltLib = null; _earlyInfo = data.EarlyBound; _earlyObjects = (_earlyInfo != null) ? new object[_earlyInfo.Length] : null; // Global variables and parameters _globalNames = data.GlobalNames; _globalValues = (_globalNames != null) ? new object[_globalNames.Length] : null; // Names _nameTableQuery = _ctxt.QueryNameTable; _atomizedNames = null; if (names != null) { // Atomize all names in "nameTableQuery". Use names from the default data source's // name table when possible. XmlNameTable nameTableDefault = _ctxt.DefaultNameTable; _atomizedNames = new string[names.Length]; if (nameTableDefault != _nameTableQuery && nameTableDefault != null) { // Ensure that atomized names from the default data source are added to the // name table used in this query for (i = 0; i < names.Length; i++) { string name = nameTableDefault.Get(names[i]); _atomizedNames[i] = _nameTableQuery.Add(name ?? names[i]); } } else { // Enter names into nametable used in this query for (i = 0; i < names.Length; i++) _atomizedNames[i] = _nameTableQuery.Add(names[i]); } } // Name filters _filters = null; if (filters != null) { // Construct name filters. Each pair of integers in the filters[] array specifies the // (localName, namespaceUri) of the NameFilter to be created. _filters = new XmlNavigatorFilter[filters.Length]; for (i = 0; i < filters.Length; i++) _filters[i] = XmlNavNameFilter.Create(_atomizedNames[filters[i].Left], _atomizedNames[filters[i].Right]); } // Prefix maping lists _prefixMappingsList = data.PrefixMappingsList; // Xml types _types = data.Types; // Xml collations _collations = data.Collations; // Document ordering _docOrderCmp = new DocumentOrderComparer(); // Indexes _indexes = null; // Output construction _stkOutput = new Stack<XmlQueryOutput>(16); _output = new XmlQueryOutput(this, seqWrt); } //----------------------------------------------- // Debugger Utility Methods //----------------------------------------------- /// <summary> /// Return array containing the names of all the global variables and parameters used in this query, in this format: /// {namespace}prefix:local-name /// </summary> public string[] DebugGetGlobalNames() { return _globalNames; } /// <summary> /// Get the value of a global value having the specified name. Always return the global value as a list of XPathItem. /// Return null if there is no global value having the specified name. /// </summary> public IList DebugGetGlobalValue(string name) { for (int idx = 0; idx < _globalNames.Length; idx++) { if (_globalNames[idx] == name) { Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed."); Debug.Assert(_globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios."); return (IList)_globalValues[idx]; } } return null; } /// <summary> /// Set the value of a global value having the specified name. If there is no such value, this method is a no-op. /// </summary> public void DebugSetGlobalValue(string name, object value) { for (int idx = 0; idx < _globalNames.Length; idx++) { if (_globalNames[idx] == name) { Debug.Assert(IsGlobalComputed(idx), "Cannot get the value of a global value until it has been computed."); Debug.Assert(_globalValues[idx] is IList<XPathItem>, "Only debugger should call this method, and all global values should have type item* in debugging scenarios."); // Always convert "value" to a list of XPathItem using the item* converter _globalValues[idx] = (IList<XPathItem>)XmlAnyListConverter.ItemList.ChangeType(value, typeof(XPathItem[]), null); break; } } } /// <summary> /// Convert sequence to it's appropriate XSLT type and return to caller. /// </summary> public object DebugGetXsltValue(IList seq) { if (seq != null && seq.Count == 1) { XPathItem item = seq[0] as XPathItem; if (item != null && !item.IsNode) { return item.TypedValue; } else if (item is RtfNavigator) { return ((RtfNavigator)item).ToNavigator(); } } return seq; } //----------------------------------------------- // Early-Bound Library Objects //----------------------------------------------- internal const BindingFlags EarlyBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; internal const BindingFlags LateBoundFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; /// <summary> /// Return the object that manages external user context information such as data sources, parameters, extension objects, etc. /// </summary> public XmlQueryContext ExternalContext { get { return _ctxt; } } /// <summary> /// Return the object that manages the state needed to implement various Xslt functions. /// </summary> public XsltLibrary XsltFunctions { get { if (_xsltLib == null) { _xsltLib = new XsltLibrary(this); } return _xsltLib; } } /// <summary> /// Get the early-bound extension object identified by "index". If it does not yet exist, create an instance using the /// corresponding ConstructorInfo. /// </summary> public object GetEarlyBoundObject(int index) { object obj; Debug.Assert(_earlyObjects != null && index < _earlyObjects.Length, "Early bound object does not exist"); obj = _earlyObjects[index]; if (obj == null) { // Early-bound object does not yet exist, so create it now obj = _earlyInfo[index].CreateObject(); _earlyObjects[index] = obj; } return obj; } /// <summary> /// Return true if the early bound object identified by "namespaceUri" contains a method that matches "name". /// </summary> public bool EarlyBoundFunctionExists(string name, string namespaceUri) { if (_earlyInfo == null) return false; for (int idx = 0; idx < _earlyInfo.Length; idx++) { if (namespaceUri == _earlyInfo[idx].NamespaceUri) return new XmlExtensionFunction(name, namespaceUri, -1, _earlyInfo[idx].EarlyBoundType, EarlyBoundFlags).CanBind(); } return false; } //----------------------------------------------- // Global variables and parameters //----------------------------------------------- /// <summary> /// Return true if the global value specified by idxValue was previously computed. /// </summary> public bool IsGlobalComputed(int index) { return _globalValues[index] != null; } /// <summary> /// Return the value that is bound to the global variable or parameter specified by idxValue. /// If the value has not yet been computed, then compute it now and store it in this.globalValues. /// </summary> public object GetGlobalValue(int index) { Debug.Assert(IsGlobalComputed(index), "Cannot get the value of a global value until it has been computed."); return _globalValues[index]; } /// <summary> /// Return the value that is bound to the global variable or parameter specified by idxValue. /// If the value has not yet been computed, then compute it now and store it in this.globalValues. /// </summary> public void SetGlobalValue(int index, object value) { Debug.Assert(!IsGlobalComputed(index), "Global value should only be set once."); _globalValues[index] = value; } //----------------------------------------------- // Names, prefix mappings, and name filters //----------------------------------------------- /// <summary> /// Return the name table used to atomize all names used by the query. /// </summary> public XmlNameTable NameTable { get { return _nameTableQuery; } } /// <summary> /// Get the atomized name at the specified index in the array of names. /// </summary> public string GetAtomizedName(int index) { Debug.Assert(_atomizedNames != null); return _atomizedNames[index]; } /// <summary> /// Get the name filter at the specified index in the array of filters. /// </summary> public XmlNavigatorFilter GetNameFilter(int index) { Debug.Assert(_filters != null); return _filters[index]; } /// <summary> /// XPathNodeType.All: Filters all nodes /// XPathNodeType.Attribute: Filters attributes /// XPathNodeType.Namespace: Not allowed /// XPathNodeType.XXX: Filters all nodes *except* those having XPathNodeType.XXX /// </summary> public XmlNavigatorFilter GetTypeFilter(XPathNodeType nodeType) { if (nodeType == XPathNodeType.All) return XmlNavNeverFilter.Create(); if (nodeType == XPathNodeType.Attribute) return XmlNavAttrFilter.Create(); return XmlNavTypeFilter.Create(nodeType); } /// <summary> /// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved, /// then throw an error. Return an XmlQualifiedName. /// </summary> public XmlQualifiedName ParseTagName(string tagName, int indexPrefixMappings) { string prefix, localName, ns; // Parse the tagName as a prefix, localName pair and resolve the prefix ParseTagName(tagName, indexPrefixMappings, out prefix, out localName, out ns); return new XmlQualifiedName(localName, ns); } /// <summary> /// Parse the specified tag name (foo:bar). Return an XmlQualifiedName consisting of the parsed local name /// and the specified namespace. /// </summary> public XmlQualifiedName ParseTagName(string tagName, string ns) { string prefix, localName; // Parse the tagName as a prefix, localName pair ValidateNames.ParseQNameThrow(tagName, out prefix, out localName); return new XmlQualifiedName(localName, ns); } /// <summary> /// Parse the specified tag name (foo:bar) and resolve the resulting prefix. If the prefix cannot be resolved, /// then throw an error. Return the prefix, localName, and namespace URI. /// </summary> internal void ParseTagName(string tagName, int idxPrefixMappings, out string prefix, out string localName, out string ns) { Debug.Assert(_prefixMappingsList != null); // Parse the tagName as a prefix, localName pair ValidateNames.ParseQNameThrow(tagName, out prefix, out localName); // Map the prefix to a namespace URI ns = null; foreach (StringPair pair in _prefixMappingsList[idxPrefixMappings]) { if (prefix == pair.Left) { ns = pair.Right; break; } } // Throw exception if prefix could not be resolved if (ns == null) { // Check for mappings that are always in-scope if (prefix.Length == 0) ns = ""; else if (prefix.Equals("xml")) ns = XmlReservedNs.NsXml; // It is not correct to resolve xmlns prefix in XPath but removing it would be a breaking change. else if (prefix.Equals("xmlns")) ns = XmlReservedNs.NsXmlNs; else throw new XslTransformException(SR.Xslt_InvalidPrefix, prefix); } } /// <summary> /// Return true if the nav1's LocalName and NamespaceURI properties equal nav2's corresponding properties. /// </summary> public bool IsQNameEqual(XPathNavigator n1, XPathNavigator n2) { if ((object)n1.NameTable == (object)n2.NameTable) { // Use atomized comparison return (object)n1.LocalName == (object)n2.LocalName && (object)n1.NamespaceURI == (object)n2.NamespaceURI; } return (n1.LocalName == n2.LocalName) && (n1.NamespaceURI == n2.NamespaceURI); } /// <summary> /// Return true if the specified navigator's LocalName and NamespaceURI properties equal the argument names. /// </summary> public bool IsQNameEqual(XPathNavigator navigator, int indexLocalName, int indexNamespaceUri) { if ((object)navigator.NameTable == (object)_nameTableQuery) { // Use atomized comparison return ((object)GetAtomizedName(indexLocalName) == (object)navigator.LocalName && (object)GetAtomizedName(indexNamespaceUri) == (object)navigator.NamespaceURI); } // Use string comparison return (GetAtomizedName(indexLocalName) == navigator.LocalName) && (GetAtomizedName(indexNamespaceUri) == navigator.NamespaceURI); } //----------------------------------------------- // Xml types //----------------------------------------------- /// <summary> /// Get the array of xml types that are used within this query. /// </summary> internal XmlQueryType[] XmlTypes { get { return _types; } } /// <summary> /// Get the Xml query type at the specified index in the array of types. /// </summary> internal XmlQueryType GetXmlType(int idxType) { Debug.Assert(_types != null); return _types[idxType]; } /// <summary> /// Forward call to ChangeTypeXsltArgument(XmlQueryType, object, Type). /// </summary> public object ChangeTypeXsltArgument(int indexType, object value, Type destinationType) { return ChangeTypeXsltArgument(GetXmlType(indexType), value, destinationType); } /// <summary> /// Convert from the Clr type of "value" to Clr type "destinationType" using V1 Xslt rules. /// These rules include converting any Rtf values to Nodes. /// </summary> internal object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type destinationType) { Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Values passed to ChangeTypeXsltArgument should be in ILGen's default Clr representation."); Debug.Assert(destinationType == XsltConvert.ObjectType || !destinationType.IsAssignableFrom(value.GetType()), "No need to call ChangeTypeXsltArgument since value is already assignable to destinationType " + destinationType); switch (xmlType.TypeCode) { case XmlTypeCode.String: if (destinationType == XsltConvert.DateTimeType) value = XsltConvert.ToDateTime((string)value); break; case XmlTypeCode.Double: if (destinationType != XsltConvert.DoubleType) value = Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); break; case XmlTypeCode.Node: Debug.Assert(xmlType != XmlQueryTypeFactory.Node && xmlType != XmlQueryTypeFactory.NodeS, "Rtf values should have been eliminated by caller."); if (destinationType == XsltConvert.XPathNodeIteratorType) { value = new XPathArrayIterator((IList)value); } else if (destinationType == XsltConvert.XPathNavigatorArrayType) { // Copy sequence to XPathNavigator[] IList<XPathNavigator> seq = (IList<XPathNavigator>)value; XPathNavigator[] navArray = new XPathNavigator[seq.Count]; for (int i = 0; i < seq.Count; i++) navArray[i] = seq[i]; value = navArray; } break; case XmlTypeCode.Item: { // Only typeof(object) is supported as a destination type if (destinationType != XsltConvert.ObjectType) throw new XslTransformException(SR.Xslt_UnsupportedClrType, destinationType.Name); // Convert to default, backwards-compatible representation // 1. NodeSet: System.Xml.XPath.XPathNodeIterator // 2. Rtf: System.Xml.XPath.XPathNavigator // 3. Other: Default V1 representation IList<XPathItem> seq = (IList<XPathItem>)value; if (seq.Count == 1) { XPathItem item = seq[0]; if (item.IsNode) { // Node or Rtf RtfNavigator rtf = item as RtfNavigator; if (rtf != null) value = rtf.ToNavigator(); else value = new XPathArrayIterator((IList)value); } else { // Atomic value value = item.TypedValue; } } else { // Nodeset value = new XPathArrayIterator((IList)value); } break; } } Debug.Assert(destinationType.IsAssignableFrom(value.GetType()), "ChangeType from type " + value.GetType().Name + " to type " + destinationType.Name + " failed"); return value; } /// <summary> /// Forward call to ChangeTypeXsltResult(XmlQueryType, object) /// </summary> public object ChangeTypeXsltResult(int indexType, object value) { return ChangeTypeXsltResult(GetXmlType(indexType), value); } /// <summary> /// Convert from the Clr type of "value" to the default Clr type that ILGen uses to represent the xml type, using /// the conversion rules of the xml type. /// </summary> internal object ChangeTypeXsltResult(XmlQueryType xmlType, object value) { if (value == null) throw new XslTransformException(SR.Xslt_ItemNull, string.Empty); switch (xmlType.TypeCode) { case XmlTypeCode.String: if (value.GetType() == XsltConvert.DateTimeType) value = XsltConvert.ToString((DateTime)value); break; case XmlTypeCode.Double: if (value.GetType() != XsltConvert.DoubleType) value = ((IConvertible)value).ToDouble(null); break; case XmlTypeCode.Node: if (!xmlType.IsSingleton) { XPathArrayIterator iter = value as XPathArrayIterator; // Special-case XPathArrayIterator in order to avoid copies if (iter != null && iter.AsList is XmlQueryNodeSequence) { value = iter.AsList as XmlQueryNodeSequence; } else { // Iterate over list and ensure it only contains nodes XmlQueryNodeSequence seq = new XmlQueryNodeSequence(); IList list = value as IList; if (list != null) { for (int i = 0; i < list.Count; i++) seq.Add(EnsureNavigator(list[i])); } else { foreach (object o in (IEnumerable)value) seq.Add(EnsureNavigator(o)); } value = seq; } // Always sort node-set by document order value = ((XmlQueryNodeSequence)value).DocOrderDistinct(_docOrderCmp); } break; case XmlTypeCode.Item: { Type sourceType = value.GetType(); IXPathNavigable navigable; // If static type is item, then infer type based on dynamic value switch (XsltConvert.InferXsltType(sourceType).TypeCode) { case XmlTypeCode.Boolean: value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Boolean), value)); break; case XmlTypeCode.Double: value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), ((IConvertible)value).ToDouble(null))); break; case XmlTypeCode.String: if (sourceType == XsltConvert.DateTimeType) value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), XsltConvert.ToString((DateTime)value))); else value = new XmlQueryItemSequence(new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), value)); break; case XmlTypeCode.Node: // Support XPathNavigator[] value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value); break; case XmlTypeCode.Item: // Support XPathNodeIterator if (value is XPathNodeIterator) { value = ChangeTypeXsltResult(XmlQueryTypeFactory.NodeS, value); break; } // Support IXPathNavigable and XPathNavigator navigable = value as IXPathNavigable; if (navigable != null) { if (value is XPathNavigator) value = new XmlQueryNodeSequence((XPathNavigator)value); else value = new XmlQueryNodeSequence(navigable.CreateNavigator()); break; } throw new XslTransformException(SR.Xslt_UnsupportedClrType, sourceType.Name); } break; } } Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Xml type " + xmlType + " is not represented in ILGen as " + value.GetType().Name); return value; } /// <summary> /// Ensure that "value" is a navigator and not null. /// </summary> private static XPathNavigator EnsureNavigator(object value) { XPathNavigator nav = value as XPathNavigator; if (nav == null) throw new XslTransformException(SR.Xslt_ItemNull, string.Empty); return nav; } /// <summary> /// Return true if the type of every item in "seq" matches the xml type identified by "idxType". /// </summary> public bool MatchesXmlType(IList<XPathItem> seq, int indexType) { XmlQueryType typBase = GetXmlType(indexType); XmlQueryCardinality card; switch (seq.Count) { case 0: card = XmlQueryCardinality.Zero; break; case 1: card = XmlQueryCardinality.One; break; default: card = XmlQueryCardinality.More; break; } if (!(card <= typBase.Cardinality)) return false; typBase = typBase.Prime; for (int i = 0; i < seq.Count; i++) { if (!CreateXmlType(seq[0]).IsSubtypeOf(typBase)) return false; } return true; } /// <summary> /// Return true if the type of "item" matches the xml type identified by "idxType". /// </summary> public bool MatchesXmlType(XPathItem item, int indexType) { return CreateXmlType(item).IsSubtypeOf(GetXmlType(indexType)); } /// <summary> /// Return true if the type of "seq" is a subtype of a singleton type identified by "code". /// </summary> public bool MatchesXmlType(IList<XPathItem> seq, XmlTypeCode code) { if (seq.Count != 1) return false; return MatchesXmlType(seq[0], code); } /// <summary> /// Return true if the type of "item" is a subtype of the type identified by "code". /// </summary> public bool MatchesXmlType(XPathItem item, XmlTypeCode code) { // All atomic type codes appear after AnyAtomicType if (code > XmlTypeCode.AnyAtomicType) return !item.IsNode && item.XmlType.TypeCode == code; // Handle node code and AnyAtomicType switch (code) { case XmlTypeCode.AnyAtomicType: return !item.IsNode; case XmlTypeCode.Node: return item.IsNode; case XmlTypeCode.Item: return true; default: if (!item.IsNode) return false; switch (((XPathNavigator)item).NodeType) { case XPathNodeType.Root: return code == XmlTypeCode.Document; case XPathNodeType.Element: return code == XmlTypeCode.Element; case XPathNodeType.Attribute: return code == XmlTypeCode.Attribute; case XPathNodeType.Namespace: return code == XmlTypeCode.Namespace; case XPathNodeType.Text: return code == XmlTypeCode.Text; case XPathNodeType.SignificantWhitespace: return code == XmlTypeCode.Text; case XPathNodeType.Whitespace: return code == XmlTypeCode.Text; case XPathNodeType.ProcessingInstruction: return code == XmlTypeCode.ProcessingInstruction; case XPathNodeType.Comment: return code == XmlTypeCode.Comment; } break; } Debug.Fail("XmlTypeCode " + code + " was not fully handled."); return false; } /// <summary> /// Create an XmlQueryType that represents the type of "item". /// </summary> private XmlQueryType CreateXmlType(XPathItem item) { if (item.IsNode) { // Rtf RtfNavigator rtf = item as RtfNavigator; if (rtf != null) return XmlQueryTypeFactory.Node; // Node XPathNavigator nav = (XPathNavigator)item; switch (nav.NodeType) { case XPathNodeType.Root: case XPathNodeType.Element: if (nav.XmlType == null) return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), XmlSchemaComplexType.UntypedAnyType, false); return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, nav.SchemaInfo.SchemaElement.IsNillable); case XPathNodeType.Attribute: if (nav.XmlType == null) return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), DatatypeImplementation.UntypedAtomicType, false); return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.New(nav.LocalName, nav.NamespaceURI), nav.XmlType, false); } return XmlQueryTypeFactory.Type(nav.NodeType, XmlQualifiedNameTest.Wildcard, XmlSchemaComplexType.AnyType, false); } // Atomic value return XmlQueryTypeFactory.Type((XmlSchemaSimpleType)item.XmlType, true); } //----------------------------------------------- // Xml collations //----------------------------------------------- /// <summary> /// Get a collation that was statically created. /// </summary> public XmlCollation GetCollation(int index) { Debug.Assert(_collations != null); return _collations[index]; } /// <summary> /// Create a collation from a string. /// </summary> public XmlCollation CreateCollation(string collation) { return XmlCollation.Create(collation); } //----------------------------------------------- // Document Ordering and Identity //----------------------------------------------- /// <summary> /// Compare the relative positions of two navigators. Return -1 if navThis is before navThat, 1 if after, and /// 0 if they are positioned to the same node. /// </summary> public int ComparePosition(XPathNavigator navigatorThis, XPathNavigator navigatorThat) { return _docOrderCmp.Compare(navigatorThis, navigatorThat); } /// <summary> /// Get a comparer which guarantees a stable ordering among nodes, even those from different documents. /// </summary> public IList<XPathNavigator> DocOrderDistinct(IList<XPathNavigator> seq) { if (seq.Count <= 1) return seq; XmlQueryNodeSequence nodeSeq = (XmlQueryNodeSequence)seq; if (nodeSeq == null) nodeSeq = new XmlQueryNodeSequence(seq); return nodeSeq.DocOrderDistinct(_docOrderCmp); } /// <summary> /// Generate a unique string identifier for the specified node. Do this by asking the navigator for an identifier /// that is unique within the document, and then prepend a document index. /// </summary> public string GenerateId(XPathNavigator navigator) { return string.Concat("ID", _docOrderCmp.GetDocumentIndex(navigator).ToString(CultureInfo.InvariantCulture), navigator.UniqueId); } //----------------------------------------------- // Indexes //----------------------------------------------- /// <summary> /// If an index having the specified Id has already been created over the "context" document, then return it /// in "index" and return true. Otherwise, create a new, empty index and return false. /// </summary> public bool FindIndex(XPathNavigator context, int indexId, out XmlILIndex index) { XPathNavigator navRoot; ArrayList docIndexes; Debug.Assert(context != null); // Get root of document navRoot = context.Clone(); navRoot.MoveToRoot(); // Search pre-existing indexes in order to determine whether the specified index has already been created if (_indexes != null && indexId < _indexes.Length) { docIndexes = (ArrayList)_indexes[indexId]; if (docIndexes != null) { // Search for an index defined over the specified document for (int i = 0; i < docIndexes.Count; i += 2) { // If we find a matching document, then return the index saved in the next slot if (((XPathNavigator)docIndexes[i]).IsSamePosition(navRoot)) { index = (XmlILIndex)docIndexes[i + 1]; return true; } } } } // Return a new, empty index index = new XmlILIndex(); return false; } /// <summary> /// Add a newly built index over the specified "context" document to the existing collection of indexes. /// </summary> public void AddNewIndex(XPathNavigator context, int indexId, XmlILIndex index) { XPathNavigator navRoot; ArrayList docIndexes; Debug.Assert(context != null); // Get root of document navRoot = context.Clone(); navRoot.MoveToRoot(); // Ensure that a slot exists for the new index if (_indexes == null) { _indexes = new ArrayList[indexId + 4]; } else if (indexId >= _indexes.Length) { // Resize array ArrayList[] indexesNew = new ArrayList[indexId + 4]; Array.Copy(_indexes, 0, indexesNew, 0, _indexes.Length); _indexes = indexesNew; } docIndexes = (ArrayList)_indexes[indexId]; if (docIndexes == null) { docIndexes = new ArrayList(); _indexes[indexId] = docIndexes; } docIndexes.Add(navRoot); docIndexes.Add(index); } //----------------------------------------------- // Output construction //----------------------------------------------- /// <summary> /// Get output writer object. /// </summary> public XmlQueryOutput Output { get { return _output; } } /// <summary> /// Start construction of a nested sequence of items. Return a new XmlQueryOutput that will be /// used to construct this new sequence. /// </summary> public void StartSequenceConstruction(out XmlQueryOutput output) { // Push current writer _stkOutput.Push(_output); // Create new writers output = _output = new XmlQueryOutput(this, new XmlCachedSequenceWriter()); } /// <summary> /// End construction of a nested sequence of items and return the items as an IList<XPathItem> /// internal class. Return previous XmlQueryOutput. /// </summary> public IList<XPathItem> EndSequenceConstruction(out XmlQueryOutput output) { IList<XPathItem> seq = ((XmlCachedSequenceWriter)_output.SequenceWriter).ResultSequence; // Restore previous XmlQueryOutput output = _output = _stkOutput.Pop(); return seq; } /// <summary> /// Start construction of an Rtf. Return a new XmlQueryOutput object that will be used to construct this Rtf. /// </summary> public void StartRtfConstruction(string baseUri, out XmlQueryOutput output) { // Push current writer _stkOutput.Push(_output); // Create new XmlQueryOutput over an Rtf writer output = _output = new XmlQueryOutput(this, new XmlEventCache(baseUri, true)); } /// <summary> /// End construction of an Rtf and return it as an RtfNavigator. Return previous XmlQueryOutput object. /// </summary> public XPathNavigator EndRtfConstruction(out XmlQueryOutput output) { XmlEventCache events; events = (XmlEventCache)_output.Writer; // Restore previous XmlQueryOutput output = _output = _stkOutput.Pop(); // Return Rtf as an RtfNavigator events.EndEvents(); return new RtfTreeNavigator(events, _nameTableQuery); } /// <summary> /// Construct a new RtfTextNavigator from the specified "text". This is much more efficient than calling /// StartNodeConstruction(), StartRtf(), WriteString(), EndRtf(), and EndNodeConstruction(). /// </summary> public XPathNavigator TextRtfConstruction(string text, string baseUri) { return new RtfTextNavigator(text, baseUri); } //----------------------------------------------- // Miscellaneous //----------------------------------------------- /// <summary> /// Report query execution information to event handler. /// </summary> public void SendMessage(string message) { _ctxt.OnXsltMessageEncountered(message); } /// <summary> /// Throw an Xml exception having the specified message text. /// </summary> public void ThrowException(string text) { throw new XslTransformException(text); } /// <summary> /// Position navThis to the same location as navThat. /// </summary> internal static XPathNavigator SyncToNavigator(XPathNavigator navigatorThis, XPathNavigator navigatorThat) { if (navigatorThis == null || !navigatorThis.MoveTo(navigatorThat)) return navigatorThat.Clone(); return navigatorThis; } /// <summary> /// Function is called in Debug mode on each time context node change. /// </summary> public static int OnCurrentNodeChanged(XPathNavigator currentNode) { IXmlLineInfo lineInfo = currentNode as IXmlLineInfo; // In case of a namespace node, check whether it is inherited or locally defined if (lineInfo != null && !(currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode))) { OnCurrentNodeChanged2(currentNode.BaseURI, lineInfo.LineNumber, lineInfo.LinePosition); } return 0; } // 'true' if current Namespace "inherited" from it's parent. Not defined locally. private static bool IsInheritedNamespace(XPathNavigator node) { Debug.Assert(node.NodeType == XPathNodeType.Namespace); XPathNavigator nav = node.Clone(); if (nav.MoveToParent()) { if (nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) { do { if ((object)nav.LocalName == (object)node.LocalName) { return false; } } while (nav.MoveToNextNamespace(XPathNamespaceScope.Local)); } } return true; } private static void OnCurrentNodeChanged2(string baseUri, int lineNumber, int linePosition) { } } }
// 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.ServiceModel.Description; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Reflection; using Microsoft.Xml; using System.ServiceModel.Diagnostics; using System.ServiceModel.Channels; using System.Runtime.Diagnostics; using System.Runtime; using System.Threading.Tasks; namespace System.ServiceModel.Dispatcher { internal abstract class OperationFormatter : IClientMessageFormatter, IDispatchMessageFormatter { private MessageDescription _replyDescription; private MessageDescription _requestDescription; private XmlDictionaryString _action; private XmlDictionaryString _replyAction; protected StreamFormatter requestStreamFormatter, replyStreamFormatter; private XmlDictionary _dictionary; private string _operationName; public OperationFormatter(OperationDescription description, bool isRpc, bool isEncoded) { Validate(description, isRpc, isEncoded); _requestDescription = description.Messages[0]; if (description.Messages.Count == 2) _replyDescription = description.Messages[1]; int stringCount = 3 + _requestDescription.Body.Parts.Count; if (_replyDescription != null) stringCount += 2 + _replyDescription.Body.Parts.Count; _dictionary = new XmlDictionary(stringCount * 2); GetActions(description, _dictionary, out _action, out _replyAction); _operationName = description.Name; requestStreamFormatter = StreamFormatter.Create(_requestDescription, _operationName, true/*isRequest*/); if (_replyDescription != null) replyStreamFormatter = StreamFormatter.Create(_replyDescription, _operationName, false/*isResponse*/); } protected abstract void AddHeadersToMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest); protected abstract void SerializeBody(XmlDictionaryWriter writer, MessageVersion version, string action, MessageDescription messageDescription, object returnValue, object[] parameters, bool isRequest); protected virtual Task SerializeBodyAsync(XmlDictionaryWriter writer, MessageVersion version, string action, MessageDescription messageDescription, object returnValue, object[] parameters, bool isRequest) { SerializeBody(writer, version, action, messageDescription, returnValue, parameters, isRequest); return Task.CompletedTask; } protected abstract void GetHeadersFromMessage(Message message, MessageDescription messageDescription, object[] parameters, bool isRequest); protected abstract object DeserializeBody(XmlDictionaryReader reader, MessageVersion version, string action, MessageDescription messageDescription, object[] parameters, bool isRequest); protected virtual void WriteBodyAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { } internal string RequestAction { get { if (_action != null) return _action.Value; return null; } } internal string ReplyAction { get { if (_replyAction != null) return _replyAction.Value; return null; } } protected XmlDictionary Dictionary { get { return _dictionary; } } protected string OperationName { get { return _operationName; } } protected MessageDescription ReplyDescription { get { return _replyDescription; } } protected MessageDescription RequestDescription { get { return _requestDescription; } } protected XmlDictionaryString AddToDictionary(string s) { return AddToDictionary(_dictionary, s); } public object DeserializeReply(Message message, object[] parameters) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); if (parameters == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message); try { object result = null; if (_replyDescription.IsTypedMessage) { object typeMessageInstance = CreateTypedMessageInstance(_replyDescription.MessageType); TypedMessageParts typedMessageParts = new TypedMessageParts(typeMessageInstance, _replyDescription); object[] parts = new object[typedMessageParts.Count]; GetPropertiesFromMessage(message, _replyDescription, parts); GetHeadersFromMessage(message, _replyDescription, parts, false/*isRequest*/); DeserializeBodyContents(message, parts, false/*isRequest*/); // copy values into the actual field/properties typedMessageParts.SetTypedMessageParts(parts); result = typeMessageInstance; } else { GetPropertiesFromMessage(message, _replyDescription, parameters); GetHeadersFromMessage(message, _replyDescription, parameters, false/*isRequest*/); result = DeserializeBodyContents(message, parameters, false/*isRequest*/); } return result; } catch (XmlException xe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( string.Format(SRServiceModel.SFxErrorDeserializingReplyBodyMore, _operationName, xe.Message), xe)); } catch (FormatException fe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( string.Format(SRServiceModel.SFxErrorDeserializingReplyBodyMore, _operationName, fe.Message), fe)); } catch (SerializationException se) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( string.Format(SRServiceModel.SFxErrorDeserializingReplyBodyMore, _operationName, se.Message), se)); } } private static object CreateTypedMessageInstance(Type messageContractType) { try { object typeMessageInstance = Activator.CreateInstance(messageContractType); return typeMessageInstance; } catch (MissingMethodException mme) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxMessageContractRequiresDefaultConstructor, messageContractType.FullName), mme)); } } public void DeserializeRequest(Message message, object[] parameters) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); if (parameters == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("parameters"), message); try { if (_requestDescription.IsTypedMessage) { object typeMessageInstance = CreateTypedMessageInstance(_requestDescription.MessageType); TypedMessageParts typedMessageParts = new TypedMessageParts(typeMessageInstance, _requestDescription); object[] parts = new object[typedMessageParts.Count]; GetPropertiesFromMessage(message, _requestDescription, parts); GetHeadersFromMessage(message, _requestDescription, parts, true/*isRequest*/); DeserializeBodyContents(message, parts, true/*isRequest*/); // copy values into the actual field/properties typedMessageParts.SetTypedMessageParts(parts); parameters[0] = typeMessageInstance; } else { GetPropertiesFromMessage(message, _requestDescription, parameters); GetHeadersFromMessage(message, _requestDescription, parameters, true/*isRequest*/); DeserializeBodyContents(message, parameters, true/*isRequest*/); } } catch (XmlException xe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( OperationFormatter.CreateDeserializationFailedFault( string.Format(SRServiceModel.SFxErrorDeserializingRequestBodyMore, _operationName, xe.Message), xe)); } catch (FormatException fe) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( OperationFormatter.CreateDeserializationFailedFault( string.Format(SRServiceModel.SFxErrorDeserializingRequestBodyMore, _operationName, fe.Message), fe)); } catch (SerializationException se) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException( string.Format(SRServiceModel.SFxErrorDeserializingRequestBodyMore, _operationName, se.Message), se)); } } private object DeserializeBodyContents(Message message, object[] parameters, bool isRequest) { MessageDescription messageDescription; StreamFormatter streamFormatter; SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { object retVal = null; streamFormatter.Deserialize(parameters, ref retVal, message); return retVal; } if (message.IsEmpty) { return null; } else { XmlDictionaryReader reader = message.GetReaderAtBodyContents(); using (reader) { object body = DeserializeBody(reader, message.Version, RequestAction, messageDescription, parameters, isRequest); message.ReadFromBodyContentsToEnd(reader); return body; } } } public Message SerializeRequest(MessageVersion messageVersion, object[] parameters) { object[] parts = null; if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters"); if (_requestDescription.IsTypedMessage) { TypedMessageParts typedMessageParts = new TypedMessageParts(parameters[0], _requestDescription); // copy values from the actual field/properties parts = new object[typedMessageParts.Count]; typedMessageParts.GetTypedMessageParts(parts); } else { parts = parameters; } Message msg = new OperationFormatterMessage(this, messageVersion, _action == null ? null : ActionHeader.Create(_action, messageVersion.Addressing), parts, null, true/*isRequest*/); AddPropertiesToMessage(msg, _requestDescription, parts); AddHeadersToMessage(msg, _requestDescription, parts, true /*isRequest*/); return msg; } public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { object[] parts = null; object resultPart = null; if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (parameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters"); if (_replyDescription.IsTypedMessage) { // If the response is a typed message then it must // be the response (as opposed to an out param). We will // serialize the response in the exact same way that we // would serialize a bunch of outs (with no return value). TypedMessageParts typedMessageParts = new TypedMessageParts(result, _replyDescription); // make a copy of the list so that we have the actual values of the field/properties parts = new object[typedMessageParts.Count]; typedMessageParts.GetTypedMessageParts(parts); } else { parts = parameters; resultPart = result; } Message msg = new OperationFormatterMessage(this, messageVersion, _replyAction == null ? null : ActionHeader.Create(_replyAction, messageVersion.Addressing), parts, resultPart, false/*isRequest*/); AddPropertiesToMessage(msg, _replyDescription, parts); AddHeadersToMessage(msg, _replyDescription, parts, false /*isRequest*/); return msg; } private void SetupStreamAndMessageDescription(bool isRequest, out StreamFormatter streamFormatter, out MessageDescription messageDescription) { if (isRequest) { streamFormatter = requestStreamFormatter; messageDescription = _requestDescription; } else { streamFormatter = replyStreamFormatter; messageDescription = _replyDescription; } } private void SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest) { MessageDescription messageDescription; StreamFormatter streamFormatter; SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { streamFormatter.Serialize(writer, parameters, returnValue); return; } SerializeBody(writer, version, RequestAction, messageDescription, returnValue, parameters, isRequest); } private async Task SerializeBodyContentsAsync(XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest) { MessageDescription messageDescription; StreamFormatter streamFormatter; SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { streamFormatter.Serialize(writer, parameters, returnValue); return; } await SerializeBodyAsync(writer, version, RequestAction, messageDescription, returnValue, parameters, isRequest); } private IAsyncResult BeginSerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest, AsyncCallback callback, object state) { return new SerializeBodyContentsAsyncResult(this, writer, version, parameters, returnValue, isRequest, callback, state); } private void EndSerializeBodyContents(IAsyncResult result) { SerializeBodyContentsAsyncResult.End(result); } internal class SerializeBodyContentsAsyncResult : AsyncResult { private static AsyncCompletion s_handleEndSerializeBodyContents = new AsyncCompletion(HandleEndSerializeBodyContents); private StreamFormatter _streamFormatter; internal SerializeBodyContentsAsyncResult(OperationFormatter operationFormatter, XmlDictionaryWriter writer, MessageVersion version, object[] parameters, object returnValue, bool isRequest, AsyncCallback callback, object state) : base(callback, state) { bool completeSelf = true; MessageDescription messageDescription; StreamFormatter streamFormatter; operationFormatter.SetupStreamAndMessageDescription(isRequest, out streamFormatter, out messageDescription); if (streamFormatter != null) { _streamFormatter = streamFormatter; IAsyncResult result = streamFormatter.BeginSerialize(writer, parameters, returnValue, PrepareAsyncCompletion(s_handleEndSerializeBodyContents), this); completeSelf = SyncContinue(result); } else { operationFormatter.SerializeBody(writer, version, operationFormatter.RequestAction, messageDescription, returnValue, parameters, isRequest); completeSelf = true; } if (completeSelf) { Complete(true); } } private static bool HandleEndSerializeBodyContents(IAsyncResult result) { SerializeBodyContentsAsyncResult thisPtr = (SerializeBodyContentsAsyncResult)result.AsyncState; thisPtr._streamFormatter.EndSerialize(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End<SerializeBodyContentsAsyncResult>(result); } } private void AddPropertiesToMessage(Message message, MessageDescription messageDescription, object[] parameters) { if (messageDescription.Properties.Count > 0) { AddPropertiesToMessageCore(message, messageDescription, parameters); } } private void AddPropertiesToMessageCore(Message message, MessageDescription messageDescription, object[] parameters) { MessageProperties properties = message.Properties; MessagePropertyDescriptionCollection propertyDescriptions = messageDescription.Properties; for (int i = 0; i < propertyDescriptions.Count; i++) { MessagePropertyDescription propertyDescription = propertyDescriptions[i]; object parameter = parameters[propertyDescription.Index]; if (null != parameter) properties.Add(propertyDescription.Name, parameter); } } private void GetPropertiesFromMessage(Message message, MessageDescription messageDescription, object[] parameters) { if (messageDescription.Properties.Count > 0) { GetPropertiesFromMessageCore(message, messageDescription, parameters); } } private void GetPropertiesFromMessageCore(Message message, MessageDescription messageDescription, object[] parameters) { MessageProperties properties = message.Properties; MessagePropertyDescriptionCollection propertyDescriptions = messageDescription.Properties; for (int i = 0; i < propertyDescriptions.Count; i++) { MessagePropertyDescription propertyDescription = propertyDescriptions[i]; if (properties.ContainsKey(propertyDescription.Name)) { parameters[propertyDescription.Index] = properties[propertyDescription.Name]; } } } internal static object GetContentOfMessageHeaderOfT(MessageHeaderDescription headerDescription, object parameterValue, out bool mustUnderstand, out bool relay, out string actor) { actor = headerDescription.Actor; mustUnderstand = headerDescription.MustUnderstand; relay = headerDescription.Relay; if (headerDescription.TypedHeader && parameterValue != null) parameterValue = TypedHeaderManager.GetContent(headerDescription.Type, parameterValue, out mustUnderstand, out relay, out actor); return parameterValue; } internal static bool IsValidReturnValue(MessagePartDescription returnValue) { return (returnValue != null) && (returnValue.Type != typeof(void)); } internal static XmlDictionaryString AddToDictionary(XmlDictionary dictionary, string s) { XmlDictionaryString dictionaryString; if (!dictionary.TryLookup(s, out dictionaryString)) { dictionaryString = dictionary.Add(s); } return dictionaryString; } internal static void Validate(OperationDescription operation, bool isRpc, bool isEncoded) { if (isEncoded && !isRpc) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxDocEncodedNotSupported, operation.Name))); } bool hasVoid = false; bool hasTypedOrUntypedMessage = false; bool hasParameter = false; for (int i = 0; i < operation.Messages.Count; i++) { MessageDescription message = operation.Messages[i]; if (message.IsTypedMessage || message.IsUntypedMessage) { if (isRpc && operation.IsValidateRpcWrapperName) { if (!isEncoded) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxTypedMessageCannotBeRpcLiteral, operation.Name))); } hasTypedOrUntypedMessage = true; } else if (message.IsVoid) hasVoid = true; else hasParameter = true; } if (hasParameter && hasTypedOrUntypedMessage) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxTypedOrUntypedMessageCannotBeMixedWithParameters, operation.Name))); if (isRpc && hasTypedOrUntypedMessage && hasVoid) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SFxTypedOrUntypedMessageCannotBeMixedWithVoidInRpc, operation.Name))); } internal static void GetActions(OperationDescription description, XmlDictionary dictionary, out XmlDictionaryString action, out XmlDictionaryString replyAction) { string actionString, replyActionString; actionString = description.Messages[0].Action; if (actionString == MessageHeaders.WildcardAction) actionString = null; if (!description.IsOneWay) replyActionString = description.Messages[1].Action; else replyActionString = null; if (replyActionString == MessageHeaders.WildcardAction) replyActionString = null; action = replyAction = null; if (actionString != null) action = AddToDictionary(dictionary, actionString); if (replyActionString != null) replyAction = AddToDictionary(dictionary, replyActionString); } internal static NetDispatcherFaultException CreateDeserializationFailedFault(string reason, Exception innerException) { reason = string.Format(SRServiceModel.SFxDeserializationFailed1, reason); FaultCode code = new FaultCode(FaultCodeConstants.Codes.DeserializationFailed, FaultCodeConstants.Namespaces.NetDispatch); code = FaultCode.CreateSenderFaultCode(code); return new NetDispatcherFaultException(reason, code, innerException); } internal static void TraceAndSkipElement(XmlReader xmlReader) { xmlReader.Skip(); } internal class TypedMessageParts { private object _instance; private MemberInfo[] _members; public TypedMessageParts(object instance, MessageDescription description) { if (description == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("description")); } if (instance == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(string.Format(SRServiceModel.SFxTypedMessageCannotBeNull, description.Action))); } _members = new MemberInfo[description.Body.Parts.Count + description.Properties.Count + description.Headers.Count]; foreach (MessagePartDescription part in description.Headers) _members[part.Index] = part.MemberInfo; foreach (MessagePartDescription part in description.Properties) _members[part.Index] = part.MemberInfo; foreach (MessagePartDescription part in description.Body.Parts) _members[part.Index] = part.MemberInfo; _instance = instance; } private object GetValue(int index) { MemberInfo memberInfo = _members[index]; PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { return propertyInfo.GetValue(_instance, null); } else { return ((FieldInfo)memberInfo).GetValue(_instance); } } private void SetValue(object value, int index) { MemberInfo memberInfo = _members[index]; PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null) { propertyInfo.SetValue(_instance, value, null); } else { ((FieldInfo)memberInfo).SetValue(_instance, value); } } internal void GetTypedMessageParts(object[] values) { for (int i = 0; i < _members.Length; i++) { values[i] = GetValue(i); } } internal void SetTypedMessageParts(object[] values) { for (int i = 0; i < _members.Length; i++) { SetValue(values[i], i); } } internal int Count { get { return _members.Length; } } } internal class OperationFormatterMessage : BodyWriterMessage { private OperationFormatter _operationFormatter; public OperationFormatterMessage(OperationFormatter operationFormatter, MessageVersion version, ActionHeader action, object[] parameters, object returnValue, bool isRequest) : base(version, action, new OperationFormatterBodyWriter(operationFormatter, version, parameters, returnValue, isRequest)) { _operationFormatter = operationFormatter; } public OperationFormatterMessage(MessageVersion version, string action, BodyWriter bodyWriter) : base(version, action, bodyWriter) { } private OperationFormatterMessage(MessageHeaders headers, KeyValuePair<string, object>[] properties, OperationFormatterBodyWriter bodyWriter) : base(headers, properties, bodyWriter) { _operationFormatter = bodyWriter.OperationFormatter; } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { base.OnWriteStartBody(writer); _operationFormatter.WriteBodyAttributes(writer, this.Version); } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { BodyWriter bufferedBodyWriter; if (BodyWriter.IsBuffered) { bufferedBodyWriter = base.BodyWriter; } else { bufferedBodyWriter = base.BodyWriter.CreateBufferedCopy(maxBufferSize); } KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[base.Properties.Count]; ((ICollection<KeyValuePair<string, object>>)base.Properties).CopyTo(properties, 0); return new OperationFormatterMessageBuffer(base.Headers, properties, bufferedBodyWriter); } internal class OperationFormatterBodyWriter : BodyWriter { private bool _isRequest; private OperationFormatter _operationFormatter; private object[] _parameters; private object _returnValue; private MessageVersion _version; private bool _onBeginWriteBodyContentsCalled; public OperationFormatterBodyWriter(OperationFormatter operationFormatter, MessageVersion version, object[] parameters, object returnValue, bool isRequest) : base(AreParametersBuffered(isRequest, operationFormatter)) { _parameters = parameters; _returnValue = returnValue; _isRequest = isRequest; _operationFormatter = operationFormatter; _version = version; } private object ThisLock { get { return this; } } private static bool AreParametersBuffered(bool isRequest, OperationFormatter operationFormatter) { StreamFormatter streamFormatter = isRequest ? operationFormatter.requestStreamFormatter : operationFormatter.replyStreamFormatter; return streamFormatter == null; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { lock (ThisLock) { _operationFormatter.SerializeBodyContents(writer, _version, _parameters, _returnValue, _isRequest); } } protected override Task OnWriteBodyContentsAsync(XmlDictionaryWriter writer) { return _operationFormatter.SerializeBodyContentsAsync(writer, _version, _parameters, _returnValue, _isRequest); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { Fx.Assert(!_onBeginWriteBodyContentsCalled, "OnBeginWriteBodyContents has already been called"); _onBeginWriteBodyContentsCalled = true; return new OnWriteBodyContentsAsyncResult(this, writer, callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { OnWriteBodyContentsAsyncResult.End(result); } internal OperationFormatter OperationFormatter { get { return _operationFormatter; } } internal class OnWriteBodyContentsAsyncResult : AsyncResult { private static AsyncCompletion s_handleEndOnWriteBodyContents = new AsyncCompletion(HandleEndOnWriteBodyContents); private OperationFormatter _operationFormatter; internal OnWriteBodyContentsAsyncResult(OperationFormatterBodyWriter operationFormatterBodyWriter, XmlDictionaryWriter writer, AsyncCallback callback, object state) : base(callback, state) { bool completeSelf = true; _operationFormatter = operationFormatterBodyWriter.OperationFormatter; IAsyncResult result = _operationFormatter.BeginSerializeBodyContents(writer, operationFormatterBodyWriter._version, operationFormatterBodyWriter._parameters, operationFormatterBodyWriter._returnValue, operationFormatterBodyWriter._isRequest, PrepareAsyncCompletion(s_handleEndOnWriteBodyContents), this); completeSelf = SyncContinue(result); if (completeSelf) { Complete(true); } } private static bool HandleEndOnWriteBodyContents(IAsyncResult result) { OnWriteBodyContentsAsyncResult thisPtr = (OnWriteBodyContentsAsyncResult)result.AsyncState; thisPtr._operationFormatter.EndSerializeBodyContents(result); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OnWriteBodyContentsAsyncResult>(result); } } } private class OperationFormatterMessageBuffer : BodyWriterMessageBuffer { public OperationFormatterMessageBuffer(MessageHeaders headers, KeyValuePair<string, object>[] properties, BodyWriter bodyWriter) : base(headers, properties, bodyWriter) { } public override Message CreateMessage() { OperationFormatterBodyWriter operationFormatterBodyWriter = base.BodyWriter as OperationFormatterBodyWriter; if (operationFormatterBodyWriter == null) return base.CreateMessage(); lock (ThisLock) { if (base.Closed) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException()); return new OperationFormatterMessage(base.Headers, base.Properties, operationFormatterBodyWriter); } } } } internal abstract class OperationFormatterHeader : MessageHeader { protected MessageHeader innerHeader; //use innerHeader to handle versionSupported, actor/role handling etc. protected OperationFormatter operationFormatter; protected MessageVersion version; public OperationFormatterHeader(OperationFormatter operationFormatter, MessageVersion version, string name, string ns, bool mustUnderstand, string actor, bool relay) { this.operationFormatter = operationFormatter; this.version = version; if (actor != null) innerHeader = MessageHeader.CreateHeader(name, ns, null/*headerValue*/, mustUnderstand, actor, relay); else innerHeader = MessageHeader.CreateHeader(name, ns, null/*headerValue*/, mustUnderstand, "", relay); } public override bool IsMessageVersionSupported(MessageVersion messageVersion) { return innerHeader.IsMessageVersionSupported(messageVersion); } public override string Name { get { return innerHeader.Name; } } public override string Namespace { get { return innerHeader.Namespace; } } public override bool MustUnderstand { get { return innerHeader.MustUnderstand; } } public override bool Relay { get { return innerHeader.Relay; } } public override string Actor { get { return innerHeader.Actor; } } protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { //Prefix needed since there may be xsi:type attribute at toplevel with qname value where ns = "" writer.WriteStartElement((this.Namespace == null || this.Namespace.Length == 0) ? string.Empty : "h", this.Name, this.Namespace); OnWriteHeaderAttributes(writer, messageVersion); } protected virtual void OnWriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { base.WriteHeaderAttributes(writer, messageVersion); } } internal class XmlElementMessageHeader : OperationFormatterHeader { protected XmlElement headerValue; public XmlElementMessageHeader(OperationFormatter operationFormatter, MessageVersion version, string name, string ns, bool mustUnderstand, string actor, bool relay, XmlElement headerValue) : base(operationFormatter, version, name, ns, mustUnderstand, actor, relay) { this.headerValue = headerValue; } protected override void OnWriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { throw ExceptionHelper.PlatformNotSupported(); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { headerValue.WriteContentTo(writer); } } internal struct QName { internal string Name; internal string Namespace; internal QName(string name, string ns) { Name = name; Namespace = ns; } } internal class QNameComparer : IEqualityComparer<QName> { static internal QNameComparer Singleton = new QNameComparer(); private QNameComparer() { } public bool Equals(QName x, QName y) { return x.Name == y.Name && x.Namespace == y.Namespace; } public int GetHashCode(QName obj) { return obj.Name.GetHashCode(); } } internal class MessageHeaderDescriptionTable : Dictionary<QName, MessageHeaderDescription> { internal MessageHeaderDescriptionTable() : base(QNameComparer.Singleton) { } internal void Add(string name, string ns, MessageHeaderDescription message) { base.Add(new QName(name, ns), message); } internal MessageHeaderDescription Get(string name, string ns) { MessageHeaderDescription message; if (base.TryGetValue(new QName(name, ns), out message)) return message; return null; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the machinelearning-2014-12-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MachineLearning.Model { /// <summary> /// Container for the parameters to the DescribeDataSources operation. /// Returns a list of <code>DataSource</code> that match the search criteria in the request. /// </summary> public partial class DescribeDataSourcesRequest : AmazonMachineLearningRequest { private string _eq; private DataSourceFilterVariable _filterVariable; private string _ge; private string _gt; private string _le; private int? _limit; private string _lt; private string _ne; private string _nextToken; private string _prefix; private SortOrder _sortOrder; /// <summary> /// Gets and sets the property EQ. /// <para> /// The equal to operator. The <code>DataSource</code> results will have <code>FilterVariable</code> /// values that exactly match the value specified with <code>EQ</code>. /// </para> /// </summary> public string EQ { get { return this._eq; } set { this._eq = value; } } // Check to see if EQ property is set internal bool IsSetEQ() { return this._eq != null; } /// <summary> /// Gets and sets the property FilterVariable. /// <para> /// Use one of the following variables to filter a list of <code>DataSource</code>: /// </para> /// <ul> <li> <code>CreatedAt</code> - Sets the search criteria to <code>DataSource</code> /// creation dates.</li> <li> <code>Status</code> - Sets the search criteria to <code>DataSource</code> /// statuses.</li> <li> <code>Name</code> - Sets the search criteria to the contents of /// <code>DataSource</code> <b> </b> <code>Name</code>.</li> <li> <code>DataUri</code> /// - Sets the search criteria to the URI of data files used to create the <code>DataSource</code>. /// The URI can identify either a file or an Amazon Simple Storage Service (Amazon S3) /// bucket or directory.</li> <li> <code>IAMUser</code> - Sets the search criteria to /// the user account that invoked the <code>DataSource</code> creation.</li> </ul> /// </summary> public DataSourceFilterVariable FilterVariable { get { return this._filterVariable; } set { this._filterVariable = value; } } // Check to see if FilterVariable property is set internal bool IsSetFilterVariable() { return this._filterVariable != null; } /// <summary> /// Gets and sets the property GE. /// <para> /// The greater than or equal to operator. The <code>DataSource</code> results will have /// <code>FilterVariable</code> values that are greater than or equal to the value specified /// with <code>GE</code>. /// </para> /// </summary> public string GE { get { return this._ge; } set { this._ge = value; } } // Check to see if GE property is set internal bool IsSetGE() { return this._ge != null; } /// <summary> /// Gets and sets the property GT. /// <para> /// The greater than operator. The <code>DataSource</code> results will have <code>FilterVariable</code> /// values that are greater than the value specified with <code>GT</code>. /// </para> /// </summary> public string GT { get { return this._gt; } set { this._gt = value; } } // Check to see if GT property is set internal bool IsSetGT() { return this._gt != null; } /// <summary> /// Gets and sets the property LE. /// <para> /// The less than or equal to operator. The <code>DataSource</code> results will have /// <code>FilterVariable</code> values that are less than or equal to the value specified /// with <code>LE</code>. /// </para> /// </summary> public string LE { get { return this._le; } set { this._le = value; } } // Check to see if LE property is set internal bool IsSetLE() { return this._le != null; } /// <summary> /// Gets and sets the property Limit. /// <para> /// The maximum number of <code>DataSource</code> to include in the result. /// </para> /// </summary> public int Limit { get { return this._limit.GetValueOrDefault(); } set { this._limit = value; } } // Check to see if Limit property is set internal bool IsSetLimit() { return this._limit.HasValue; } /// <summary> /// Gets and sets the property LT. /// <para> /// The less than operator. The <code>DataSource</code> results will have <code>FilterVariable</code> /// values that are less than the value specified with <code>LT</code>. /// </para> /// </summary> public string LT { get { return this._lt; } set { this._lt = value; } } // Check to see if LT property is set internal bool IsSetLT() { return this._lt != null; } /// <summary> /// Gets and sets the property NE. /// <para> /// The not equal to operator. The <code>DataSource</code> results will have <code>FilterVariable</code> /// values not equal to the value specified with <code>NE</code>. /// </para> /// </summary> public string NE { get { return this._ne; } set { this._ne = value; } } // Check to see if NE property is set internal bool IsSetNE() { return this._ne != null; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The ID of the page in the paginated results. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property Prefix. /// <para> /// A string that is found at the beginning of a variable, such as <code>Name</code> or /// <code>Id</code>. /// </para> /// /// <para> /// For example, a <code>DataSource</code> could have the <code>Name</code> <code>2014-09-09-HolidayGiftMailer</code>. /// To search for this <code>DataSource</code>, select <code>Name</code> for the <code>FilterVariable</code> /// and any of the following strings for the <code>Prefix</code>: /// </para> /// <ul> <li> /// <para> /// 2014-09 /// </para> /// </li> <li> /// <para> /// 2014-09-09 /// </para> /// </li> <li> /// <para> /// 2014-09-09-Holiday /// </para> /// </li> </ul> /// </summary> public string Prefix { get { return this._prefix; } set { this._prefix = value; } } // Check to see if Prefix property is set internal bool IsSetPrefix() { return this._prefix != null; } /// <summary> /// Gets and sets the property SortOrder. /// <para> /// A two-value parameter that determines the sequence of the resulting list of <code>DataSource</code>. /// </para> /// <ul> <li> <code>asc</code> - Arranges the list in ascending order (A-Z, 0-9).</li> /// <li> <code>dsc</code> - Arranges the list in descending order (Z-A, 9-0).</li> </ul> /// /// <para> /// Results are sorted by <code>FilterVariable</code>. /// </para> /// </summary> public SortOrder SortOrder { get { return this._sortOrder; } set { this._sortOrder = value; } } // Check to see if SortOrder property is set internal bool IsSetSortOrder() { return this._sortOrder != null; } } }
using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Xml; using ICSharpCode.SharpZipLib.Zip; using MarkdownSharp; using NuGet; using Splat; using ICSharpCode.SharpZipLib.Core; using System.Threading.Tasks; namespace Squirrel { internal static class FrameworkTargetVersion { public static FrameworkName Net40 = new FrameworkName(".NETFramework,Version=v4.0"); public static FrameworkName Net45 = new FrameworkName(".NETFramework,Version=v4.5"); } public interface IReleasePackage { string InputPackageFile { get; } string ReleasePackageFile { get; } string SuggestedReleaseFileName { get; } string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null); } public static class VersionComparer { public static bool Matches(IVersionSpec versionSpec, SemanticVersion version) { if (versionSpec == null) return true; // I CAN'T DEAL WITH THIS bool minVersion; if (versionSpec.MinVersion == null) { minVersion = true; // no preconditon? LET'S DO IT } else if (versionSpec.IsMinInclusive) { minVersion = version >= versionSpec.MinVersion; } else { minVersion = version > versionSpec.MinVersion; } bool maxVersion; if (versionSpec.MaxVersion == null) { maxVersion = true; // no preconditon? LET'S DO IT } else if (versionSpec.IsMaxInclusive) { maxVersion = version <= versionSpec.MaxVersion; } else { maxVersion = version < versionSpec.MaxVersion; } return maxVersion && minVersion; } } public class ReleasePackage : IEnableLogger, IReleasePackage { IEnumerable<IPackage> localPackageCache; public ReleasePackage(string inputPackageFile, bool isReleasePackage = false) { InputPackageFile = inputPackageFile; if (isReleasePackage) { ReleasePackageFile = inputPackageFile; } } public string InputPackageFile { get; protected set; } public string ReleasePackageFile { get; protected set; } public string SuggestedReleaseFileName { get { var zp = new ZipPackage(InputPackageFile); return String.Format("{0}-{1}-full.nupkg", zp.Id, zp.Version); } } public SemanticVersion Version { get { return InputPackageFile.ToSemanticVersion(); } } public string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null) { Contract.Requires(!String.IsNullOrEmpty(outputFile)); releaseNotesProcessor = releaseNotesProcessor ?? (x => (new Markdown()).Transform(x)); if (ReleasePackageFile != null) { return ReleasePackageFile; } var package = new ZipPackage(InputPackageFile); // we can tell from here what platform(s) the package targets // but given this is a simple package we only // ever expect one entry here (crash hard otherwise) var frameworks = package.GetSupportedFrameworks(); if (frameworks.Count() > 1) { var platforms = frameworks .Aggregate(new StringBuilder(), (sb, f) => sb.Append(f.ToString() + "; ")); throw new InvalidOperationException(String.Format( "The input package file {0} targets multiple platforms - {1} - and cannot be transformed into a release package.", InputPackageFile, platforms)); } else if (!frameworks.Any()) { throw new InvalidOperationException(String.Format( "The input package file {0} targets no platform and cannot be transformed into a release package.", InputPackageFile)); } var targetFramework = frameworks.Single(); // Recursively walk the dependency tree and extract all of the // dependent packages into the a temporary directory this.Log().Info("Creating release package: {0} => {1}", InputPackageFile, outputFile); var dependencies = findAllDependentPackages( package, new LocalPackageRepository(packagesRootDir), frameworkName: targetFramework); string tempPath = null; using (Utility.WithTempDirectory(out tempPath, null)) { var tempDir = new DirectoryInfo(tempPath); ExtractZipDecoded(InputPackageFile, tempPath); this.Log().Info("Extracting dependent packages: [{0}]", String.Join(",", dependencies.Select(x => x.Id))); extractDependentPackages(dependencies, tempDir, targetFramework); var specPath = tempDir.GetFiles("*.nuspec").First().FullName; this.Log().Info("Removing unnecessary data"); removeDependenciesFromPackageSpec(specPath); removeDeveloperDocumentation(tempDir); if (releaseNotesProcessor != null) { renderReleaseNotesMarkdown(specPath, releaseNotesProcessor); } addDeltaFilesToContentTypes(tempDir.FullName); if (contentsPostProcessHook != null) { contentsPostProcessHook(tempPath); } createZipEncoded(outputFile, tempPath); ReleasePackageFile = outputFile; return ReleasePackageFile; } } // nupkg file %-encodes zip entry names. This method decodes entry names before writing to disk. // We must do this, or PathTooLongException may be thrown for some unicode entry names. public static void ExtractZipDecoded(string zipFilePath, string outFolder) { var zf = new ZipFile(zipFilePath); var buffer = new byte[64*1024]; try { foreach (ZipEntry zipEntry in zf) { if (!zipEntry.IsFile) continue; var entryFileName = Uri.UnescapeDataString(zipEntry.Name); var fullZipToPath = Path.Combine(outFolder, entryFileName); var directoryName = Path.GetDirectoryName(fullZipToPath); if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } var zipStream = zf.GetInputStream(zipEntry); using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } } } finally { zf.Close(); } } public static async Task ExtractZipForInstall(string zipFilePath, string outFolder) { var zf = new ZipFile(zipFilePath); var directoryFilter = new NameFilter("lib"); var entries = zf.OfType<ZipEntry>().ToArray(); var re = new Regex(@"lib[\\\/][^\\\/]*[\\\/]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); try { await Utility.ForEachAsync(entries, (zipEntry) => { if (!zipEntry.IsFile) return; var entryFileName = Uri.UnescapeDataString(zipEntry.Name); var fullZipToPath = Path.Combine(outFolder, entryFileName); var directoryName = Path.GetDirectoryName(fullZipToPath); if (!directoryFilter.IsMatch(directoryName)) return; fullZipToPath = re.Replace(fullZipToPath, "", 1); directoryName = re.Replace(directoryName, "", 1); var buffer = new byte[64*1024]; if (directoryName.Length > 0) { Utility.Retry(() => Directory.CreateDirectory(directoryName), 2); } Utility.Retry(() => { using (var zipStream = zf.GetInputStream(zipEntry)) using (FileStream streamWriter = File.Create(fullZipToPath)) { StreamUtils.Copy(zipStream, streamWriter, buffer); } }, 5); }, 4); } finally { zf.Close(); } } // Create zip file with entry names %-encoded, as nupkg file does. void createZipEncoded(string zipFilePath, string folder) { folder = Path.GetFullPath(folder); var offset = folder.Length + (folder.EndsWith("\\", StringComparison.OrdinalIgnoreCase) ? 1 : 0); var fsOut = File.Create(zipFilePath); var zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(9); compressFolderEncoded(folder, zipStream, offset); zipStream.IsStreamOwner = true; zipStream.Close(); } void compressFolderEncoded(string path, ZipOutputStream zipStream, int folderOffset) { string[] files = Directory.GetFiles(path); var buffer = new byte[64 * 1024]; foreach (string filename in files) { var fi = new FileInfo(filename); string entryName = filename.Substring(folderOffset); entryName = ZipEntry.CleanName(entryName); entryName = Uri.EscapeUriString(entryName); var newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } string[] folders = Directory.GetDirectories(path); foreach (string folder in folders) { compressFolderEncoded(folder, zipStream, folderOffset); } } void extractDependentPackages(IEnumerable<IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework) { dependencies.ForEach(pkg => { this.Log().Info("Scanning {0}", pkg.Id); pkg.GetLibFiles().ForEach(file => { var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path)); if (!VersionUtility.IsCompatible(framework , new[] { file.TargetFramework })) { this.Log().Info("Ignoring {0} as the target framework is not compatible", outPath); return; } Directory.CreateDirectory(outPath.Directory.FullName); using (var of = File.Create(outPath.FullName)) { this.Log().Info("Writing {0} to {1}", file.Path, outPath); file.GetStream().CopyTo(of); } }); }); } void removeDeveloperDocumentation(DirectoryInfo expandedRepoPath) { expandedRepoPath.GetAllFilesRecursively() .Where(x => x.Name.EndsWith(".dll", true, CultureInfo.InvariantCulture)) .Select(x => new FileInfo(x.FullName.ToLowerInvariant().Replace(".dll", ".xml"))) .Where(x => x.Exists) .ForEach(x => x.Delete()); } void renderReleaseNotesMarkdown(string specPath, Func<string, string> releaseNotesProcessor) { var doc = new XmlDocument(); doc.Load(specPath); // XXX: This code looks full tart var metadata = doc.DocumentElement.ChildNodes .OfType<XmlElement>() .First(x => x.Name.ToLowerInvariant() == "metadata"); var releaseNotes = metadata.ChildNodes .OfType<XmlElement>() .FirstOrDefault(x => x.Name.ToLowerInvariant() == "releasenotes"); if (releaseNotes == null) { this.Log().Info("No release notes found in {0}", specPath); return; } releaseNotes.InnerText = String.Format("<![CDATA[\n" + "{0}\n" + "]]>", releaseNotesProcessor(releaseNotes.InnerText)); doc.Save(specPath); } void removeDependenciesFromPackageSpec(string specPath) { var xdoc = new XmlDocument(); xdoc.Load(specPath); var metadata = xdoc.DocumentElement.FirstChild; var dependenciesNode = metadata.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name.ToLowerInvariant() == "dependencies"); if (dependenciesNode != null) { metadata.RemoveChild(dependenciesNode); } xdoc.Save(specPath); } internal IEnumerable<IPackage> findAllDependentPackages( IPackage package = null, IPackageRepository packageRepository = null, HashSet<string> packageCache = null, FrameworkName frameworkName = null) { package = package ?? new ZipPackage(InputPackageFile); packageCache = packageCache ?? new HashSet<string>(); var deps = package.DependencySets .Where(x => x.TargetFramework == null || x.TargetFramework == frameworkName) .SelectMany(x => x.Dependencies); return deps.SelectMany(dependency => { var ret = matchPackage(packageRepository, dependency.Id, dependency.VersionSpec); if (ret == null) { var message = String.Format("Couldn't find file for package in {1}: {0}", dependency.Id, packageRepository.Source); this.Log().Error(message); throw new Exception(message); } if (packageCache.Contains(ret.GetFullName())) { return Enumerable.Empty<IPackage>(); } packageCache.Add(ret.GetFullName()); return findAllDependentPackages(ret, packageRepository, packageCache, frameworkName).StartWith(ret).Distinct(y => y.GetFullName()); }).ToArray(); } IPackage matchPackage(IPackageRepository packageRepository, string id, IVersionSpec version) { return packageRepository.FindPackagesById(id).FirstOrDefault(x => VersionComparer.Matches(version, x.Version)); } static internal void addDeltaFilesToContentTypes(string rootDirectory) { var doc = new XmlDocument(); var path = Path.Combine(rootDirectory, "[Content_Types].xml"); doc.Load(path); ContentType.Merge(doc); ContentType.Clean(doc); using (var sw = new StreamWriter(path, false, Encoding.UTF8)) { doc.Save(sw); } } } public class ChecksumFailedException : Exception { public string Filename { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Math.Geometry; using FlatRedBall.Math; using FlatRedBall.Graphics; #if FRB_MDX using System.Drawing; using FlatRedBall.Graphics; #elif XNA4 using Color = Microsoft.Xna.Framework.Color; #elif FRB_XNA using Color = Microsoft.Xna.Framework.Graphics.Color; #endif namespace EditorObjects { public class LineGrid { #region Fields Color mCenterLineColor = Color.White; Color mGridColor = Color.DarkGray; PositionedObjectList<Line> mHorizontalLines = new PositionedObjectList<Line>(); PositionedObjectList<Line> mVerticalLines = new PositionedObjectList<Line>(); int mNumberOfHorizontalLines = 11; int mNumberOfVerticalLines = 11; // The world coordinate centers float mX; float mY; float mZ; float mDistanceBetweenLines = 1; Layer mLayer; bool mVisible = true; #endregion #region Properties public Color CenterLineColor { get { return mCenterLineColor; } set { mCenterLineColor = value; UpdateGrid(); } } public float DistanceBetweenLines { get { return mDistanceBetweenLines; } set { mDistanceBetweenLines = value; UpdateGrid(); } } public Color GridColor { get { return mGridColor; } set { mGridColor = value; UpdateGrid(); } } public Layer Layer { set { for (int i = 0; i < mHorizontalLines.Count; i++) { ShapeManager.AddToLayer(mHorizontalLines[i], value, false); } for (int i = 0; i < mVerticalLines.Count; i++) { ShapeManager.AddToLayer(mVerticalLines[i], value, false); } mLayer = value; } } public int NumberOfHorizontalLines { get { return mNumberOfHorizontalLines; } set { if (value < 0) { throw new ArgumentException("Cannot have a negative number of horiontal lines"); } mNumberOfHorizontalLines = value; UpdateGrid(); } } public int NumberOfVerticalLines { get { return mNumberOfVerticalLines; } set { if (value < 0) { throw new ArgumentException("Cannot have a negative number of vertical lines"); } mNumberOfVerticalLines = value; UpdateGrid(); } } public bool Visible { get { return mVisible; } set { mVisible = value; UpdateVisibility(); } } public float X { get { return mX; } set { mX = value; UpdateGrid(); } } public float Y { get { return mY; } set { mY = value; UpdateGrid(); } } public float Z { get { return mZ; } set { mZ = value; UpdateGrid(); } } #endregion #region Methods #region Constructor public LineGrid() { CenterLineColor = Color.White; GridColor = Color.DarkGray; UpdateGrid(); } #endregion #region Private Methods private void UpdateGrid() { #region Make sure there are enough horizontal lines while (mHorizontalLines.Count < mNumberOfHorizontalLines) { Line newLine = new Line(); if (mLayer != null) { ShapeManager.AddToLayer(newLine, mLayer, false); } mHorizontalLines.Add(newLine); } while (mHorizontalLines.Count > mNumberOfHorizontalLines) { ShapeManager.Remove(mHorizontalLines.Last); } #endregion #region Make sure there are enough vertical lines while (mVerticalLines.Count < mNumberOfVerticalLines) { Line newLine = new Line(); if (mLayer != null) { ShapeManager.AddToLayer(newLine, mLayer, false); } mVerticalLines.Add(newLine); } while (mVerticalLines.Count > mNumberOfVerticalLines) { ShapeManager.Remove(mVerticalLines.Last); } #endregion #region Get top, bottom, left, right of LineGrid float bottom = mY - mDistanceBetweenLines *(mNumberOfHorizontalLines - 1) / 2.0f; float top = mY + mDistanceBetweenLines *(mNumberOfHorizontalLines - 1) / 2.0f; float left = mX - mDistanceBetweenLines *(mNumberOfVerticalLines - 1) / 2.0f; float right = mX + mDistanceBetweenLines *(mNumberOfVerticalLines - 1) / 2.0f; #endregion #region Position, color, and scale the horizontal lines for (int i = 0; i < mNumberOfHorizontalLines; i++) { mHorizontalLines[i].X = mX; mHorizontalLines[i].Y = bottom + i * mDistanceBetweenLines; mHorizontalLines[i].Z = mZ; mHorizontalLines[i].RelativePoint1.X = left - mX; mHorizontalLines[i].RelativePoint1.Y = 0; mHorizontalLines[i].RelativePoint2.X = right - mX; mHorizontalLines[i].RelativePoint2.Y = 0; if (i == mNumberOfHorizontalLines / 2) mHorizontalLines[i].Color = CenterLineColor; else mHorizontalLines[i].Color = GridColor; } #endregion #region Position, color, and scale the vertical lines for (int i = 0; i < mNumberOfVerticalLines; i++) { mVerticalLines[i].X = left + i * mDistanceBetweenLines; ; mVerticalLines[i].Y = mY; mVerticalLines[i].Z = mZ; mVerticalLines[i].RelativePoint1.X = 0; mVerticalLines[i].RelativePoint1.Y = bottom - mY; mVerticalLines[i].RelativePoint2.X = 0; mVerticalLines[i].RelativePoint2.Y = top - mY; if (i == mNumberOfVerticalLines / 2) mVerticalLines[i].Color = CenterLineColor; else mVerticalLines[i].Color = GridColor; } #endregion UpdateVisibility(); } private void UpdateVisibility() { for (int i = mHorizontalLines.Count - 1; i > -1; i--) { mHorizontalLines[i].Visible = mVisible; } for (int i = mVerticalLines.Count - 1; i > -1; i--) { mVerticalLines[i].Visible = mVisible; } } #endregion #endregion } }
namespace YAF.Pages.Admin { #region Using using System; using System.Data; using System.Linq; using System.Web.Security; using System.Web.UI.WebControls; using VZF.Data.Common; using YAF.Core; using YAF.Core.Services; using YAF.Types; using YAF.Types.Constants; using YAF.Types.Flags; using YAF.Types.Interfaces; using VZF.Utils; using VZF.Utils.Helpers; using System.Collections.Generic; using YAF.Classes; using VZF.Utilities; using System.Web; #endregion /// <summary> /// Interface for creating or editing user roles/groups. /// </summary> public partial class editgroup : AdminPage { #region Methods public DataTable AccessMasksList { get; set; } private Dictionary<int, DataTable> personalAccessMaskListIds; /// <summary> /// Handles databinding event of initial access maks dropdown control. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void BindData_AccessMaskID([NotNull] object sender, [NotNull] EventArgs e) { // We don't change access masks if it's a guest if (!this.IsGuestX.Checked) { // get sender object as dropdown list var c = (DropDownList) sender; // list all access masks as data source c.DataSource = this.AccessMasksList; // set value and text field names c.DataValueField = "AccessMaskID"; c.DataTextField = "Name"; } else { } } /// <summary> /// Handles click on cancel button. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Cancel_Click([NotNull] object sender, [NotNull] EventArgs e) { // go back to roles administration YafBuildLink.Redirect(ForumPages.admin_groups); } /// <summary> /// Creates page links for this page. /// </summary> protected override void CreatePageLinks() { // forum index this.PageLinks.AddLink(this.PageContext.BoardSettings.Name, YafBuildLink.GetLink(ForumPages.forum)); // admin index this.PageLinks.AddLink(this.GetText("ADMIN_ADMIN", "Administration"), YafBuildLink.GetLink(ForumPages.admin_admin)); this.PageLinks.AddLink(this.GetText("ADMIN_GROUPS", "TITLE"), YafBuildLink.GetLink(ForumPages.admin_groups)); // current page label (no link) this.PageLinks.AddLink(this.GetText("ADMIN_EDITGROUP", "TITLE"), string.Empty); this.Page.Header.Title = "{0} - {1} - {2}".FormatWith( this.GetText("ADMIN_ADMIN", "Administration"), this.GetText("ADMIN_GROUPS", "TITLE"), this.GetText("ADMIN_EDITGROUP", "TITLE")); } /// <summary> /// Handles page load event. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { // this needs to be done just once, not during postbacks if (this.IsPostBack) { return; } // create page links this.CreatePageLinks(); this.Save.Text = this.GetText("COMMON", "SAVE"); this.Cancel.Text = this.GetText("COMMON", "CANCEL"); if (Config.LargeForumTree && this.Request.QueryString.GetFirstOrDefault("i") != null) { string args = "&links=1"; int? groupId = null; if (this.Request.QueryString.GetFirstOrDefault("i") !=null) { groupId = this.Request.QueryString.GetFirstOrDefault("i").ToType<int>(); args = args + "&amdd={0}".FormatWith(groupId); } this.treeRow.Visible = true; YafContext.Current.PageElements.RegisterJQueryUI(); YafContext.Current.PageElements.RegisterJsResourceInclude("fancytree", "js/jquery.fancytree-all.min.js"); YafContext.Current.PageElements.RegisterCssIncludeResource("css/fancytree/{0}/ui.fancytree.css".FormatWith(YafContext.Current.Get<YafBoardSettings>().FancyTreeTheme)); YafContext.Current.PageElements.RegisterJsResourceInclude("ftreeeditgroupjs", "js/fancytree.vzf.nodesadminsetgroupaccess.js"); YafContext.Current.PageElements.RegisterJsBlockStartup( "fancytreeeditgroupscr", "fancyTreeSetNodesGroupAccessLazyJS('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');" .FormatWith( Config.JQueryAlias, "treegroupaccess", PageContext.PageUserID, PageContext.PageBoardID, groupId, args, string.Empty, "{0}resource.ashx?".FormatWith(YafForumInfo.ForumClientFileRoot), "&forumUrl={0}".FormatWith(HttpUtility.UrlDecode(YafBuildLink.GetBasePath())))); } // bind data this.BindData(); // is this editing of existing role or creation of new one? if (this.Request.QueryString.GetFirstOrDefault("i") == null) { return; } // we are not creating new role this.NewGroupRow.Visible = false; // get data about edited role using ( DataTable dt = CommonDb.group_list(this.PageContext.PageModuleID, this.PageContext.PageBoardID, this.Request.QueryString.GetFirstOrDefault("i"), 0, 1000000)) { // get it as row DataRow row = dt.Rows[0]; // get role flags var flags = new GroupFlags(row["Flags"]); // set controls to role values this.Name.Text = (string)row["Name"]; this.IsAdminX.Checked = flags.IsAdmin; this.IsAdminX.Enabled = !flags.IsGuest; this.IsStartX.Checked = flags.IsStart; this.IsStartX.Enabled = !flags.IsGuest; this.IsModeratorX.Checked = flags.IsModerator; this.IsModeratorX.Enabled = !flags.IsGuest; this.IsHiddenX.Checked = flags.IsHidden; // this.IsHiddenX.Enabled = !flags.IsGuest; this.PMLimit.Text = row["PMLimit"].ToString(); this.PMLimit.Enabled = !flags.IsGuest; this.StyleTextBox.Text = row["Style"].ToString(); this.Priority.Text = row["SortOrder"].ToString(); this.UsrAlbums.Text = row["UsrAlbums"].ToString(); this.UsrAlbums.Enabled = !flags.IsGuest; this.UsrAlbumImages.Text = row["UsrAlbumImages"].ToString(); this.UsrAlbumImages.Enabled = !flags.IsGuest; this.UsrSigChars.Text = row["UsrSigChars"].ToString(); this.UsrSigChars.Enabled = !flags.IsGuest; this.UsrSigBBCodes.Text = row["UsrSigBBCodes"].ToString(); this.UsrSigBBCodes.Enabled = !flags.IsGuest; this.UsrSigHTMLTags.Text = row["UsrSigHTMLTags"].ToString(); this.UsrSigHTMLTags.Enabled = !flags.IsGuest; this.PersonalGroupsNumber.Text = row["UsrPersonalGroups"].ToString(); this.PersonalGroupsNumber.Enabled = !flags.IsGuest; this.PersonalForumsNumber.Text = row["UsrPersonalForums"].ToString(); this.PersonalForumsNumber.Enabled = !flags.IsGuest; this.PersonalAccessMasksNumber.Text = row["UsrPersonalMasks"].ToString(); this.PersonalAccessMasksNumber.Enabled = !flags.IsGuest; // this.UserNickStyleEditor.Styles = row["Style"].ToString(); this.Description.Text = row["Description"].ToString(); this.IsGuestX.Checked = flags.IsGuest; // IsGuest flag can be set for only one role. if it isn't for this, disable that row if (flags.IsGuest) { this.IsGuestTR.Visible = true; this.IsGuestX.Enabled = !flags.IsGuest; this.AccessList.Visible = false; } } } /// <summary> /// Handles click on save button. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void Save_Click([NotNull] object sender, [NotNull] EventArgs e) { if (!ValidationHelper.IsValidInt(this.PMLimit.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_VALID_NUMBER")); return; } if (!ValidationHelper.IsValidInt(this.Priority.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_INTEGER")); return; } if (!ValidationHelper.IsValidInt(this.UsrAlbums.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_ALBUM_NUMBER")); return; } if (!ValidationHelper.IsValidInt(this.UsrSigChars.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_SIG_NUMBER")); return; } if (!ValidationHelper.IsValidInt(this.PersonalForumsNumber.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_PFORUMS_NUMBER")); return; } if (!ValidationHelper.IsValidInt(this.PersonalAccessMasksNumber.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_PFORUMS_MASKSNUMBER")); return; } if (!ValidationHelper.IsValidInt(this.PersonalGroupsNumber.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_PFORUMS_PGROUPSNUMBER")); return; } if (!ValidationHelper.IsValidInt(this.UsrAlbumImages.Text.Trim())) { this.PageContext.AddLoadMessage(this.GetText("ADMIN_EDITGROUP", "MSG_TOTAL_NUMBER")); return; } // Role long roleID = 0; // get role ID from page's parameter if (this.Request.QueryString.GetFirstOrDefault("i") != null) { roleID = long.Parse(this.Request.QueryString.GetFirstOrDefault("i")); } // get new and old name string roleName = this.Name.Text.Trim(); string oldRoleName = string.Empty; // if we are editing exising role, get it's original name if (roleID != 0) { // get the current role name in the DB using (DataTable dt = CommonDb.group_list(this.PageContext.PageModuleID, YafContext.Current.PageBoardID, roleID, 0, 1000000)) { foreach (DataRow row in dt.Rows) { oldRoleName = row["Name"].ToString(); } } } // save role and get its ID if it's new (if it's old role, we get it anyway) roleID = CommonDb.group_save(PageContext.PageModuleID, roleID, this.PageContext.PageBoardID, roleName, this.IsAdminX.Checked, this.IsGuestX.Checked, this.IsStartX.Checked, this.IsModeratorX.Checked, this.IsHiddenX.Checked, AccessMaskID.SelectedValue, this.PMLimit.Text.Trim(), this.StyleTextBox.Text.Trim(), this.Priority.Text.Trim(), this.Description.Text, this.UsrSigChars.Text, this.UsrSigBBCodes.Text, this.UsrSigHTMLTags.Text, this.UsrAlbums.Text.Trim(), this.UsrAlbumImages.Text.Trim(), PageContext.PageUserID, false, this.PersonalForumsNumber.Text.Trim(), this.PersonalAccessMasksNumber.Text.Trim(), this.PersonalGroupsNumber.Text.Trim()); // empty out access table CommonDb.activeaccess_reset(PageContext.PageModuleID); // see if need to rename an existing role... if (oldRoleName.IsSet() && roleName != oldRoleName && RoleMembershipHelper.RoleExists(oldRoleName) && !RoleMembershipHelper.RoleExists(roleName) && !this.IsGuestX.Checked) { // transfer users in addition to changing the name of the role... var users = this.Get<RoleProvider>().GetUsersInRole(oldRoleName); // delete the old role... RoleMembershipHelper.DeleteRole(oldRoleName, false); // create new role... RoleMembershipHelper.CreateRole(roleName); if (users.Any()) { // put users into new role... this.Get<RoleProvider>().AddUsersToRoles(users, new[] { roleName }); } } else if (!RoleMembershipHelper.RoleExists(roleName) && !this.IsGuestX.Checked) { // if role doesn't exist in provider's data source, create it // simply create it RoleMembershipHelper.CreateRole(roleName); } // Clearing cache with old user lazy data... this.Get<IDataCache>().Remove(k => k.StartsWith(Constants.Cache.ActiveUserLazyData.FormatWith(String.Empty))); // Access masks for a newly created or an existing role if (this.Request.QueryString.GetFirstOrDefault("i") != null) { // go trhough all forums for (int i = 0; i < this.AccessList.Items.Count; i++) { // get current repeater item RepeaterItem item = this.AccessList.Items[i]; // get forum ID int forumID = int.Parse(((Label)item.FindControl("ForumID")).Text); // save forum access masks for this role CommonDb.forumaccess_save(PageContext.PageModuleID, forumID, roleID, ((DropDownList)item.FindControl("AccessmaskID")).SelectedValue); } YafBuildLink.Redirect(ForumPages.admin_groups); } // remove caching in case something got updated... this.Get<IDataCache>().Remove(Constants.Cache.ForumModerators); // Done, redirect to role editing page YafBuildLink.Redirect(ForumPages.admin_editgroup, "i={0}", roleID); } /// <summary> /// Handles pre-render event of each forum's access mask dropdown. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> protected void SetDropDownIndex([NotNull] object sender, [NotNull] EventArgs e) { // get dropdown which raised this event var list = (DropDownList)sender; // select value from the list ListItem item = list.Items.FindByValue(list.Attributes["value"]); // verify something was found... if (item != null) { item.Selected = true; } } /// <summary> /// Bind data for this control. /// </summary> private void BindData() { // set datasource of access list (list of forums and role's access masks) if we are editing existing mask if (!Config.LargeForumTree && this.Request.QueryString.GetFirstOrDefault("i") != null) { this.AccessList.DataSource = CommonDb.forumaccess_group(PageContext.PageModuleID, this.Request.QueryString.GetFirstOrDefault("i"), PageContext.PageUserID, false); } // TODO: here should be a swithch between common forums and personal forums this.AccessMasksList = CommonDb.accessmask_aforumlist(mid: this.PageContext.PageModuleID, boardId: this.PageContext.PageBoardID, accessMaskId: null, excludeFlags: 0, pageUserId: null, isAdminMask: true, isCommonMask: true); // bind data to controls this.DataBind(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace KScottAllenWebApi2.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; } } }
#region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; #endregion namespace TwglExport { /// <summary> /// Export a selected Revit element to WebGL by /// traversing and analysing its element geometry. /// </summary> [Transaction( TransactionMode.ReadOnly )] public class CmdElemGeom : IExternalCommand { /// <summary> /// Toggle between a local server and /// a remote Heroku-hosted one. /// </summary> static public bool UseLocalServer = true; /// <summary> /// If true, individual curved surface facets are /// retained, otherwise (default) smoothing is /// applied. /// </summary> static public bool RetainCurvedSurfaceFacets = false; /// <summary> /// Generate a JSON string defining the geometry /// data consisting of face indices, vertices and /// normal vectors. /// </summary> /// <param name="scale">Scaling factor to fit it all into a two-unit cube</param> /// <param name="faceIndices">Face indices</param> /// <param name="faceVertices">Face vertices</param> /// <param name="faceNormals">Face normals</param> /// <returns></returns> static public string GetJsonGeometryData( double scale, List<int> faceIndices, List<int> faceVertices, List<double> faceNormals ) { string sposition = string.Join( ", ", faceVertices.ConvertAll<string>( i => ( i * scale ).ToString( "0.##" ) ) ); string snormal = string.Join( ", ", faceNormals.ConvertAll<string>( f => f.ToString( "0.##" ) ) ); string sindices = string.Join( ", ", faceIndices.ConvertAll<string>( i => i.ToString() ) ); Debug.Print( "position: [{0}],", sposition ); Debug.Print( "normal: [{0}],", snormal ); Debug.Print( "indices: [{0}],", sindices ); //string json_geometry_data = string.Format( // "{ \"position\": [{0}],\n\"normal\": [{1}], \"indices\": [{2}] }", // sposition, snormal, sindices ); string json_geometry_data = "{ \"position\": [" + sposition + "],\n\"normal\": [" + snormal + "],\n\"indices\": [" + sindices + "] }"; Debug.Print( "json: " + json_geometry_data ); return json_geometry_data; } static bool EnsureJsModulePresent( string filename ) { bool rc = File.Exists( filename ); if( !rc ) { Util.ErrorMsg( string.Format( "{0} not found.", filename ) ); } return rc; } /// <summary> /// Check that the necessary JavaScript support /// modules are present in the specified folder. /// </summary> static bool EnsureJsModulesPresent( string dir ) { string [] modules = new string[] { "fs.js", "jquery-1.3.2.min.js", "twgl-full.min.js", "viewer.js", "vs.js" }; return modules.All<string>( s => EnsureJsModulePresent( Path.Combine( dir, s ) ) ); } /// <summary> /// Invoke the node.js WebGL viewer web server. /// Use a local or global base URL and an HTTP POST /// request passing the 3D geometry data as body. /// </summary> static public bool DisplayWgl( string json_geometry_data ) { bool rc = false; string base_url = UseLocalServer ? "http://127.0.0.1:5000" : "https://nameless-harbor-7576.herokuapp.com"; string api_route = "api/v2"; string uri = base_url + "/" + api_route; HttpWebRequest req = WebRequest.Create( uri ) as HttpWebRequest; req.KeepAlive = false; req.Method = WebRequestMethods.Http.Post; // Turn our request string into a byte stream. byte[] postBytes = Encoding.UTF8.GetBytes( json_geometry_data ); req.ContentLength = postBytes.Length; // Specify content type. req.ContentType = "application/json; charset=UTF-8"; // or just "text/json"? req.Accept = "application/json"; req.ContentLength = postBytes.Length; Stream requestStream = req.GetRequestStream(); requestStream.Write( postBytes, 0, postBytes.Length ); requestStream.Close(); HttpWebResponse res = req.GetResponse() as HttpWebResponse; string result; using( StreamReader reader = new StreamReader( res.GetResponseStream() ) ) { result = reader.ReadToEnd(); } // Get JavaScript modules from server public folder. result = result.Replace( "<script src=\"/", "<script src=\"" + base_url + "/" ); string filename = Path.GetTempFileName(); filename = Path.ChangeExtension( filename, "html" ); //string dir = Path.GetDirectoryName( filename ); //// Get JavaScript modules from current directory. //string path = dir // .Replace( Path.GetPathRoot( dir ), "" ) // .Replace( '\\', '/' ); ////result = result.Replace( "<script src=\"/", //// "<script src=\"file:///" + dir + "/" ); // XMLHttpRequest cannot load file:///C:/Users/tammikj/AppData/Local/Temp/vs.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. //result = result.Replace( "<script src=\"/", // "<script src=\"" ); //if( EnsureJsModulesPresent( dir ) ) { using( StreamWriter writer = File.CreateText( filename ) ) { writer.Write( result ); writer.Close(); } System.Diagnostics.Process.Start( filename ); rc = true; } return rc; } public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; ICollection<ElementId> ids = sel.GetElementIds(); if( 1 != ids.Count ) { message = "Please select an element to export to TWGL."; return Result.Failed; } Element e = null; foreach( ElementId id in ids ) { e = doc.GetElement( id ); } // Determine bounding box in order to translate // all coordinates to bounding box midpoint. BoundingBoxXYZ bb = e.get_BoundingBox( null ); XYZ pmin = bb.Min; XYZ pmax = bb.Max; XYZ vsize = pmax - pmin; XYZ pmid = pmin + 0.5 * vsize; Options opt = new Options(); GeometryElement geo = e.get_Geometry( opt ); List<int> faceIndices = new List<int>(); List<int> faceVertices = new List<int>(); List<double> faceNormals = new List<double>(); int[] triangleIndices = new int[3]; XYZ[] triangleCorners = new XYZ[3]; foreach( GeometryObject obj in geo ) { Solid solid = obj as Solid; if( solid != null && 0 < solid.Faces.Size ) { faceIndices.Clear(); faceVertices.Clear(); faceNormals.Clear(); foreach( Face face in solid.Faces ) { Mesh mesh = face.Triangulate(); int nTriangles = mesh.NumTriangles; IList<XYZ> vertices = mesh.Vertices; int nVertices = vertices.Count; List<int> vertexCoordsMm = new List<int>( 3 * nVertices ); // A vertex may be reused several times with // different normals for different faces, so // we cannot precalculate normals per vertex. //List<double> normals = new List<double>( 3 * nVertices ); foreach( XYZ v in vertices ) { // Translate the entire element geometry // to the bounding box midpoint and scale // to metric millimetres. XYZ p = v - pmid; vertexCoordsMm.Add( Util.FootToMm( p.X ) ); vertexCoordsMm.Add( Util.FootToMm( p.Y ) ); vertexCoordsMm.Add( Util.FootToMm( p.Z ) ); } for( int i = 0; i < nTriangles; ++i ) { MeshTriangle triangle = mesh.get_Triangle( i ); for( int j = 0; j < 3; ++j ) { int k = (int) triangle.get_Index( j ); triangleIndices[j] = k; triangleCorners[j] = vertices[k]; } // Calculate constant triangle facet normal. XYZ v = triangleCorners[1] - triangleCorners[0]; XYZ w = triangleCorners[2] - triangleCorners[0]; XYZ triangleNormal = v .CrossProduct( w ) .Normalize(); for( int j = 0; j < 3; ++j ) { int nFaceVertices = faceVertices.Count; Debug.Assert( nFaceVertices.Equals( faceNormals.Count ), "expected equal number of face vertex and normal coordinates" ); faceIndices.Add( nFaceVertices / 3 ); int i3 = triangleIndices[j] * 3; // Rotate the X, Y and Z directions, // since the Z direction points upward // in Revit as opposed to sideways or // outwards or forwards in WebGL. faceVertices.Add( vertexCoordsMm[i3 + 1] ); faceVertices.Add( vertexCoordsMm[i3 + 2] ); faceVertices.Add( vertexCoordsMm[i3] ); if( RetainCurvedSurfaceFacets ) { faceNormals.Add( triangleNormal.Y ); faceNormals.Add( triangleNormal.Z ); faceNormals.Add( triangleNormal.X ); } else { UV uv = face.Project( triangleCorners[j] ).UVPoint; XYZ normal = face.ComputeNormal( uv ); faceNormals.Add( normal.Y ); faceNormals.Add( normal.Z ); faceNormals.Add( normal.X ); } } } } // Scale the vertices to a [-1,1] cube // centered around the origin. Translation // to the origin was already performed above. double scale = 2.0 / Util.FootToMm( Util.MaxCoord( vsize ) ); string json_geometry_data = GetJsonGeometryData( scale, faceIndices, faceVertices, faceNormals ); DisplayWgl( json_geometry_data ); // Ignore other solids in this element. // Please use the custom exporter for // more complex element geometry. break; } } return Result.Succeeded; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Reflection; using System.Xml; using NUnit.Framework.Api; using NUnit.Framework.Internal.Commands; #if true #else using System.Collections; #endif namespace NUnit.Framework.Internal { /// <summary> /// TestSuite represents a composite test, which contains other tests. /// </summary> public class TestSuite : Test { #region Fields /// <summary> /// Our collection of child tests /// </summary> #if true private List<ITest> tests = new List<ITest>(); #else private ArrayList tests = new ArrayList(); #endif /// <summary> /// Set to true to suppress sorting this suite's contents /// </summary> protected bool maintainTestOrder; ///// <summary> ///// Arguments for use in creating a parameterized fixture ///// </summary> //internal object[] arguments; /// <summary> /// The fixture setup methods for this suite /// </summary> protected MethodInfo[] oneTimeSetUpMethods; /// <summary> /// The fixture teardown methods for this suite /// </summary> protected MethodInfo[] oneTimeTearDownMethods; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="name">The name of the suite.</param> public TestSuite( string name ) : base( name ) { } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="parentSuiteName">Name of the parent suite.</param> /// <param name="name">The name of the suite.</param> public TestSuite( string parentSuiteName, string name ) : base( parentSuiteName, name ) { } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="fixtureType">Type of the fixture.</param> public TestSuite(Type fixtureType) : this(fixtureType, null) { } /// <summary> /// Initializes a new instance of the <see cref="TestSuite"/> class. /// </summary> /// <param name="fixtureType">Type of the fixture.</param> /// <param name="arguments">The arguments.</param> public TestSuite(Type fixtureType, object[] arguments) : base(fixtureType) { string name = TypeHelper.GetDisplayName(fixtureType, arguments); this.Name = name; this.FullName = name; string nspace = fixtureType.Namespace; if (nspace != null && nspace != "") this.FullName = nspace + "." + name; this.arguments = arguments; } #endregion #region Public Methods /// <summary> /// Sorts tests under this suite. /// </summary> public void Sort() { if (!maintainTestOrder) { this.tests.Sort(); foreach (Test test in Tests) { TestSuite suite = test as TestSuite; if (suite != null) suite.Sort(); } } } #if false /// <summary> /// Sorts tests under this suite using the specified comparer. /// </summary> /// <param name="comparer">The comparer.</param> public void Sort(IComparer comparer) { this.tests.Sort(comparer); foreach( Test test in Tests ) { TestSuite suite = test as TestSuite; if ( suite != null ) suite.Sort(comparer); } } #endif /// <summary> /// Adds a test to the suite. /// </summary> /// <param name="test">The test.</param> public void Add( Test test ) { // if( test.RunState == RunState.Runnable ) // { // test.RunState = this.RunState; // test.IgnoreReason = this.IgnoreReason; // } test.Parent = this; tests.Add(test); } #if !NUNITLITE && false /// <summary> /// Adds a pre-constructed test fixture to the suite. /// </summary> /// <param name="fixture">The fixture.</param> public void Add( object fixture ) { Test test = TestFixtureBuilder.BuildFrom( fixture ); if ( test != null ) Add( test ); } #endif #endregion #region Properties /// <summary> /// Gets this test's child tests /// </summary> /// <value>The list of child tests</value> #if true public override IList<ITest> Tests #else public override IList Tests #endif { get { return tests; } } /// <summary> /// Gets a count of test cases represented by /// or contained under this test. /// </summary> /// <value></value> public override int TestCaseCount { get { int count = 0; foreach(Test test in Tests) { count += test.TestCaseCount; } return count; } } /// <summary> /// Gets the set up methods. /// </summary> /// <returns></returns> internal MethodInfo[] OneTimeSetUpMethods { get { return oneTimeSetUpMethods; } } /// <summary> /// Gets the tear down methods. /// </summary> /// <returns></returns> internal MethodInfo[] OneTimeTearDownMethods { get { return oneTimeTearDownMethods; } } #endregion #region Test Overrides /// <summary> /// Overridden to return a TestSuiteResult. /// </summary> /// <returns>A TestResult for this test.</returns> public override TestResult MakeTestResult() { return new TestSuiteResult(this); } protected override TestCommand MakeTestCommand(ITestFilter filter) { TestCommand command = new TestSuiteCommand(this); foreach (Test childTest in Tests) if (filter.Pass(childTest)) command.Children.Add(childTest.GetTestCommand(filter)); #if !NUNITLITE && false if (ShouldRunOnOwnThread) command = new ThreadedTestCommand(command); #endif return command; } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public override bool HasChildren { get { return tests.Count > 0; } } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public override string XmlElementName { get { return "test-suite"; } } /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public override System.Xml.XmlNode AddToXml(XmlNode parentNode, bool recursive) { XmlNode thisNode = XmlHelper.AddElement(parentNode, "test-suite"); XmlHelper.AddAttribute(thisNode, "type", this.TestType); PopulateTestNode(thisNode, recursive); XmlHelper.AddAttribute(thisNode, "testcasecount", this.TestCaseCount.ToString()); if (recursive) foreach (Test test in this.Tests) test.AddToXml(thisNode, recursive); return thisNode; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { // // N.B.: // A lot of this code is directly from DateTime.cs. If you update that class, // update this one as well. // However, we still need these duplicated code because we will add era support // in this class. // // using System.Threading; using System; using System.Globalization; using System.Runtime.Serialization; using System.Diagnostics.Contracts; // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class GregorianCalendar : Calendar { /* A.D. = anno Domini */ public const int ADEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; #region Serialization [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_type < GregorianCalendarTypes.Localized || m_type > GregorianCalendarTypes.TransliteratedFrench) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Serialization_MemberOutOfRange"), "type", "GregorianCalendar")); } } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Gregorian calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new GregorianCalendar(); } return (s_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( nameof(type), Environment.GetResourceString("ArgumentOutOfRange_Range", GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } Contract.EndContractBlock(); this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch (value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: throw new ArgumentOutOfRangeException(nameof(m_type), Environment.GetResourceString("ArgumentOutOfRange_Enum")); } } } internal override int ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((int)m_type); } } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day)* TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), -120000, 120000)); } Contract.EndContractBlock(); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (ADEra); } public override int[] Eras { get { return (new int[] {ADEra} ); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (12); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 12)); } Contract.EndContractBlock(); if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } Contract.EndContractBlock(); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 12)); } Contract.EndContractBlock(); return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result); } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System; using ForieroEditor.Platforms.iOS.Xcode.PBX; namespace ForieroEditor.Platforms.iOS.Xcode { using PBXBuildFileSection = KnownSectionBase<PBXBuildFileData>; using PBXFileReferenceSection = KnownSectionBase<PBXFileReferenceData>; using PBXGroupSection = KnownSectionBase<PBXGroupData>; using PBXContainerItemProxySection = KnownSectionBase<PBXContainerItemProxyData>; using PBXReferenceProxySection = KnownSectionBase<PBXReferenceProxyData>; using PBXSourcesBuildPhaseSection = KnownSectionBase<PBXSourcesBuildPhaseData>; using PBXFrameworksBuildPhaseSection = KnownSectionBase<PBXFrameworksBuildPhaseData>; using PBXResourcesBuildPhaseSection = KnownSectionBase<PBXResourcesBuildPhaseData>; using PBXCopyFilesBuildPhaseSection = KnownSectionBase<PBXCopyFilesBuildPhaseData>; using PBXShellScriptBuildPhaseSection = KnownSectionBase<PBXShellScriptBuildPhaseData>; using PBXVariantGroupSection = KnownSectionBase<PBXVariantGroupData>; using PBXNativeTargetSection = KnownSectionBase<PBXNativeTargetData>; using PBXTargetDependencySection = KnownSectionBase<PBXTargetDependencyData>; using XCBuildConfigurationSection = KnownSectionBase<XCBuildConfigurationData>; using XCConfigurationListSection = KnownSectionBase<XCConfigurationListData>; using UnknownSection = KnownSectionBase<PBXObjectData>; // Determines the tree the given path is relative to public enum PBXSourceTree { Absolute, // The path is absolute Source, // The path is relative to the source folder Group, // The path is relative to the folder it's in. This enum is used only internally, // do not use it as function parameter Build, // The path is relative to the build products folder Developer, // The path is relative to the developer folder Sdk // The path is relative to the sdk folder} } public class PBXProject { PBXProjectData m_Data = new PBXProjectData (); // convenience accessors for public members of data. This is temporary; will be fixed by an interface change // of PBXProjectData PBXContainerItemProxySection containerItems { get { return m_Data.containerItems; } } PBXReferenceProxySection references { get { return m_Data.references; } } PBXSourcesBuildPhaseSection sources { get { return m_Data.sources; } } PBXFrameworksBuildPhaseSection frameworks { get { return m_Data.frameworks; } } PBXResourcesBuildPhaseSection resources { get { return m_Data.resources; } } PBXCopyFilesBuildPhaseSection copyFiles { get { return m_Data.copyFiles; } } PBXShellScriptBuildPhaseSection shellScripts { get { return m_Data.shellScripts; } } PBXNativeTargetSection nativeTargets { get { return m_Data.nativeTargets; } } PBXTargetDependencySection targetDependencies { get { return m_Data.targetDependencies; } } PBXVariantGroupSection variantGroups { get { return m_Data.variantGroups; } } XCBuildConfigurationSection buildConfigs { get { return m_Data.buildConfigs; } } XCConfigurationListSection configs { get { return m_Data.configs; } } PBXProjectSection project { get { return m_Data.project; } } PBXBuildFileData BuildFilesGet (string guid) { return m_Data.BuildFilesGet (guid); } void BuildFilesAdd (string targetGuid, PBXBuildFileData buildFile) { m_Data.BuildFilesAdd (targetGuid, buildFile); } void BuildFilesRemove (string targetGuid, string fileGuid) { m_Data.BuildFilesRemove (targetGuid, fileGuid); } PBXBuildFileData BuildFilesGetForSourceFile (string targetGuid, string fileGuid) { return m_Data.BuildFilesGetForSourceFile (targetGuid, fileGuid); } IEnumerable<PBXBuildFileData> BuildFilesGetAll () { return m_Data.BuildFilesGetAll (); } void FileRefsAdd (string realPath, string projectPath, PBXGroupData parent, PBXFileReferenceData fileRef) { m_Data.FileRefsAdd (realPath, projectPath, parent, fileRef); } PBXFileReferenceData FileRefsGet (string guid) { return m_Data.FileRefsGet (guid); } PBXFileReferenceData FileRefsGetByRealPath (string path, PBXSourceTree sourceTree) { return m_Data.FileRefsGetByRealPath (path, sourceTree); } PBXFileReferenceData FileRefsGetByProjectPath (string path) { return m_Data.FileRefsGetByProjectPath (path); } void FileRefsRemove (string guid) { m_Data.FileRefsRemove (guid); } PBXGroupData GroupsGet (string guid) { return m_Data.GroupsGet (guid); } PBXGroupData GroupsGetByChild (string childGuid) { return m_Data.GroupsGetByChild (childGuid); } PBXGroupData GroupsGetMainGroup () { return m_Data.GroupsGetMainGroup (); } PBXGroupData GroupsGetByProjectPath (string sourceGroup) { return m_Data.GroupsGetByProjectPath (sourceGroup); } void GroupsAdd (string projectPath, PBXGroupData parent, PBXGroupData gr) { m_Data.GroupsAdd (projectPath, parent, gr); } void GroupsAddDuplicate (PBXGroupData gr) { m_Data.GroupsAddDuplicate (gr); } void GroupsRemove (string guid) { m_Data.GroupsRemove (guid); } FileGUIDListBase BuildSectionAny (PBXNativeTargetData target, string path, bool isFolderRef) { return m_Data.BuildSectionAny (target, path, isFolderRef); } public static string GetPBXProjectPath (string buildPath) { return Utils.CombinePaths (buildPath, "Unity-iPhone.xcodeproj/project.pbxproj"); } public static string GetUnityTargetName () { return "Unity-iPhone"; } public static string GetUnityTestTargetName () { return "Unity-iPhone Tests"; } internal string ProjectGuid () { return project.project.guid; } /// Returns a guid identifying native target with name @a name public string TargetGuidByName (string name) { foreach (var entry in nativeTargets.GetEntries()) if (entry.Value.name == name) return entry.Key; return null; } public static bool IsKnownExtension (string ext) { return FileTypeUtils.IsKnownExtension (ext); } public static bool IsBuildable (string ext) { return FileTypeUtils.IsBuildableFile (ext); } // The same file can be referred to by more than one project path. private string AddFileImpl (string path, string projectPath, PBXSourceTree tree, bool isFolderReference) { path = Utils.FixSlashesInPath (path); projectPath = Utils.FixSlashesInPath (projectPath); if (!isFolderReference && Path.GetExtension (path) != Path.GetExtension (projectPath)) throw new Exception ("Project and real path extensions do not match"); string guid = FindFileGuidByProjectPath (projectPath); if (guid == null) guid = FindFileGuidByRealPath (path); if (guid == null) { PBXFileReferenceData fileRef; if (isFolderReference) fileRef = PBXFileReferenceData.CreateFromFolderReference (path, Utils.GetFilenameFromPath (projectPath), tree); else fileRef = PBXFileReferenceData.CreateFromFile (path, Utils.GetFilenameFromPath (projectPath), tree); PBXGroupData parent = CreateSourceGroup (Utils.GetDirectoryFromPath (projectPath)); parent.children.AddGUID (fileRef.guid); FileRefsAdd (path, projectPath, parent, fileRef); guid = fileRef.guid; } return guid; } // The extension of the files identified by path and projectPath must be the same. public string AddFile (string path, string projectPath) { return AddFileImpl (path, projectPath, PBXSourceTree.Source, false); } // sourceTree must not be PBXSourceTree.Group public string AddFile (string path, string projectPath, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception ("sourceTree must not be PBXSourceTree.Group"); return AddFileImpl (path, projectPath, sourceTree, false); } public string AddFolderReference (string path, string projectPath) { return AddFileImpl (path, projectPath, PBXSourceTree.Source, true); } // sourceTree must not be PBXSourceTree.Group public string AddFolderReference (string path, string projectPath, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception ("sourceTree must not be PBXSourceTree.Group"); return AddFileImpl (path, projectPath, sourceTree, true); } private void AddBuildFileImpl (string targetGuid, string fileGuid, bool weak, string compileFlags) { PBXNativeTargetData target = nativeTargets [targetGuid]; PBXFileReferenceData fileRef = FileRefsGet (fileGuid); string ext = Path.GetExtension (fileRef.path); if (FileTypeUtils.IsBuildable (ext, fileRef.isFolderReference) && BuildFilesGetForSourceFile (targetGuid, fileGuid) == null) { PBXBuildFileData buildFile = PBXBuildFileData.CreateFromFile (fileGuid, weak, compileFlags); BuildFilesAdd (targetGuid, buildFile); BuildSectionAny (target, ext, fileRef.isFolderReference).files.AddGUID (buildFile.guid); } } public void AddFileToBuild (string targetGuid, string fileGuid) { AddBuildFileImpl (targetGuid, fileGuid, false, null); } public void AddFileToBuildWithFlags (string targetGuid, string fileGuid, string compileFlags) { AddBuildFileImpl (targetGuid, fileGuid, false, compileFlags); } // returns null on error // FIXME: at the moment returns all flags as the first element of the array public List<string> GetCompileFlagsForFile (string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile (targetGuid, fileGuid); if (buildFile == null) return null; if (buildFile.compileFlags == null) return new List<string> (); return new List<string>{ buildFile.compileFlags }; } public void SetCompileFlagsForFile (string targetGuid, string fileGuid, List<string> compileFlags) { var buildFile = BuildFilesGetForSourceFile (targetGuid, fileGuid); if (buildFile == null) return; if (compileFlags == null) buildFile.compileFlags = null; else buildFile.compileFlags = string.Join (" ", compileFlags.ToArray ()); } public void AddAssetTagForFile (string targetGuid, string fileGuid, string tag) { var buildFile = BuildFilesGetForSourceFile (targetGuid, fileGuid); if (buildFile == null) return; if (!buildFile.assetTags.Contains (tag)) buildFile.assetTags.Add (tag); if (!project.project.knownAssetTags.Contains (tag)) project.project.knownAssetTags.Add (tag); } public void RemoveAssetTagForFile (string targetGuid, string fileGuid, string tag) { var buildFile = BuildFilesGetForSourceFile (targetGuid, fileGuid); if (buildFile == null) return; buildFile.assetTags.Remove (tag); // remove from known tags if this was the last one foreach (var buildFile2 in BuildFilesGetAll()) { if (buildFile2.assetTags.Contains (tag)) return; } project.project.knownAssetTags.Remove (tag); } public void AddAssetTagToDefaultInstall (string targetGuid, string tag) { if (!project.project.knownAssetTags.Contains (tag)) return; AddBuildProperty (targetGuid, "ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS", tag); } public void RemoveAssetTagFromDefaultInstall (string targetGuid, string tag) { UpdateBuildProperty (targetGuid, "ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS", null, new string[]{ tag }); } public void RemoveAssetTag (string tag) { foreach (var buildFile in BuildFilesGetAll()) buildFile.assetTags.Remove (tag); foreach (var targetGuid in nativeTargets.GetGuids()) RemoveAssetTagFromDefaultInstall (targetGuid, tag); project.project.knownAssetTags.Remove (tag); } public bool ContainsFileByRealPath (string path) { return FindFileGuidByRealPath (path) != null; } // sourceTree must not be PBXSourceTree.Group public bool ContainsFileByRealPath (string path, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception ("sourceTree must not be PBXSourceTree.Group"); return FindFileGuidByRealPath (path, sourceTree) != null; } public bool ContainsFileByProjectPath (string path) { return FindFileGuidByProjectPath (path) != null; } public bool HasFramework (string framework) { return ContainsFileByRealPath ("System/Library/Frameworks/" + framework); } /// The framework must be specified with the '.framework' extension public void AddFrameworkToProject (string targetGuid, string framework, bool weak) { string fileGuid = AddFile ("System/Library/Frameworks/" + framework, "Frameworks/" + framework, PBXSourceTree.Sdk); AddBuildFileImpl (targetGuid, fileGuid, weak, null); } /// The framework must be specified with the '.framework' extension // FIXME: targetGuid is ignored at the moment public void RemoveFrameworkFromProject (string targetGuid, string framework) { string fileGuid = FindFileGuidByRealPath ("System/Library/Frameworks/" + framework); if (fileGuid != null) RemoveFile (fileGuid); } // sourceTree must not be PBXSourceTree.Group public string FindFileGuidByRealPath (string path, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception ("sourceTree must not be PBXSourceTree.Group"); path = Utils.FixSlashesInPath (path); var fileRef = FileRefsGetByRealPath (path, sourceTree); if (fileRef != null) return fileRef.guid; return null; } public string FindFileGuidByRealPath (string path) { path = Utils.FixSlashesInPath (path); foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees()) { string res = FindFileGuidByRealPath (path, tree); if (res != null) return res; } return null; } public string FindFileGuidByProjectPath (string path) { path = Utils.FixSlashesInPath (path); var fileRef = FileRefsGetByProjectPath (path); if (fileRef != null) return fileRef.guid; return null; } public void RemoveFileFromBuild (string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile (targetGuid, fileGuid); if (buildFile == null) return; BuildFilesRemove (targetGuid, fileGuid); string buildGuid = buildFile.guid; if (buildGuid != null) { foreach (var section in sources.GetEntries()) section.Value.files.RemoveGUID (buildGuid); foreach (var section in resources.GetEntries()) section.Value.files.RemoveGUID (buildGuid); foreach (var section in copyFiles.GetEntries()) section.Value.files.RemoveGUID (buildGuid); foreach (var section in frameworks.GetEntries()) section.Value.files.RemoveGUID (buildGuid); } } public void RemoveFile (string fileGuid) { if (fileGuid == null) return; // remove from parent PBXGroupData parent = GroupsGetByChild (fileGuid); if (parent != null) parent.children.RemoveGUID (fileGuid); RemoveGroupIfEmpty (parent); // remove actual file foreach (var target in nativeTargets.GetEntries()) RemoveFileFromBuild (target.Value.guid, fileGuid); FileRefsRemove (fileGuid); } void RemoveGroupIfEmpty (PBXGroupData gr) { if (gr.children.Count == 0 && gr != GroupsGetMainGroup ()) { // remove from parent PBXGroupData parent = GroupsGetByChild (gr.guid); parent.children.RemoveGUID (gr.guid); RemoveGroupIfEmpty (parent); // remove actual group GroupsRemove (gr.guid); } } private void RemoveGroupChildrenRecursive (PBXGroupData parent) { List<string> children = new List<string> (parent.children); parent.children.Clear (); foreach (string guid in children) { PBXFileReferenceData file = FileRefsGet (guid); if (file != null) { foreach (var target in nativeTargets.GetEntries()) RemoveFileFromBuild (target.Value.guid, guid); FileRefsRemove (guid); continue; } PBXGroupData gr = GroupsGet (guid); if (gr != null) { RemoveGroupChildrenRecursive (gr); GroupsRemove (gr.guid); continue; } } } internal void RemoveFilesByProjectPathRecursive (string projectPath) { projectPath = Utils.FixSlashesInPath (projectPath); PBXGroupData gr = GroupsGetByProjectPath (projectPath); if (gr == null) return; RemoveGroupChildrenRecursive (gr); RemoveGroupIfEmpty (gr); } // Returns null on error internal List<string> GetGroupChildrenFiles (string projectPath) { projectPath = Utils.FixSlashesInPath (projectPath); PBXGroupData gr = GroupsGetByProjectPath (projectPath); if (gr == null) return null; var res = new List<string> (); foreach (var guid in gr.children) { var fileRef = FileRefsGet (guid); if (fileRef != null) res.Add (fileRef.name); } return res; } private PBXGroupData GetPBXGroupChildByName (PBXGroupData group, string name) { foreach (string guid in group.children) { var gr = GroupsGet (guid); if (gr != null && gr.name == name) return gr; } return null; } /// Creates source group identified by sourceGroup, if needed, and returns it. /// If sourceGroup is empty or null, root group is returned private PBXGroupData CreateSourceGroup (string sourceGroup) { sourceGroup = Utils.FixSlashesInPath (sourceGroup); if (sourceGroup == null || sourceGroup == "") return GroupsGetMainGroup (); PBXGroupData gr = GroupsGetByProjectPath (sourceGroup); if (gr != null) return gr; // the group does not exist -- create new gr = GroupsGetMainGroup (); var elements = PBX.Utils.SplitPath (sourceGroup); string projectPath = null; foreach (string pathEl in elements) { if (projectPath == null) projectPath = pathEl; else projectPath += "/" + pathEl; PBXGroupData child = GetPBXGroupChildByName (gr, pathEl); if (child != null) gr = child; else { PBXGroupData newGroup = PBXGroupData.Create (pathEl, pathEl, PBXSourceTree.Group); gr.children.AddGUID (newGroup.guid); GroupsAdd (projectPath, gr, newGroup); gr = newGroup; } } return gr; } // sourceTree must not be PBXSourceTree.Group public void AddExternalProjectDependency (string path, string projectPath, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception ("sourceTree must not be PBXSourceTree.Group"); path = Utils.FixSlashesInPath (path); projectPath = Utils.FixSlashesInPath (projectPath); // note: we are duplicating products group for the project reference. Otherwise Xcode crashes. PBXGroupData productGroup = PBXGroupData.CreateRelative ("Products"); GroupsAddDuplicate (productGroup); // don't use GroupsAdd here PBXFileReferenceData fileRef = PBXFileReferenceData.CreateFromFile (path, Path.GetFileName (projectPath), sourceTree); FileRefsAdd (path, projectPath, null, fileRef); CreateSourceGroup (Utils.GetDirectoryFromPath (projectPath)).children.AddGUID (fileRef.guid); project.project.AddReference (productGroup.guid, fileRef.guid); } /** This function must be called only after the project the library is in has been added as a dependency via AddExternalProjectDependency. projectPath must be the same as the 'path' parameter passed to the AddExternalProjectDependency. remoteFileGuid must be the guid of the referenced file as specified in PBXFileReference section of the external project TODO: what. is remoteInfo entry in PBXContainerItemProxy? Is in referenced project name or referenced library name without extension? */ public void AddExternalLibraryDependency (string targetGuid, string filename, string remoteFileGuid, string projectPath, string remoteInfo) { PBXNativeTargetData target = nativeTargets [targetGuid]; filename = Utils.FixSlashesInPath (filename); projectPath = Utils.FixSlashesInPath (projectPath); // find the products group to put the new library in string projectGuid = FindFileGuidByRealPath (projectPath); if (projectGuid == null) throw new Exception ("No such project"); string productsGroupGuid = null; foreach (var proj in project.project.projectReferences) { if (proj.projectRef == projectGuid) { productsGroupGuid = proj.group; break; } } if (productsGroupGuid == null) throw new Exception ("Malformed project: no project in project references"); PBXGroupData productGroup = GroupsGet (productsGroupGuid); // verify file extension string ext = Path.GetExtension (filename); if (!FileTypeUtils.IsBuildableFile (ext)) throw new Exception ("Wrong file extension"); // create ContainerItemProxy object var container = PBXContainerItemProxyData.Create (projectGuid, "2", remoteFileGuid, remoteInfo); containerItems.AddEntry (container); // create a reference and build file for the library string typeName = FileTypeUtils.GetTypeName (ext); var libRef = PBXReferenceProxyData.Create (filename, typeName, container.guid, "BUILT_PRODUCTS_DIR"); references.AddEntry (libRef); PBXBuildFileData libBuildFile = PBXBuildFileData.CreateFromFile (libRef.guid, false, null); BuildFilesAdd (targetGuid, libBuildFile); BuildSectionAny (target, ext, false).files.AddGUID (libBuildFile.guid); // add to products folder productGroup.children.AddGUID (libRef.guid); } private void SetDefaultAppExtensionReleaseBuildFlags (XCBuildConfigurationData config, string infoPlistPath) { config.AddProperty ("ALWAYS_SEARCH_USER_PATHS", "NO"); config.AddProperty ("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x"); config.AddProperty ("CLANG_CXX_LIBRARY", "libc++"); config.AddProperty ("CLANG_ENABLE_MODULES", "YES"); config.AddProperty ("CLANG_ENABLE_OBJC_ARC", "YES"); config.AddProperty ("CLANG_WARN_BOOL_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_CONSTANT_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR"); config.AddProperty ("CLANG_WARN_EMPTY_BODY", "YES"); config.AddProperty ("CLANG_WARN_ENUM_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_INT_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR"); config.AddProperty ("CLANG_WARN_UNREACHABLE_CODE", "YES"); config.AddProperty ("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES"); config.AddProperty ("COPY_PHASE_STRIP", "YES"); config.AddProperty ("ENABLE_NS_ASSERTIONS", "NO"); config.AddProperty ("ENABLE_STRICT_OBJC_MSGSEND", "YES"); config.AddProperty ("GCC_C_LANGUAGE_STANDARD", "gnu99"); config.AddProperty ("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES"); config.AddProperty ("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR"); config.AddProperty ("GCC_WARN_UNDECLARED_SELECTOR", "YES"); config.AddProperty ("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE"); config.AddProperty ("GCC_WARN_UNUSED_FUNCTION", "YES"); config.AddProperty ("INFOPLIST_FILE", infoPlistPath); config.AddProperty ("IPHONEOS_DEPLOYMENT_TARGET", "8.0"); config.AddProperty ("LD_RUNPATH_SEARCH_PATHS", "$(inherited)"); config.AddProperty ("LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks"); config.AddProperty ("LD_RUNPATH_SEARCH_PATHS", "@executable_path/../../Frameworks"); config.AddProperty ("MTL_ENABLE_DEBUG_INFO", "NO"); config.AddProperty ("PRODUCT_NAME", "$(TARGET_NAME)"); config.AddProperty ("SKIP_INSTALL", "YES"); config.AddProperty ("VALIDATE_PRODUCT", "YES"); } private void SetDefaultAppExtensionDebugBuildFlags (XCBuildConfigurationData config, string infoPlistPath) { config.AddProperty ("ALWAYS_SEARCH_USER_PATHS", "NO"); config.AddProperty ("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x"); config.AddProperty ("CLANG_CXX_LIBRARY", "libc++"); config.AddProperty ("CLANG_ENABLE_MODULES", "YES"); config.AddProperty ("CLANG_ENABLE_OBJC_ARC", "YES"); config.AddProperty ("CLANG_WARN_BOOL_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_CONSTANT_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR"); config.AddProperty ("CLANG_WARN_EMPTY_BODY", "YES"); config.AddProperty ("CLANG_WARN_ENUM_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_INT_CONVERSION", "YES"); config.AddProperty ("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR"); config.AddProperty ("CLANG_WARN_UNREACHABLE_CODE", "YES"); config.AddProperty ("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES"); config.AddProperty ("COPY_PHASE_STRIP", "NO"); config.AddProperty ("ENABLE_STRICT_OBJC_MSGSEND", "YES"); config.AddProperty ("GCC_C_LANGUAGE_STANDARD", "gnu99"); config.AddProperty ("GCC_DYNAMIC_NO_PIC", "NO"); config.AddProperty ("GCC_OPTIMIZATION_LEVEL", "0"); config.AddProperty ("GCC_PREPROCESSOR_DEFINITIONS", "DEBUG=1"); config.AddProperty ("GCC_PREPROCESSOR_DEFINITIONS", "$(inherited)"); config.AddProperty ("GCC_SYMBOLS_PRIVATE_EXTERN", "NO"); config.AddProperty ("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES"); config.AddProperty ("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR"); config.AddProperty ("GCC_WARN_UNDECLARED_SELECTOR", "YES"); config.AddProperty ("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE"); config.AddProperty ("GCC_WARN_UNUSED_FUNCTION", "YES"); config.AddProperty ("INFOPLIST_FILE", infoPlistPath); config.AddProperty ("IPHONEOS_DEPLOYMENT_TARGET", "8.0"); config.AddProperty ("LD_RUNPATH_SEARCH_PATHS", "$(inherited)"); config.AddProperty ("LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks"); config.AddProperty ("LD_RUNPATH_SEARCH_PATHS", "@executable_path/../../Frameworks"); config.AddProperty ("MTL_ENABLE_DEBUG_INFO", "YES"); config.AddProperty ("ONLY_ACTIVE_ARCH", "YES"); config.AddProperty ("PRODUCT_NAME", "$(TARGET_NAME)"); config.AddProperty ("SKIP_INSTALL", "YES"); } internal PBXNativeTargetData CreateNewTarget (string name, string ext, string type) { // create build configurations var releaseBuildConfig = XCBuildConfigurationData.Create ("Release"); buildConfigs.AddEntry (releaseBuildConfig); var debugBuildConfig = XCBuildConfigurationData.Create ("Debug"); buildConfigs.AddEntry (debugBuildConfig); var buildConfigList = XCConfigurationListData.Create (); configs.AddEntry (buildConfigList); buildConfigList.buildConfigs.AddGUID (releaseBuildConfig.guid); buildConfigList.buildConfigs.AddGUID (debugBuildConfig.guid); // create build file reference string fullName = name + ext; var productFileRef = AddFile (fullName, "Products/" + fullName, PBXSourceTree.Build); var newTarget = PBXNativeTargetData.Create (name, productFileRef, type, buildConfigList.guid); nativeTargets.AddEntry (newTarget); project.project.targets.Add (newTarget.guid); return newTarget; } // Returns the guid of the new target internal string AddAppExtension (string mainTarget, string name, string infoPlistPath) { string ext = ".appex"; var newTarget = CreateNewTarget (name, ext, "com.apple.product-type.app-extension"); SetDefaultAppExtensionReleaseBuildFlags (buildConfigs [BuildConfigByName (newTarget.guid, "Release")], infoPlistPath); SetDefaultAppExtensionDebugBuildFlags (buildConfigs [BuildConfigByName (newTarget.guid, "Debug")], infoPlistPath); var sourcesBuildPhase = PBXSourcesBuildPhaseData.Create (); sources.AddEntry (sourcesBuildPhase); newTarget.phases.AddGUID (sourcesBuildPhase.guid); var resourcesBuildPhase = PBXResourcesBuildPhaseData.Create (); resources.AddEntry (resourcesBuildPhase); newTarget.phases.AddGUID (resourcesBuildPhase.guid); var frameworksBuildPhase = PBXFrameworksBuildPhaseData.Create (); frameworks.AddEntry (frameworksBuildPhase); newTarget.phases.AddGUID (frameworksBuildPhase.guid); var copyFilesBuildPhase = PBXCopyFilesBuildPhaseData.Create ("Embed App Extensions", "13"); copyFiles.AddEntry (copyFilesBuildPhase); nativeTargets [mainTarget].phases.AddGUID (copyFilesBuildPhase.guid); var containerProxy = PBXContainerItemProxyData.Create (project.project.guid, "1", newTarget.guid, name); containerItems.AddEntry (containerProxy); var targetDependency = PBXTargetDependencyData.Create (newTarget.guid, containerProxy.guid); targetDependencies.AddEntry (targetDependency); nativeTargets [mainTarget].dependencies.AddGUID (targetDependency.guid); var buildAppCopy = PBXBuildFileData.CreateFromFile (FindFileGuidByProjectPath ("Products/" + name + ext), false, ""); BuildFilesAdd (mainTarget, buildAppCopy); copyFilesBuildPhase.files.AddGUID (buildAppCopy.guid); AddFile (infoPlistPath, name + "/Supporting Files/Info.plist", PBXSourceTree.Source); return newTarget.guid; } public string BuildConfigByName (string targetGuid, string name) { PBXNativeTargetData target = nativeTargets [targetGuid]; foreach (string guid in configs[target.buildConfigList].buildConfigs) { var buildConfig = buildConfigs [guid]; if (buildConfig != null && buildConfig.name == name) return buildConfig.guid; } return null; } string GetConfigListForTarget (string targetGuid) { if (targetGuid == project.project.guid) return project.project.buildConfigList; else return nativeTargets [targetGuid].buildConfigList; } // Adds an item to a build property that contains a value list. Duplicate build properties // are ignored. Values for name "LIBRARY_SEARCH_PATHS" are quoted if they contain spaces. // targetGuid may refer to PBXProject object public void AddBuildProperty (string targetGuid, string name, string value) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) AddBuildPropertyForConfig (guid, name, value); } public void AddBuildProperty (IEnumerable<string> targetGuids, string name, string value) { foreach (string t in targetGuids) AddBuildProperty (t, name, value); } public void AddBuildPropertyForConfig (string configGuid, string name, string value) { buildConfigs [configGuid].AddProperty (name, value); } public void AddBuildPropertyForConfig (IEnumerable<string> configGuids, string name, string value) { foreach (string guid in configGuids) AddBuildPropertyForConfig (guid, name, value); } // targetGuid may refer to PBXProject object public void SetBuildProperty (string targetGuid, string name, string value) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) SetBuildPropertyForConfig (guid, name, value); } public void SetBuildProperty (IEnumerable<string> targetGuids, string name, string value) { foreach (string t in targetGuids) SetBuildProperty (t, name, value); } public void SetBuildPropertyForConfig (string configGuid, string name, string value) { buildConfigs [configGuid].SetProperty (name, value); } public void SetBuildPropertyForConfig (IEnumerable<string> configGuids, string name, string value) { foreach (string guid in configGuids) SetBuildPropertyForConfig (guid, name, value); } internal void RemoveBuildProperty (string targetGuid, string name) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) RemoveBuildPropertyForConfig (guid, name); } internal void RemoveBuildProperty (IEnumerable<string> targetGuids, string name) { foreach (string t in targetGuids) RemoveBuildProperty (t, name); } internal void RemoveBuildPropertyForConfig (string configGuid, string name) { buildConfigs [configGuid].RemoveProperty (name); } internal void RemoveBuildPropertyForConfig (IEnumerable<string> configGuids, string name) { foreach (string guid in configGuids) RemoveBuildPropertyForConfig (guid, name); } /// Interprets the value of the given property as a set of space-delimited strings, then /// removes strings equal to items to removeValues and adds strings in addValues. public void UpdateBuildProperty (string targetGuid, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) UpdateBuildPropertyForConfig (guid, name, addValues, removeValues); } public void UpdateBuildProperty (IEnumerable<string> targetGuids, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string t in targetGuids) UpdateBuildProperty (t, name, addValues, removeValues); } public void UpdateBuildPropertyForConfig (string configGuid, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { var config = buildConfigs [configGuid]; if (config != null) { if (removeValues != null) foreach (var v in removeValues) config.RemovePropertyValue (name, v); if (addValues != null) foreach (var v in addValues) config.AddProperty (name, v); } } public void UpdateBuildPropertyForConfig (IEnumerable<string> configGuids, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string guid in configGuids) UpdateBuildProperty (guid, name, addValues, removeValues); } public void ReadFromFile (string path) { ReadFromString (File.ReadAllText (path)); } public void ReadFromString (string src) { TextReader sr = new StringReader (src); ReadFromStream (sr); } public void ReadFromStream (TextReader sr) { m_Data.ReadFromStream (sr); } public void WriteToFile (string path) { File.WriteAllText (path, WriteToString ()); } public void WriteToStream (TextWriter sw) { sw.Write (WriteToString ()); } public string WriteToString () { return m_Data.WriteToString (); } } } // namespace ForieroEditor.Platforms.iOS.Xcode
// // Created by Ian Copland on 2015-11-10 // // The MIT License (MIT) // // Copyright (c) 2015 Tag Games Limited // // 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 UnityEngine; using System.Collections; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; namespace SdkCore { /// <summary> /// <para>Provides a means to make both GET and POST requests to the given /// web-server. Requests can be both HTTP and HTTPS.</para> /// /// <para>This is thread-safe.</para> /// </summary> public sealed class HttpSystem { private TaskScheduler m_taskScheduler; /// <summary> /// Initializes a new instance of the HTTP system with the given task /// scheduler. /// </summary> /// /// <param name="taskScheduler">The task scheduler.</param> public HttpSystem(TaskScheduler taskScheduler) { ReleaseAssert.IsTrue(taskScheduler != null, "The task scheduler in a HTTP request system must not be null."); m_taskScheduler = taskScheduler; } /// <summary> /// Makes a HTTP GET request with the given request object. This is /// performed asynchronously, with the callback block run on a background /// thread. /// </summary> /// /// <param name="request">The GET HTTP request.</param> /// <param name="callback">The callback which will provide the response from the server. /// The callback will be made on a background thread.</param> public void SendRequest(HttpGetRequest request, Action<HttpGetRequest, HttpResponse> callback) { ReleaseAssert.IsTrue(request != null, "The HTTP GET request must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); SendRequest(request.Url, request.Headers, null, (HttpResponse response) => { callback(request, response); }); } /// <summary> /// Makes a HTTP POST request with the given request object. This is /// performed asynchronously, with the callback block run on a background /// thread. /// </summary> /// /// <param name="request">The POST HTTP request.</param> /// <param name="callback">The callback which will provide the response from the server. /// The callback will be made on a background thread.</param> public void SendRequest(HttpPostRequest request, Action<HttpPostRequest, HttpResponse> callback) { ReleaseAssert.IsTrue(request != null, "The HTTP POST request must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); var headers = new Dictionary<string, string>(request.Headers); if (request.ContentType != null) { headers.Add("Content-Type", request.ContentType); } SendRequest(request.Url, headers, request.Body, (HttpResponse response) => { callback(request, response); }); } /// <summary> /// Provides the means to send both GET and POST requests depending on the /// input data. /// </summary> /// /// <param name="url">The URL that the request is targetting.</param> /// <param name="headers">The headers for the HTTP request.</param> /// <param name="body">The body of the request. If null, a GET request will be sent.</param> /// <param name="callback">The callback providing the response from the server.</param> private void SendRequest(String url, IDictionary<string, string> headers, byte[] body, Action<HttpResponse> callback) { ReleaseAssert.IsTrue(url != null, "The URL must not be null when sending a request."); ReleaseAssert.IsTrue(headers != null, "The headers must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); // Unity's WWW class works with the Dictionary concrete class rather than the abstract // IDictionary. Rather than cast a copy is made so we can be sure other dictionary types // will work. Dictionary<string, string> headersConcreteDict = new Dictionary<string, string>(headers); m_taskScheduler.ScheduleMainThreadTask(() => { var www = new WWW(url, body, headersConcreteDict); m_taskScheduler.StartCoroutine(ProcessRequest(www, callback)); }); } /// <summary> /// <para>The coroutine for processing the HTTP request. This will yield until the /// request has completed then parse the information required by a HTTP response /// from the WWW object.</para> /// </summary> /// /// <returns>The coroutine enumerator.</returns> /// /// <param name="www">The WWW object.</param> /// <param name="callback">The callback providing the response from the server.</param> private IEnumerator ProcessRequest(WWW www, Action<HttpResponse> callback) { ReleaseAssert.IsTrue(www != null, "The WWW must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); yield return www; HttpResponseDesc desc = null; if (string.IsNullOrEmpty(www.error)) { ReleaseAssert.IsTrue(www.responseHeaders != null, "A successful HTTP response must have a headers object."); desc = new HttpResponseDesc(HttpResult.Success); desc.Headers = new Dictionary<string, string>(www.responseHeaders); if (www.bytes != null) { desc.Body = www.bytes; } var httpStatus = www.responseHeaders ["STATUS"]; ReleaseAssert.IsTrue(!string.IsNullOrEmpty(httpStatus), "A successful HTTP response must have a HTTP status value in the header."); desc.HttpResponseCode = ParseHttpStatus(httpStatus); } else { var bytes = www.bytes; int httpResponseCode = 0; #if UNITY_IPHONE && !UNITY_EDITOR var text = www.text; if ( !string.IsNullOrEmpty(text) ) { var bodyDictionary = Json.Deserialize(text) as Dictionary<string, object>; if (bodyDictionary != null && bodyDictionary.ContainsKey ("HttpCode")) { httpResponseCode = Convert.ToInt32(bodyDictionary ["HttpCode"]); bytes = Encoding.UTF8.GetBytes(text); } } #else httpResponseCode = ParseHttpError(www.error); #endif if (httpResponseCode != 0) { desc = new HttpResponseDesc(HttpResult.Success); desc.Headers = new Dictionary<string, string>(www.responseHeaders); if (www.bytes != null) { desc.Body = www.bytes; } desc.HttpResponseCode = httpResponseCode; } else { desc = new HttpResponseDesc(HttpResult.CouldNotConnect); } } HttpResponse response = new HttpResponse(desc); m_taskScheduler.ScheduleBackgroundTask(() => { callback(response); }); } /// <summary> /// Parses the HTTP response code from the given HTTP STATUS string. The string should /// be in the format 'HTTP/X YYY...' or 'HTTP/X.X YYY...' where YYY is the response /// code. /// </summary> /// /// <returns>The response code.</returns> /// /// <param name="httpStatus">The HTTP status string in the format 'HTTP/X YYY...' /// or 'HTTP/X.X YYY...'.</param> private int ParseHttpStatus(string httpStatus) { ReleaseAssert.IsTrue(httpStatus != null, "The HTTP status string must not be null when parsing a response code."); var regex = new Regex("[a-zA-Z]*\\/\\d+(\\.\\d)?\\s(?<httpResponseCode>\\d+)\\s"); var match = regex.Match(httpStatus); ReleaseAssert.IsTrue(match.Groups.Count == 3, "There must be exactly 3 match groups when using a regex on a HTTP status."); var responseCodeString = match.Groups ["httpResponseCode"].Value; ReleaseAssert.IsTrue(responseCodeString != null, "The response code string cannot be null when using a regex on a HTTP status."); return Int32.Parse(responseCodeString); } /// <summary> /// Parses the HTTP response code from the given HTTP error string. The string should /// be in the format 'XXX ...' where XXX is the HTTP response code. /// </summary> /// /// <returns>The response code parsed from the error, or 0 if there wasn't one.</returns> /// /// <param name="httpError">The HTTP error string.</param> private int ParseHttpError(string httpError) { ReleaseAssert.IsTrue(httpError != null, "The HTTP error string must not be null when parsing a response code."); var regex = new Regex("(?<httpResponseCode>[0-9][0-9][0-9])\\s"); if (regex.IsMatch(httpError)) { var match = regex.Match(httpError); ReleaseAssert.IsTrue(match.Groups.Count == 2, "There must be exactly 2 match groups when using a regex on a HTTP error."); var responseCodeString = match.Groups ["httpResponseCode"].Value; ReleaseAssert.IsTrue(responseCodeString != null, "The response code string cannot be null when using a regex on a HTTP error."); return Int32.Parse(responseCodeString); } return 0; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagr = Google.Api.Gax.ResourceNames; using gccv = Google.Cloud.ContactCenterInsights.V1; namespace Google.Cloud.ContactCenterInsights.V1 { public partial class CalculateStatsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Location"/> resource name property. /// </summary> public gagr::LocationName LocationAsLocationName { get => string.IsNullOrEmpty(Location) ? null : gagr::LocationName.Parse(Location, allowUnparsed: true); set => Location = value?.ToString() ?? ""; } } public partial class CreateAnalysisOperationMetadata { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Conversation"/> resource name property. /// </summary> public ConversationName ConversationAsConversationName { get => string.IsNullOrEmpty(Conversation) ? null : ConversationName.Parse(Conversation, allowUnparsed: true); set => Conversation = value?.ToString() ?? ""; } } public partial class CreateConversationRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListConversationsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetConversationRequest { /// <summary> /// <see cref="gccv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::ConversationName ConversationName { get => string.IsNullOrEmpty(Name) ? null : gccv::ConversationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteConversationRequest { /// <summary> /// <see cref="gccv::ConversationName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::ConversationName ConversationName { get => string.IsNullOrEmpty(Name) ? null : gccv::ConversationName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateAnalysisRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListAnalysesRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetAnalysisRequest { /// <summary> /// <see cref="gccv::AnalysisName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::AnalysisName AnalysisName { get => string.IsNullOrEmpty(Name) ? null : gccv::AnalysisName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteAnalysisRequest { /// <summary> /// <see cref="gccv::AnalysisName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::AnalysisName AnalysisName { get => string.IsNullOrEmpty(Name) ? null : gccv::AnalysisName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ExportInsightsDataRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CreateIssueModelRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListIssueModelsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetIssueModelRequest { /// <summary> /// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::IssueModelName IssueModelName { get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteIssueModelRequest { /// <summary> /// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::IssueModelName IssueModelName { get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeployIssueModelRequest { /// <summary> /// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::IssueModelName IssueModelName { get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class UndeployIssueModelRequest { /// <summary> /// <see cref="gccv::IssueModelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::IssueModelName IssueModelName { get => string.IsNullOrEmpty(Name) ? null : gccv::IssueModelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetIssueRequest { /// <summary> /// <see cref="gccv::IssueName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::IssueName IssueName { get => string.IsNullOrEmpty(Name) ? null : gccv::IssueName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListIssuesRequest { /// <summary> /// <see cref="IssueModelName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public IssueModelName ParentAsIssueModelName { get => string.IsNullOrEmpty(Parent) ? null : IssueModelName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CalculateIssueModelStatsRequest { /// <summary> /// <see cref="IssueModelName"/>-typed view over the <see cref="IssueModel"/> resource name property. /// </summary> public IssueModelName IssueModelAsIssueModelName { get => string.IsNullOrEmpty(IssueModel) ? null : IssueModelName.Parse(IssueModel, allowUnparsed: true); set => IssueModel = value?.ToString() ?? ""; } } public partial class CreatePhraseMatcherRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListPhraseMatchersRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetPhraseMatcherRequest { /// <summary> /// <see cref="gccv::PhraseMatcherName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::PhraseMatcherName PhraseMatcherName { get => string.IsNullOrEmpty(Name) ? null : gccv::PhraseMatcherName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeletePhraseMatcherRequest { /// <summary> /// <see cref="gccv::PhraseMatcherName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::PhraseMatcherName PhraseMatcherName { get => string.IsNullOrEmpty(Name) ? null : gccv::PhraseMatcherName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetSettingsRequest { /// <summary> /// <see cref="gccv::SettingsName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::SettingsName SettingsName { get => string.IsNullOrEmpty(Name) ? null : gccv::SettingsName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ namespace System.Data.SqlClient { /// <devdoc> Class of variables for the Tds connection. /// </devdoc> internal static class TdsEnums { // internal tdsparser constants public const string SQL_PROVIDER_NAME = Common.DbConnectionStringDefaults.ApplicationName; public static readonly Decimal SQL_SMALL_MONEY_MIN = new Decimal(-214748.3648); public static readonly Decimal SQL_SMALL_MONEY_MAX = new Decimal(214748.3647); // HACK!!! // Constant for SqlDbType.SmallVarBinary... store internal variable here instead of on // SqlDbType so that it is not surfaced to the user!!! Related to dtc and the fact that // the TransactionManager TDS stream is the only token left that uses VarBinarys instead of // BigVarBinarys. public const SqlDbType SmallVarBinary = (SqlDbType)(SqlDbType.Variant) + 1; // network protocol string constants public const string TCP = "tcp"; public const string NP = "np"; public const string RPC = "rpc"; public const string BV = "bv"; public const string ADSP = "adsp"; public const string SPX = "spx"; public const string VIA = "via"; public const string LPC = "lpc"; // network function string contants public const string INIT_SSPI_PACKAGE = "InitSSPIPackage"; public const string INIT_SESSION = "InitSession"; public const string CONNECTION_GET_SVR_USER = "ConnectionGetSvrUser"; public const string GEN_CLIENT_CONTEXT = "GenClientContext"; // tdsparser packet handling constants public const byte SOFTFLUSH = 0; public const byte HARDFLUSH = 1; public const byte IGNORE = 2; // header constants public const int HEADER_LEN = 8; public const int HEADER_LEN_FIELD_OFFSET = 2; public const int YUKON_HEADER_LEN = 12; //Yukon headers also include a MARS session id public const int MARS_ID_OFFSET = 8; public const int HEADERTYPE_QNOTIFICATION = 1; public const int HEADERTYPE_MARS = 2; public const int HEADERTYPE_TRACE = 3; // other various constants public const int SUCCEED = 1; public const int FAIL = 0; public const short TYPE_SIZE_LIMIT = 8000; public const int MIN_PACKET_SIZE = 512; // Login packet can be no greater than 4k until server sends us env-change // increasing packet size. public const int DEFAULT_LOGIN_PACKET_SIZE = 4096; public const int MAX_PRELOGIN_PAYLOAD_LENGTH = 1024; public const int MAX_PACKET_SIZE = 32768; public const int MAX_SERVER_USER_NAME = 256; // obtained from luxor // Severity 0 - 10 indicates informational (non-error) messages // Severity 11 - 16 indicates errors that can be corrected by user (syntax errors, etc...) // Severity 17 - 19 indicates failure due to insufficient resources in the server // (max locks exceeded, not enough memory, other internal server limits reached, etc..) // Severity 20 - 25 Severe problems with the server, connection terminated. public const byte MIN_ERROR_CLASS = 11; // webdata 100667: This should actually be 11 public const byte MAX_USER_CORRECTABLE_ERROR_CLASS = 16; public const byte FATAL_ERROR_CLASS = 20; // Message types public const byte MT_SQL = 1; // SQL command batch public const byte MT_LOGIN = 2; // Login message for pre-Sphinx (before version 7.0) public const byte MT_RPC = 3; // Remote procedure call public const byte MT_TOKENS = 4; // Table response data stream public const byte MT_BINARY = 5; // Unformatted binary response data (UNUSED) public const byte MT_ATTN = 6; // Attention (break) signal public const byte MT_BULK = 7; // Bulk load data public const byte MT_OPEN = 8; // Set up subchannel (UNUSED) public const byte MT_CLOSE = 9; // Close subchannel (UNUSED) public const byte MT_ERROR = 10; // Protocol error detected public const byte MT_ACK = 11; // Protocol acknowledgement (UNUSED) public const byte MT_ECHO = 12; // Echo data (UNUSED) public const byte MT_LOGOUT = 13; // Logout message (UNUSED) public const byte MT_TRANS = 14; // Transaction Manager Interface public const byte MT_OLEDB = 15; // ? (UNUSED) public const byte MT_LOGIN7 = 16; // Login message for Sphinx (version 7) or later public const byte MT_SSPI = 17; // SSPI message public const byte MT_PRELOGIN = 18; // Pre-login handshake // Message status bits public const byte ST_EOM = 0x1; // Packet is end-of-message public const byte ST_AACK = 0x2; // Packet acknowledges attention (server to client) public const byte ST_IGNORE = 0x2; // Ignore this event (client to server) public const byte ST_BATCH = 0x4; // Message is part of a batch. public const byte ST_RESET_CONNECTION = 0x8; // Exec sp_reset_connection prior to processing message public const byte ST_RESET_CONNECTION_PRESERVE_TRANSACTION = 0x10; // reset prior to processing, with preserving local tx // TDS control tokens public const byte SQLCOLFMT = 0xa1; public const byte SQLPROCID = 0x7c; public const byte SQLCOLNAME = 0xa0; public const byte SQLTABNAME = 0xa4; public const byte SQLCOLINFO = 0xa5; public const byte SQLALTNAME = 0xa7; public const byte SQLALTFMT = 0xa8; public const byte SQLERROR = 0xaa; public const byte SQLINFO = 0xab; public const byte SQLRETURNVALUE = 0xac; public const byte SQLRETURNSTATUS = 0x79; public const byte SQLRETURNTOK = 0xdb; public const byte SQLALTCONTROL = 0xaf; public const byte SQLROW = 0xd1; public const byte SQLNBCROW = 0xd2; // same as ROW with null-bit-compression support public const byte SQLALTROW = 0xd3; public const byte SQLDONE = 0xfd; public const byte SQLDONEPROC = 0xfe; public const byte SQLDONEINPROC = 0xff; public const byte SQLOFFSET = 0x78; public const byte SQLORDER = 0xa9; public const byte SQLDEBUG_CMD = 0x60; public const byte SQLLOGINACK = 0xad; public const byte SQLFEATUREEXTACK = 0xae; // TDS 7.4 - feature ack public const byte SQLSESSIONSTATE = 0xe4; // TDS 7.4 - connection resiliency session state public const byte SQLENVCHANGE = 0xe3; // Environment change notification public const byte SQLSECLEVEL = 0xed; // Security level token ??? public const byte SQLROWCRC = 0x39; // ROWCRC datastream??? public const byte SQLCOLMETADATA = 0x81; // Column metadata including name public const byte SQLALTMETADATA = 0x88; // Alt column metadata including name public const byte SQLSSPI = 0xed; // SSPI data // Environment change notification streams // TYPE on TDS ENVCHANGE token stream (from sql\ntdbms\include\odsapi.h) // public const byte ENV_DATABASE = 1; // Database changed public const byte ENV_LANG = 2; // Language changed public const byte ENV_CHARSET = 3; // Character set changed public const byte ENV_PACKETSIZE = 4; // Packet size changed public const byte ENV_LOCALEID = 5; // Unicode data sorting locale id public const byte ENV_COMPFLAGS = 6; // Unicode data sorting comparison flags public const byte ENV_COLLATION = 7; // SQL Collation // The following are environment change tokens valid for Yukon or later. public const byte ENV_BEGINTRAN = 8; // Transaction began public const byte ENV_COMMITTRAN = 9; // Transaction committed public const byte ENV_ROLLBACKTRAN = 10; // Transaction rolled back public const byte ENV_ENLISTDTC = 11; // Enlisted in Distributed Transaction public const byte ENV_DEFECTDTC = 12; // Defected from Distributed Transaction public const byte ENV_LOGSHIPNODE = 13; // Realtime Log shipping primary node public const byte ENV_PROMOTETRANSACTION = 15; // Promote Transaction public const byte ENV_TRANSACTIONMANAGERADDRESS = 16; // Transaction Manager Address public const byte ENV_TRANSACTIONENDED = 17; // Transaction Ended public const byte ENV_SPRESETCONNECTIONACK = 18; // SP_Reset_Connection ack public const byte ENV_USERINSTANCE = 19; // User Instance public const byte ENV_ROUTING = 20; // Routing (ROR) information public enum EnvChangeType : byte { ENVCHANGE_DATABASE = ENV_DATABASE, ENVCHANGE_LANG = ENV_LANG, ENVCHANGE_CHARSET = ENV_CHARSET, ENVCHANGE_PACKETSIZE = ENV_PACKETSIZE, ENVCHANGE_LOCALEID = ENV_LOCALEID, ENVCHANGE_COMPFLAGS = ENV_COMPFLAGS, ENVCHANGE_COLLATION = ENV_COLLATION, ENVCHANGE_BEGINTRAN = ENV_BEGINTRAN, ENVCHANGE_COMMITTRAN = ENV_COMMITTRAN, ENVCHANGE_ROLLBACKTRAN = ENV_ROLLBACKTRAN, ENVCHANGE_ENLISTDTC = ENV_ENLISTDTC, ENVCHANGE_DEFECTDTC = ENV_DEFECTDTC, ENVCHANGE_LOGSHIPNODE = ENV_LOGSHIPNODE, ENVCHANGE_PROMOTETRANSACTION = ENV_PROMOTETRANSACTION, ENVCHANGE_TRANSACTIONMANAGERADDRESS = ENV_TRANSACTIONMANAGERADDRESS, ENVCHANGE_TRANSACTIONENDED = ENV_TRANSACTIONENDED, ENVCHANGE_SPRESETCONNECTIONACK = ENV_SPRESETCONNECTIONACK, ENVCHANGE_USERINSTANCE = ENV_USERINSTANCE, ENVCHANGE_ROUTING = ENV_ROUTING } // done status stream bit masks public const int DONE_MORE = 0x0001; // more command results coming public const int DONE_ERROR = 0x0002; // error in command batch public const int DONE_INXACT = 0x0004; // transaction in progress public const int DONE_PROC = 0x0008; // done from stored proc public const int DONE_COUNT = 0x0010; // count in done info public const int DONE_ATTN = 0x0020; // oob ack public const int DONE_INPROC = 0x0040; // like DONE_PROC except proc had error public const int DONE_RPCINBATCH = 0x0080; // Done from RPC in batch public const int DONE_SRVERROR = 0x0100; // Severe error in which resultset should be discarded public const int DONE_FMTSENT = 0x8000; // fmt message sent, done_inproc req'd // Feature Extension public const byte FEATUREEXT_TERMINATOR = 0xFF; public const byte FEATUREEXT_SRECOVERY = 0x01; [Flags] public enum FeatureExtension : uint { None = 0, SessionRecovery = 1, } // Loginrec defines public const byte MAX_LOG_NAME = 30; // TDS 4.2 login rec max name length public const byte MAX_PROG_NAME = 10; // max length of loginrec progran name public const byte SEC_COMP_LEN = 8; // length of security compartments public const byte MAX_PK_LEN = 6; // max length of TDS packet size public const byte MAX_NIC_SIZE = 6; // The size of a MAC or client address public const byte SQLVARIANT_SIZE = 2; // size of the fixed portion of a sql variant (type, cbPropBytes) public const byte VERSION_SIZE = 4; // size of the tds version (4 unsigned bytes) public const int CLIENT_PROG_VER = 0x06000000; // Client interface version public const int YUKON_LOG_REC_FIXED_LEN = 0x5e; // misc public const int TEXT_TIME_STAMP_LEN = 8; public const int COLLATION_INFO_LEN = 4; /* public const byte INT4_LSB_HI = 0; // lsb is low byte (eg 68000) // public const byte INT4_LSB_LO = 1; // lsb is low byte (eg VAX) public const byte INT2_LSB_HI = 2; // lsb is low byte (eg 68000) // public const byte INT2_LSB_LO = 3; // lsb is low byte (eg VAX) public const byte FLT_IEEE_HI = 4; // lsb is low byte (eg 68000) public const byte CHAR_ASCII = 6; // ASCII character set public const byte TWO_I4_LSB_HI = 8; // lsb is low byte (eg 68000 // public const byte TWO_I4_LSB_LO = 9; // lsb is low byte (eg VAX) // public const byte FLT_IEEE_LO = 10; // lsb is low byte (eg MSDOS) public const byte FLT4_IEEE_HI = 12; // IEEE 4-byte floating point -lsb is high byte // public const byte FLT4_IEEE_LO = 13; // IEEE 4-byte floating point -lsb is low byte public const byte TWO_I2_LSB_HI = 16; // lsb is high byte // public const byte TWO_I2_LSB_LO = 17; // lsb is low byte public const byte LDEFSQL = 0; // server sends its default public const byte LDEFUSER = 0; // regular old user public const byte LINTEGRATED = 8; // integrated security login */ /* Versioning scheme table: Client sends: 0x70000000 -> Sphinx 0x71000000 -> Shiloh RTM 0x71000001 -> Shiloh SP1 0x72xx0002 -> Yukon RTM Server responds: 0x07000000 -> Sphinx // Notice server response format is different for bwd compat 0x07010000 -> Shiloh RTM // Notice server response format is different for bwd compat 0x71000001 -> Shiloh SP1 0x72xx0002 -> Yukon RTM */ // Shiloh SP1 and beyond versioning scheme: // Majors: public const int YUKON_MAJOR = 0x72; // the high-byte is sufficient to distinguish later versions public const int KATMAI_MAJOR = 0x73; public const int DENALI_MAJOR = 0x74; // Increments: public const int YUKON_INCREMENT = 0x09; public const int KATMAI_INCREMENT = 0x0b; public const int DENALI_INCREMENT = 0x00; // Minors: public const int YUKON_RTM_MINOR = 0x0002; public const int KATMAI_MINOR = 0x0003; public const int DENALI_MINOR = 0x0004; public const int ORDER_68000 = 1; public const int USE_DB_ON = 1; public const int INIT_DB_FATAL = 1; public const int SET_LANG_ON = 1; public const int INIT_LANG_FATAL = 1; public const int ODBC_ON = 1; public const int SSPI_ON = 1; public const int REPL_ON = 3; // send the read-only intent to the server public const int READONLY_INTENT_ON = 1; // Token masks public const byte SQLLenMask = 0x30; // mask to check for length tokens public const byte SQLFixedLen = 0x30; // Mask to check for fixed token public const byte SQLVarLen = 0x20; // Value to check for variable length token public const byte SQLZeroLen = 0x10; // Value to check for zero length token public const byte SQLVarCnt = 0x00; // Value to check for variable count token // Token masks for COLINFO status public const byte SQLDifferentName = 0x20; // column name different than select list name public const byte SQLExpression = 0x4; // column was result of an expression public const byte SQLKey = 0x8; // column is part of the key for the table public const byte SQLHidden = 0x10; // column not part of select list but added because part of key // Token masks for COLMETADATA flags // first byte public const byte Nullable = 0x1; public const byte Identity = 0x10; public const byte Updatability = 0xb; // mask off bits 3 and 4 // second byte public const byte ClrFixedLen = 0x1; // Fixed length CLR type public const byte IsColumnSet = 0x4; // Column is an XML representation of an aggregation of other columns // null values public const uint VARLONGNULL = 0xffffffff; // null value for text and image types public const int VARNULL = 0xffff; // null value for character and binary types public const int MAXSIZE = 8000; // max size for any column public const byte FIXEDNULL = 0; public const UInt64 UDTNULL = 0xffffffffffffffff; // SQL Server Data Type Tokens. public const int SQLVOID = 0x1f; public const int SQLTEXT = 0x23; public const int SQLVARBINARY = 0x25; public const int SQLINTN = 0x26; public const int SQLVARCHAR = 0x27; public const int SQLBINARY = 0x2d; public const int SQLIMAGE = 0x22; public const int SQLCHAR = 0x2f; public const int SQLINT1 = 0x30; public const int SQLBIT = 0x32; public const int SQLINT2 = 0x34; public const int SQLINT4 = 0x38; public const int SQLMONEY = 0x3c; public const int SQLDATETIME = 0x3d; public const int SQLFLT8 = 0x3e; public const int SQLFLTN = 0x6d; public const int SQLMONEYN = 0x6e; public const int SQLDATETIMN = 0x6f; public const int SQLFLT4 = 0x3b; public const int SQLMONEY4 = 0x7a; public const int SQLDATETIM4 = 0x3a; public const int SQLDECIMALN = 0x6a; public const int SQLNUMERICN = 0x6c; public const int SQLUNIQUEID = 0x24; public const int SQLBIGCHAR = 0xaf; public const int SQLBIGVARCHAR = 0xa7; public const int SQLBIGBINARY = 0xad; public const int SQLBIGVARBINARY = 0xa5; public const int SQLBITN = 0x68; public const int SQLNCHAR = 0xef; public const int SQLNVARCHAR = 0xe7; public const int SQLNTEXT = 0x63; public const int SQLUDT = 0xF0; // aggregate operator type TDS tokens, used by compute statements: public const int AOPCNTB = 0x09; public const int AOPSTDEV = 0x30; public const int AOPSTDEVP = 0x31; public const int AOPVAR = 0x32; public const int AOPVARP = 0x33; public const int AOPCNT = 0x4b; public const int AOPSUM = 0x4d; public const int AOPAVG = 0x4f; public const int AOPMIN = 0x51; public const int AOPMAX = 0x52; public const int AOPANY = 0x53; public const int AOPNOOP = 0x56; // SQL Server user-defined type tokens we care about public const int SQLTIMESTAMP = 0x50; public const int MAX_NUMERIC_LEN = 0x11; // 17 bytes of data for max numeric/decimal length public const int DEFAULT_NUMERIC_PRECISION = 0x1D; // 29 is the default max numeric precision(Decimal.MaxValue) if not user set public const int SPHINX_DEFAULT_NUMERIC_PRECISION = 0x1C; // 28 is the default max numeric precision for Sphinx(Decimal.MaxValue doesn't work for sphinx) public const int MAX_NUMERIC_PRECISION = 0x26; // 38 is max numeric precision; public const byte UNKNOWN_PRECISION_SCALE = 0xff; // -1 is value for unknown precision or scale // The following datatypes are specific to SHILOH (version 8) and later. public const int SQLINT8 = 0x7f; public const int SQLVARIANT = 0x62; // The following datatypes are specific to Yukon (version 9) or later public const int SQLXMLTYPE = 0xf1; public const int XMLUNICODEBOM = 0xfeff; public static readonly byte[] XMLUNICODEBOMBYTES = { 0xff, 0xfe }; // The following datatypes are specific to Katmai (version 10) or later public const int SQLTABLE = 0xf3; public const int SQLDATE = 0x28; public const int SQLTIME = 0x29; public const int SQLDATETIME2 = 0x2a; public const int SQLDATETIMEOFFSET = 0x2b; public const int DEFAULT_VARTIME_SCALE = 7; //Partially length prefixed datatypes constants. These apply to XMLTYPE, BIGVARCHRTYPE, // NVARCHARTYPE, and BIGVARBINTYPE. Valid for Yukon or later public const ulong SQL_PLP_NULL = 0xffffffffffffffff; // Represents null value public const ulong SQL_PLP_UNKNOWNLEN = 0xfffffffffffffffe; // Data coming in chunks, total length unknown public const int SQL_PLP_CHUNK_TERMINATOR = 0x00000000; // Represents end of chunked data. public const ushort SQL_USHORTVARMAXLEN = 0xffff; // Second ushort in TDS stream is this value if one of max types // TVPs require some new in-value control tokens: public const byte TVP_ROWCOUNT_ESTIMATE = 0x12; public const byte TVP_ROW_TOKEN = 0x01; public const byte TVP_END_TOKEN = 0x00; public const ushort TVP_NOMETADATA_TOKEN = 0xFFFF; public const byte TVP_ORDER_UNIQUE_TOKEN = 0x10; // TvpColumnMetaData flags public const int TVP_DEFAULT_COLUMN = 0x200; // TVP_ORDER_UNIQUE_TOKEN flags public const byte TVP_ORDERASC_FLAG = 0x1; public const byte TVP_ORDERDESC_FLAG = 0x2; public const byte TVP_UNIQUE_FLAG = 0x4; // RPC function names public const string SP_EXECUTESQL = "sp_executesql"; // used against 7.0 servers public const string SP_PREPEXEC = "sp_prepexec"; // used against 7.5 servers public const string SP_PREPARE = "sp_prepare"; // used against 7.0 servers public const string SP_EXECUTE = "sp_execute"; public const string SP_UNPREPARE = "sp_unprepare"; public const string SP_PARAMS = "sp_procedure_params_rowset"; public const string SP_PARAMS_MANAGED = "sp_procedure_params_managed"; public const string SP_PARAMS_MGD10 = "sp_procedure_params_100_managed"; // RPC ProcID's // NOTE: It is more efficient to call these procs using ProcID's instead of names public const ushort RPC_PROCID_CURSOR = 1; public const ushort RPC_PROCID_CURSOROPEN = 2; public const ushort RPC_PROCID_CURSORPREPARE = 3; public const ushort RPC_PROCID_CURSOREXECUTE = 4; public const ushort RPC_PROCID_CURSORPREPEXEC = 5; public const ushort RPC_PROCID_CURSORUNPREPARE = 6; public const ushort RPC_PROCID_CURSORFETCH = 7; public const ushort RPC_PROCID_CURSOROPTION = 8; public const ushort RPC_PROCID_CURSORCLOSE = 9; public const ushort RPC_PROCID_EXECUTESQL = 10; public const ushort RPC_PROCID_PREPARE = 11; public const ushort RPC_PROCID_EXECUTE = 12; public const ushort RPC_PROCID_PREPEXEC = 13; public const ushort RPC_PROCID_PREPEXECRPC = 14; public const ushort RPC_PROCID_UNPREPARE = 15; // For Transactions public const string TRANS_BEGIN = "BEGIN TRANSACTION"; public const string TRANS_COMMIT = "COMMIT TRANSACTION"; public const string TRANS_ROLLBACK = "ROLLBACK TRANSACTION"; public const string TRANS_IF_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION"; public const string TRANS_SAVE = "SAVE TRANSACTION"; // For Transactions - isolation levels public const string TRANS_READ_COMMITTED = "SET TRANSACTION ISOLATION LEVEL READ COMMITTED"; public const string TRANS_READ_UNCOMMITTED = "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"; public const string TRANS_REPEATABLE_READ = "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"; public const string TRANS_SERIALIZABLE = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"; public const string TRANS_SNAPSHOT = "SET TRANSACTION ISOLATION LEVEL SNAPSHOT"; // Batch RPC flags public const byte SHILOH_RPCBATCHFLAG = 0x80; public const byte YUKON_RPCBATCHFLAG = 0xFF; // RPC flags public const byte RPC_RECOMPILE = 0x1; public const byte RPC_NOMETADATA = 0x2; // RPC parameter class public const byte RPC_PARAM_BYREF = 0x1; public const byte RPC_PARAM_DEFAULT = 0x2; public const byte RPC_PARAM_IS_LOB_COOKIE = 0x8; // SQL parameter list text public const string PARAM_OUTPUT = "output"; // SQL Parameter constants public const int MAX_PARAMETER_NAME_LENGTH = 128; // metadata options (added around an existing sql statement) // prefixes public const string FMTONLY_ON = " SET FMTONLY ON;"; public const string FMTONLY_OFF = " SET FMTONLY OFF;"; // suffixes public const string BROWSE_ON = " SET NO_BROWSETABLE ON;"; public const string BROWSE_OFF = " SET NO_BROWSETABLE OFF;"; // generic table name public const string TABLE = "Table"; public const int EXEC_THRESHOLD = 0x3; // if the number of commands we execute is > than this threshold, than do prep/exec/unprep instead // of executesql. // dbnetlib error values public const short TIMEOUT_EXPIRED = -2; public const short ENCRYPTION_NOT_SUPPORTED = 20; // CAUTION: These are not error codes returned by SNI. This is used for backward compatibility // since netlib (now removed from sqlclient) returned these codes. // SQL error values (from sqlerrorcodes.h) public const int LOGON_FAILED = 18456; public const int PASSWORD_EXPIRED = 18488; public const int IMPERSONATION_FAILED = 1346; public const int P_TOKENTOOLONG = 103; // SNI\Win32 error values // NOTE: these are simply windows system error codes, not SNI specific public const uint SNI_UNINITIALIZED = unchecked((uint)-1); public const uint SNI_SUCCESS = 0; // The operation completed successfully. public const uint SNI_ERROR = 1; // Error public const uint SNI_WAIT_TIMEOUT = 258; // The wait operation timed out. public const uint SNI_SUCCESS_IO_PENDING = 997; // Overlapped I/O operation is in progress. // Windows Sockets Error Codes public const short SNI_WSAECONNRESET = 10054; // An existing connection was forcibly closed by the remote host. // SNI internal errors (shouldn't overlap with Win32 / socket errors) public const uint SNI_QUEUE_FULL = 1048576; // Packet queue is full // SNI flags public const UInt32 SNI_SSL_VALIDATE_CERTIFICATE = 1; // This enables validation of server certificate public const UInt32 SNI_SSL_USE_SCHANNEL_CACHE = 2; // This enables schannel session cache public const UInt32 SNI_SSL_IGNORE_CHANNEL_BINDINGS = 0x10; // Used with SSL Provider, sent to SNIAddProvider in case of SQL Authentication & Encrypt. public const string DEFAULT_ENGLISH_CODE_PAGE_STRING = "iso_1"; public const short DEFAULT_ENGLISH_CODE_PAGE_VALUE = 1252; public const short CHARSET_CODE_PAGE_OFFSET = 2; internal const int MAX_SERVERNAME = 255; // Sql Statement Tokens in the DONE packet // (see ntdbms\ntinc\tokens.h) // internal const ushort SELECT = 0xc1; internal const ushort INSERT = 0xc3; internal const ushort DELETE = 0xc4; internal const ushort UPDATE = 0xc5; internal const ushort ABORT = 0xd2; internal const ushort BEGINXACT = 0xd4; internal const ushort ENDXACT = 0xd5; internal const ushort BULKINSERT = 0xf0; internal const ushort OPENCURSOR = 0x20; internal const ushort MERGE = 0x117; // Login data validation Rules // internal const ushort MAXLEN_HOSTNAME = 128; // the client machine name internal const ushort MAXLEN_USERNAME = 128; // the client user id internal const ushort MAXLEN_PASSWORD = 128; // the password supplied by the client internal const ushort MAXLEN_APPNAME = 128; // the client application name internal const ushort MAXLEN_SERVERNAME = 128; // the server name internal const ushort MAXLEN_CLIENTINTERFACE = 128; // the interface library name internal const ushort MAXLEN_LANGUAGE = 128; // the initial language internal const ushort MAXLEN_DATABASE = 128; // the initial database internal const ushort MAXLEN_ATTACHDBFILE = 260; // the filename for a database that is to be attached during the connection process internal const ushort MAXLEN_NEWPASSWORD = 128; // new password for the specified login. // array copied directly from tdssort.h from luxor public static readonly UInt16[] CODE_PAGE_FROM_SORT_ID = { 0, /* 0 */ 0, /* 1 */ 0, /* 2 */ 0, /* 3 */ 0, /* 4 */ 0, /* 5 */ 0, /* 6 */ 0, /* 7 */ 0, /* 8 */ 0, /* 9 */ 0, /* 10 */ 0, /* 11 */ 0, /* 12 */ 0, /* 13 */ 0, /* 14 */ 0, /* 15 */ 0, /* 16 */ 0, /* 17 */ 0, /* 18 */ 0, /* 19 */ 0, /* 20 */ 0, /* 21 */ 0, /* 22 */ 0, /* 23 */ 0, /* 24 */ 0, /* 25 */ 0, /* 26 */ 0, /* 27 */ 0, /* 28 */ 0, /* 29 */ 437, /* 30 */ 437, /* 31 */ 437, /* 32 */ 437, /* 33 */ 437, /* 34 */ 0, /* 35 */ 0, /* 36 */ 0, /* 37 */ 0, /* 38 */ 0, /* 39 */ 850, /* 40 */ 850, /* 41 */ 850, /* 42 */ 850, /* 43 */ 850, /* 44 */ 0, /* 45 */ 0, /* 46 */ 0, /* 47 */ 0, /* 48 */ 850, /* 49 */ 1252, /* 50 */ 1252, /* 51 */ 1252, /* 52 */ 1252, /* 53 */ 1252, /* 54 */ 850, /* 55 */ 850, /* 56 */ 850, /* 57 */ 850, /* 58 */ 850, /* 59 */ 850, /* 60 */ 850, /* 61 */ 0, /* 62 */ 0, /* 63 */ 0, /* 64 */ 0, /* 65 */ 0, /* 66 */ 0, /* 67 */ 0, /* 68 */ 0, /* 69 */ 0, /* 70 */ 1252, /* 71 */ 1252, /* 72 */ 1252, /* 73 */ 1252, /* 74 */ 1252, /* 75 */ 0, /* 76 */ 0, /* 77 */ 0, /* 78 */ 0, /* 79 */ 1250, /* 80 */ 1250, /* 81 */ 1250, /* 82 */ 1250, /* 83 */ 1250, /* 84 */ 1250, /* 85 */ 1250, /* 86 */ 1250, /* 87 */ 1250, /* 88 */ 1250, /* 89 */ 1250, /* 90 */ 1250, /* 91 */ 1250, /* 92 */ 1250, /* 93 */ 1250, /* 94 */ 1250, /* 95 */ 1250, /* 96 */ 1250, /* 97 */ 1250, /* 98 */ 0, /* 99 */ 0, /* 100 */ 0, /* 101 */ 0, /* 102 */ 0, /* 103 */ 1251, /* 104 */ 1251, /* 105 */ 1251, /* 106 */ 1251, /* 107 */ 1251, /* 108 */ 0, /* 109 */ 0, /* 110 */ 0, /* 111 */ 1253, /* 112 */ 1253, /* 113 */ 1253, /* 114 */ 0, /* 115 */ 0, /* 116 */ 0, /* 117 */ 0, /* 118 */ 0, /* 119 */ 1253, /* 120 */ 1253, /* 121 */ 1253, /* 122 */ 0, /* 123 */ 1253, /* 124 */ 0, /* 125 */ 0, /* 126 */ 0, /* 127 */ 1254, /* 128 */ 1254, /* 129 */ 1254, /* 130 */ 0, /* 131 */ 0, /* 132 */ 0, /* 133 */ 0, /* 134 */ 0, /* 135 */ 1255, /* 136 */ 1255, /* 137 */ 1255, /* 138 */ 0, /* 139 */ 0, /* 140 */ 0, /* 141 */ 0, /* 142 */ 0, /* 143 */ 1256, /* 144 */ 1256, /* 145 */ 1256, /* 146 */ 0, /* 147 */ 0, /* 148 */ 0, /* 149 */ 0, /* 150 */ 0, /* 151 */ 1257, /* 152 */ 1257, /* 153 */ 1257, /* 154 */ 1257, /* 155 */ 1257, /* 156 */ 1257, /* 157 */ 1257, /* 158 */ 1257, /* 159 */ 1257, /* 160 */ 0, /* 161 */ 0, /* 162 */ 0, /* 163 */ 0, /* 164 */ 0, /* 165 */ 0, /* 166 */ 0, /* 167 */ 0, /* 168 */ 0, /* 169 */ 0, /* 170 */ 0, /* 171 */ 0, /* 172 */ 0, /* 173 */ 0, /* 174 */ 0, /* 175 */ 0, /* 176 */ 0, /* 177 */ 0, /* 178 */ 0, /* 179 */ 0, /* 180 */ 0, /* 181 */ 0, /* 182 */ 1252, /* 183 */ 1252, /* 184 */ 1252, /* 185 */ 1252, /* 186 */ 0, /* 187 */ 0, /* 188 */ 0, /* 189 */ 0, /* 190 */ 0, /* 191 */ 932, /* 192 */ 932, /* 193 */ 949, /* 194 */ 949, /* 195 */ 950, /* 196 */ 950, /* 197 */ 936, /* 198 */ 936, /* 199 */ 932, /* 200 */ 949, /* 201 */ 950, /* 202 */ 936, /* 203 */ 874, /* 204 */ 874, /* 205 */ 874, /* 206 */ 0, /* 207 */ 0, /* 208 */ 0, /* 209 */ 1252, /* 210 */ 1252, /* 211 */ 1252, /* 212 */ 1252, /* 213 */ 1252, /* 214 */ 1252, /* 215 */ 1252, /* 216 */ 1252, /* 217 */ 0, /* 218 */ 0, /* 219 */ 0, /* 220 */ 0, /* 221 */ 0, /* 222 */ 0, /* 223 */ 0, /* 224 */ 0, /* 225 */ 0, /* 226 */ 0, /* 227 */ 0, /* 228 */ 0, /* 229 */ 0, /* 230 */ 0, /* 231 */ 0, /* 232 */ 0, /* 233 */ 0, /* 234 */ 0, /* 235 */ 0, /* 236 */ 0, /* 237 */ 0, /* 238 */ 0, /* 239 */ 0, /* 240 */ 0, /* 241 */ 0, /* 242 */ 0, /* 243 */ 0, /* 244 */ 0, /* 245 */ 0, /* 246 */ 0, /* 247 */ 0, /* 248 */ 0, /* 249 */ 0, /* 250 */ 0, /* 251 */ 0, /* 252 */ 0, /* 253 */ 0, /* 254 */ 0, /* 255 */ }; internal enum TransactionManagerRequestType { Begin = 5, Commit = 7, Rollback = 8, Save = 9 }; internal enum TransactionManagerIsolationLevel { Unspecified = 0x00, ReadUncommitted = 0x01, ReadCommitted = 0x02, RepeatableRead = 0x03, Serializable = 0x04, Snapshot = 0x05 } internal enum GenericType { MultiSet = 131, }; // Date, Time, DateTime2, DateTimeOffset specific constants internal static readonly Int64[] TICKS_FROM_SCALE = { 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1, }; internal const int WHIDBEY_DATE_LENGTH = 10; internal static readonly int[] WHIDBEY_TIME_LENGTH = { 8, 10, 11, 12, 13, 14, 15, 16 }; internal static readonly int[] WHIDBEY_DATETIME2_LENGTH = { 19, 21, 22, 23, 24, 25, 26, 27 }; internal static readonly int[] WHIDBEY_DATETIMEOFFSET_LENGTH = { 26, 28, 29, 30, 31, 32, 33, 34 }; } internal enum SniContext { Undefined = 0, Snix_Connect, Snix_PreLoginBeforeSuccessfullWrite, Snix_PreLogin, Snix_LoginSspi, Snix_ProcessSspi, Snix_Login, Snix_EnableMars, Snix_AutoEnlist, Snix_GetMarsSession, Snix_Execute, Snix_Read, Snix_Close, Snix_SendRows, } }
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; // ReSharper disable InconsistentNaming #pragma warning disable 1591 namespace TWCore.Serialization.NSerializer { public delegate void SerializeActionDelegate(object obj, SerializersTable table); public class SerializerTypeDescriptor { private static readonly MethodInfo NSerializableSerializeMInfo = typeof(INSerializable).GetMethod("Serialize", BindingFlags.Public | BindingFlags.Instance); public readonly bool IsNSerializable; public readonly byte[] Definition; public readonly Type Type; public readonly LambdaExpression InnerWriterLambda; public readonly SerializeActionDelegate SerializeAction; [MethodImpl(MethodImplOptions.AggressiveInlining)] public SerializerTypeDescriptor(Type type, HashSet<Type> previousTypes = null) { Type = type; if (previousTypes == null) previousTypes = new HashSet<Type>(); var ifaces = type.GetInterfaces(); var iListType = ifaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)); var iDictionaryType = ifaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); var isIList = iListType != null; var isIDictionary = iDictionaryType != null; var runtimeProperties = type.GetRuntimeProperties().OrderBy(p => p.Name).Where(prop => { if (prop.IsSpecialName || !prop.CanRead || !prop.CanWrite) return false; if (prop.GetAttribute<NonSerializeAttribute>() != null) return false; if (prop.GetIndexParameters().Length > 0) return false; if (isIList && prop.Name == "Capacity") return false; return true; }).ToArray(); // var properties = runtimeProperties.Select(p => p.Name).ToArray(); IsNSerializable = ifaces.Any(i => i == typeof(INSerializable)); var isArray = type.IsArray; var isList = false; if (!isArray) isList = !isIDictionary && isIList; // var typeName = type.GetTypeName(); var defText = typeName + ";" + (isArray ? "1" : "0") + ";" + (isList ? "1" : "0") + ";" + (isIDictionary ? "1" : "0") + ";" + properties.Join(";"); var defBytesLength = Encoding.UTF8.GetByteCount(defText); var defBytes = new byte[defBytesLength + 5]; defBytes[0] = DataBytesDefinition.TypeStart; defBytes[1] = (byte)defBytesLength; defBytes[2] = (byte)(defBytesLength >> 8); defBytes[3] = (byte)(defBytesLength >> 16); defBytes[4] = (byte)(defBytesLength >> 24); Encoding.UTF8.GetBytes(defText, 0, defText.Length, defBytes, 5); Definition = defBytes; SerializeAction = null; // var serExpressions = new List<Expression>(); var varExpressions = new List<ParameterExpression>(); // var obj = Expression.Parameter(typeof(object), "obj"); var serTable = Expression.Parameter(typeof(SerializersTable), "table"); var instance = Expression.Parameter(type, "instance"); varExpressions.Add(instance); serExpressions.Add(Expression.Assign(instance, Expression.Convert(obj, type))); // if (isArray) { var elementType = type.GetElementType(); var arrLength = Expression.Parameter(typeof(int), "length"); varExpressions.Add(arrLength); serExpressions.Add(Expression.Assign(arrLength, Expression.Call(instance, SerializersTable.ArrayLengthGetMethod))); serExpressions.Add(Expression.Call(serTable, SerializersTable.WriteIntMethodInfo, arrLength)); var forIdx = Expression.Parameter(typeof(int), "i"); varExpressions.Add(forIdx); var breakLabel = Expression.Label(typeof(void), "exitLoop"); serExpressions.Add(Expression.Assign(forIdx, Expression.Constant(0))); var getValueExpression = Expression.ArrayIndex(instance, Expression.PostIncrementAssign(forIdx)); var loop = Expression.Loop( Expression.IfThenElse( Expression.LessThan(forIdx, arrLength), WriteExpression(elementType, getValueExpression, serTable), Expression.Break(breakLabel)), breakLabel); serExpressions.Add(loop); } else if (isList) { var argTypes = iListType.GenericTypeArguments; var iLength = Expression.Parameter(typeof(int), "length"); varExpressions.Add(iLength); serExpressions.Add(Expression.Assign(iLength, Expression.Call(instance, SerializersTable.ListCountGetMethod))); serExpressions.Add(Expression.Call(serTable, SerializersTable.WriteIntMethodInfo, iLength)); var forIdx = Expression.Parameter(typeof(int), "i"); varExpressions.Add(forIdx); var breakLabel = Expression.Label(typeof(void), "exitLoop"); serExpressions.Add(Expression.Assign(forIdx, Expression.Constant(0))); var getValueExpression = Expression.MakeIndex(instance, SerializersTable.ListIndexProperty, new[] { Expression.PostIncrementAssign(forIdx) }); var loop = Expression.Loop( Expression.IfThenElse( Expression.LessThan(forIdx, iLength), WriteExpression(argTypes[0], getValueExpression, serTable), Expression.Break(breakLabel)), breakLabel); serExpressions.Add(loop); } else if (isIDictionary) { var argTypes = iDictionaryType.GenericTypeArguments; var iLength = Expression.Parameter(typeof(int), "length"); varExpressions.Add(iLength); serExpressions.Add(Expression.Assign(iLength, Expression.Call(instance, SerializersTable.ListCountGetMethod))); serExpressions.Add(Expression.Call(serTable, SerializersTable.WriteIntMethodInfo, iLength)); var enumerator = Expression.Parameter(typeof(IDictionaryEnumerator), "enumerator"); varExpressions.Add(enumerator); serExpressions.Add(Expression.Assign(enumerator, Expression.Call(instance, SerializersTable.DictionaryGetEnumeratorMethod))); var breakLabel = Expression.Label(typeof(void), "exitLoop"); var getKeyExpression = Expression.Convert(Expression.Call(enumerator, SerializersTable.DictionaryEnumeratorKeyMethod), argTypes[0]); var getValueExpression = Expression.Convert(Expression.Call(enumerator, SerializersTable.DictionaryEnumeratorValueMethod), argTypes[1]); var loop = Expression.Loop( Expression.IfThenElse( Expression.Call(enumerator, SerializersTable.EnumeratorMoveNextMethod), Expression.Block( WriteExpression(argTypes[0], getKeyExpression, serTable), WriteExpression(argTypes[1], getValueExpression, serTable) ), Expression.Break(breakLabel)), breakLabel); serExpressions.Add(loop); } // if (runtimeProperties.Length > 0) { foreach (var prop in runtimeProperties) { var getExpression = Expression.Property(instance, prop); serExpressions.Add(WriteExpression(prop.PropertyType, getExpression, serTable)); } } // var serExpression = Expression.Block(varExpressions, serExpressions).Reduce(); var innerValue = Expression.Parameter(type, "innerValue"); var innerSerExpression = Expression.Block(varExpressions, new[] { Expression.Assign(instance, innerValue) } .Concat( serExpressions.Skip(1)) ).Reduce(); InnerWriterLambda = Expression.Lambda(innerSerExpression, type.Name + "Writer", new[] { innerValue, serTable }); var serializationLambda = Expression.Lambda<SerializeActionDelegate>(serExpression, type.Name + "_Serializer", new[] { obj, serTable }); SerializeAction = serializationLambda.Compile(); Expression WriteExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression) { if (itemType == typeof(int)) return SerializersTable.WriteIntExpression(itemGetExpression, serTableExpression); if (itemType == typeof(int?)) return SerializersTable.WriteNulleableIntExpression(itemGetExpression, serTableExpression); if (itemType == typeof(bool)) return SerializersTable.WriteBooleanExpression(itemGetExpression, serTableExpression); if (itemType == typeof(bool?)) return SerializersTable.WriteNulleableBooleanExpression(itemGetExpression, serTableExpression); if (SerializersTable.WriteValues.TryGetValue(itemType, out var wMethodTuple)) return Expression.Call(serTableExpression, wMethodTuple.Method, itemGetExpression); if (itemType.IsEnum) return Expression.Call(serTableExpression, SerializersTable.WriteValues[typeof(Enum)].Method, Expression.Convert(itemGetExpression, typeof(Enum))); if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var nullParam = Expression.Parameter(itemType); var nullBlock = Expression.Block(new[] { nullParam }, Expression.Assign(nullParam, itemGetExpression), Expression.IfThenElse( Expression.Equal(nullParam, Expression.Constant(null, itemType)), Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), WriteExpression(itemType.GenericTypeArguments[0], nullParam, serTableExpression) ) ); return nullBlock; } if (itemType == typeof(IEnumerable) || itemType == typeof(IEnumerable<>) || itemType.ReflectedType == typeof(IEnumerable) || itemType.ReflectedType == typeof(IEnumerable<>) || itemType.ReflectedType == typeof(Enumerable) || itemType.FullName.IndexOf("System.Linq", StringComparison.Ordinal) > -1 || itemType.IsAssignableFrom(typeof(IEnumerable))) return Expression.Call(serTableExpression, SerializersTable.InternalWriteObjectValueMInfo, itemGetExpression); if (itemType.IsAbstract || itemType.IsInterface || itemType == typeof(object)) return Expression.Call(serTableExpression, SerializersTable.InternalWriteObjectValueMInfo, itemGetExpression); if (itemType.IsSealed) return WriteSealedExpression(itemType, itemGetExpression, serTableExpression); return WriteMixedExpression(itemType, itemGetExpression, serTableExpression); //return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); } /* var intParam = Expression.Parameter(typeof(int?)); var block = Expression.Block(new[] { intParam }, Expression.Assign(intParam, value), Expression.IfThenElse( Expression.Equal(intParam, Expression.Constant(null, typeof(int?))), Expression.Call(serTable, WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), WriteIntExpression(Expression.Call(intParam, IntValueProperty), serTable))); return block.Reduce(); */ Expression WriteSealedExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression) { if (itemType == type) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); if (!previousTypes.Add(itemType)) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); var innerDescriptor = SerializersTable.Descriptors.GetOrAdd(itemType, (tp, ptypes) => new SerializerTypeDescriptor(tp, ptypes), previousTypes); var innerVarExpressions = new List<ParameterExpression>(); var innerSerExpressions = new List<Expression>(); var returnLabel = Expression.Label(typeof(void), "return"); var value = Expression.Parameter(itemType, "value"); innerVarExpressions.Add(value); innerSerExpressions.Add(Expression.Assign(value, Expression.Convert(itemGetExpression, itemType))); #region Null Check innerSerExpressions.Add( Expression.IfThen(Expression.ReferenceEqual(value, Expression.Constant(null)), Expression.Block( Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), Expression.Return(returnLabel) ) ) ); #endregion #region Object Cache Check var objCacheExp = Expression.Field(serTableExpression, "_objectCache"); var objIdxExp = Expression.Variable(typeof(int), "objIdx"); innerVarExpressions.Add(objIdxExp); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(objCacheExp, SerializersTable.TryGetValueObjectSerializerCacheMethod, value, objIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteRefObjectMInfo, objIdxExp), Expression.Return(returnLabel) ), Expression.Call(objCacheExp, SerializersTable.SetObjectSerializerCacheMethod, value) ) ); #endregion #region Type Cache Check var typeCacheExp = Expression.Field(serTableExpression, "_typeCache"); var typeIdxExp = Expression.Variable(typeof(int), "tIdx"); innerVarExpressions.Add(typeIdxExp); var descDefinition = typeof(SerializerTypeDescriptor<>).MakeGenericType(itemType).GetField("Definition", BindingFlags.Public | BindingFlags.Static); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(typeCacheExp, SerializersTable.TryGetValueTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type)), typeIdxExp), Expression.Call(serTable, SerializersTable.WriteRefTypeMInfo, typeIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteBytesMethodInfo, Expression.Field(null, descDefinition)), Expression.Call(typeCacheExp, SerializersTable.SetTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type))) ) ) ); #endregion #region Serializer Call if (innerDescriptor.IsNSerializable) { innerSerExpressions.Add(Expression.Call(Expression.Convert(value, typeof(INSerializable)), NSerializableSerializeMInfo, serTableExpression)); } else { innerSerExpressions.Add(Expression.Invoke(innerDescriptor.InnerWriterLambda, value, serTable)); } #endregion innerSerExpressions.Add(Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.TypeEnd))); innerSerExpressions.Add(Expression.Label(returnLabel)); var innerExpression = Expression.Block(innerVarExpressions, innerSerExpressions).Reduce(); previousTypes.Remove(itemType); return innerExpression; } Expression WriteMixedExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression) { if (itemType == type) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); if (!previousTypes.Add(itemType)) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); var innerDescriptor = SerializersTable.Descriptors.GetOrAdd(itemType, (tp, ptypes) => new SerializerTypeDescriptor(tp, ptypes), previousTypes); var innerVarExpressions = new List<ParameterExpression>(); var innerSerExpressions = new List<Expression>(); var returnLabel = Expression.Label(typeof(void), "return"); var objValue = Expression.Parameter(typeof(object), "objValue"); innerVarExpressions.Add(objValue); innerSerExpressions.Add(Expression.Assign(objValue, itemGetExpression)); #region Null Check innerSerExpressions.Add( Expression.IfThen(Expression.ReferenceEqual(objValue, Expression.Constant(null)), Expression.Block( Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), Expression.Return(returnLabel) ) ) ); #endregion #region Object Cache Check var objCacheExp = Expression.Field(serTableExpression, "_objectCache"); var objIdxExp = Expression.Variable(typeof(int), "objIdx"); innerVarExpressions.Add(objIdxExp); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(objCacheExp, SerializersTable.TryGetValueObjectSerializerCacheMethod, objValue, objIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteRefObjectMInfo, objIdxExp), Expression.Return(returnLabel) ), Expression.Call(objCacheExp, SerializersTable.SetObjectSerializerCacheMethod, objValue) ) ); #endregion var valueType = Expression.Parameter(typeof(Type), "valueType"); innerVarExpressions.Add(valueType); innerSerExpressions.Add(Expression.Assign(valueType, Expression.Call(objValue, SerializersTable.GetTypeMethodInfo))); innerSerExpressions.Add( Expression.IfThenElse(Expression.TypeIs(objValue, itemType), WriteShortSealedExpression(itemType, objValue, serTableExpression, returnLabel, innerDescriptor), Expression.Call(serTableExpression, SerializersTable.InternalMixedWriteObjectValueMInfo, objValue, valueType) ) ); innerSerExpressions.Add(Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.TypeEnd))); innerSerExpressions.Add(Expression.Label(returnLabel)); var innerExpression = Expression.Block(innerVarExpressions, innerSerExpressions).Reduce(); previousTypes.Remove(itemType); return innerExpression; } Expression WriteShortSealedExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression, LabelTarget returnLabel, SerializerTypeDescriptor innerDescriptor) { var innerVarExpressions = new List<ParameterExpression>(); var innerSerExpressions = new List<Expression>(); var value = Expression.Parameter(itemType, "value"); innerVarExpressions.Add(value); innerSerExpressions.Add(Expression.Assign(value, Expression.Convert(itemGetExpression, itemType))); #region Type Cache Check var typeCacheExp = Expression.Field(serTableExpression, "_typeCache"); var typeIdxExp = Expression.Variable(typeof(int), "tIdx"); innerVarExpressions.Add(typeIdxExp); var descDefinition = typeof(SerializerTypeDescriptor<>).MakeGenericType(itemType).GetField("Definition", BindingFlags.Public | BindingFlags.Static); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(typeCacheExp, SerializersTable.TryGetValueTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type)), typeIdxExp), Expression.Call(serTable, SerializersTable.WriteRefTypeMInfo, typeIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteBytesMethodInfo, Expression.Field(null, descDefinition)), Expression.Call(typeCacheExp, SerializersTable.SetTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type))) ) ) ); #endregion #region Serializer Call if (innerDescriptor.IsNSerializable) { innerSerExpressions.Add(Expression.Call(Expression.Convert(value, typeof(INSerializable)), NSerializableSerializeMInfo, serTableExpression)); } else { innerSerExpressions.Add(Expression.Invoke(innerDescriptor.InnerWriterLambda, value, serTable)); } #endregion var innerExpression = Expression.Block(innerVarExpressions, innerSerExpressions).Reduce(); return innerExpression; } } } public static class SerializerTypeDescriptor<T> { public static byte[] Definition; public static SerializerTypeDescriptor Descriptor; static SerializerTypeDescriptor() { Descriptor = SerializersTable.Descriptors.GetOrAdd(typeof(T), t => new SerializerTypeDescriptor(t)); Definition = Descriptor.Definition; } } }
//------------------------------------------------------------------------------ // <copyright file="MapPathBasedVirtualPathProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Implementation of VirtualPathProvider based on the metabase and the standard * file system. This is what ASP.NET uses by default. */ namespace System.Web.Hosting { using System; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Configuration; using System.Web.Util; using System.Web.Configuration; using System.Web.Caching; using System.Web.Compilation; using Util=System.Web.UI.Util; using System.Security.Permissions; using System.Web.Security; internal class MapPathBasedVirtualPathProvider: VirtualPathProvider { public override string GetFileHash(string virtualPath, IEnumerable virtualPathDependencies) { HashCodeCombiner hashCodeCombiner = new HashCodeCombiner(); // Calculate the hash based on the time stamps of all the virtual paths foreach (string virtualDependency in virtualPathDependencies) { string physicalDependency = HostingEnvironment.MapPathInternal(virtualDependency); hashCodeCombiner.AddFile(physicalDependency); } return hashCodeCombiner.CombinedHashString; } public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { if (virtualPathDependencies == null) return null; StringCollection physicalDependencies = null; // Get the list of physical dependencies foreach (string virtualDependency in virtualPathDependencies) { string physicalDependency = HostingEnvironment.MapPathInternal(virtualDependency); if (physicalDependencies == null) physicalDependencies = new StringCollection(); physicalDependencies.Add(physicalDependency); } if (physicalDependencies == null) return null; // Copy the list of physical dependencies into an array string[] physicalDependenciesArray = new string[physicalDependencies.Count]; physicalDependencies.CopyTo(physicalDependenciesArray, 0); return new CacheDependency(0, physicalDependenciesArray, utcStart); } private string CreateCacheKey(bool isFile, string physicalPath) { // Need different prefixes for file/directory lookups if (isFile) return CacheInternal.PrefixMapPathVPPFile + physicalPath; else return CacheInternal.PrefixMapPathVPPDir + physicalPath; } private bool CacheLookupOrInsert(string virtualPath, bool isFile) { string physicalPath = HostingEnvironment.MapPathInternal(virtualPath); bool doNotCache = CachedPathData.DoNotCacheUrlMetadata; string cacheKey = null; if (!doNotCache) { cacheKey = CreateCacheKey(isFile, physicalPath); // tri-state: // * null means it's not cached // * true means it's cached and it exists // * false means it's cached and it doesn't exist bool? cacheValue = HttpRuntime.CacheInternal[cacheKey] as bool?; if (cacheValue != null) { return cacheValue.Value; } } bool exists = (isFile) ? File.Exists(physicalPath) : Directory.Exists(physicalPath); if (doNotCache) { return exists; } // Setup a cache entry for this so we don't hit the file system every time CacheDependency dep = null; // Code based on similar logic from FileAuthorizationModule. // If file does not exist, but it's path is beneath the app root, we will cache it and // use the first existing directory as the cache depenedency path. If it does not exist // and it's not beneath the app root, we cannot cache it. string existingDir = (exists) ? physicalPath : FileUtil.GetFirstExistingDirectory(AppRoot, physicalPath); if (existingDir != null) { dep = new CacheDependency(existingDir); TimeSpan slidingExp = CachedPathData.UrlMetadataSlidingExpiration; HttpRuntime.CacheInternal.UtcInsert(cacheKey, exists, dep, Cache.NoAbsoluteExpiration, slidingExp); } return exists; } private static string _AppRoot; private static string AppRoot { get { string appRoot = _AppRoot; if (appRoot == null) { InternalSecurityPermissions.AppPathDiscovery.Assert(); appRoot = Path.GetFullPath(HttpRuntime.AppDomainAppPathInternal); appRoot = FileUtil.RemoveTrailingDirectoryBackSlash(appRoot); _AppRoot = appRoot; } return appRoot; } } public override bool FileExists(string virtualPath) { return CacheLookupOrInsert(virtualPath, true); } public override bool DirectoryExists(string virtualDir) { return CacheLookupOrInsert(virtualDir, false); } public override VirtualFile GetFile(string virtualPath) { return new MapPathBasedVirtualFile(virtualPath); } public override VirtualDirectory GetDirectory(string virtualDir) { return new MapPathBasedVirtualDirectory(virtualDir); } } internal class MapPathBasedVirtualFile: VirtualFile { private string _physicalPath; private FindFileData _ffd; internal MapPathBasedVirtualFile(string virtualPath) : base(virtualPath) { } internal MapPathBasedVirtualFile(string virtualPath, string physicalPath, FindFileData ffd) : base(virtualPath) { _physicalPath = physicalPath; _ffd = ffd; } private void EnsureFileInfoObtained() { // Get the physical path and FindFileData on demand if (_physicalPath == null) { Debug.Assert(_ffd == null); _physicalPath = HostingEnvironment.MapPathInternal(VirtualPath); FindFileData.FindFile(_physicalPath, out _ffd); } } public override string Name { get { EnsureFileInfoObtained(); // If for whatever reason we couldn't get the FindFileData, just call the base (VSWhidbey 501294) if (_ffd == null) return base.Name; return _ffd.FileNameLong; } } public override Stream Open() { EnsureFileInfoObtained(); TimeStampChecker.AddFile(VirtualPath, _physicalPath); return new FileStream(_physicalPath, FileMode.Open, FileAccess.Read, FileShare.Read); } internal string PhysicalPath { get { EnsureFileInfoObtained(); return _physicalPath; } } } internal class MapPathBasedVirtualDirectory: VirtualDirectory { public MapPathBasedVirtualDirectory(string virtualPath) : base(virtualPath) { } public override IEnumerable Directories { get { return new MapPathBasedVirtualPathCollection( System.Web.VirtualPath.CreateNonRelative(VirtualPath), RequestedEntryType.Directories); } } public override IEnumerable Files { get { return new MapPathBasedVirtualPathCollection( System.Web.VirtualPath.CreateNonRelative(VirtualPath), RequestedEntryType.Files); } } public override IEnumerable Children { get { return new MapPathBasedVirtualPathCollection( System.Web.VirtualPath.CreateNonRelative(VirtualPath), RequestedEntryType.All); } } } internal enum RequestedEntryType { Files, Directories, All } internal class MapPathBasedVirtualPathCollection: MarshalByRefObject, IEnumerable { private VirtualPath _virtualPath; private RequestedEntryType _requestedEntryType; internal MapPathBasedVirtualPathCollection(VirtualPath virtualPath, RequestedEntryType requestedEntryType) { _virtualPath = virtualPath; _requestedEntryType = requestedEntryType; } public override Object InitializeLifetimeService(){ return null; // never expire lease } IEnumerator IEnumerable.GetEnumerator() { return new MapPathBasedVirtualPathEnumerator(_virtualPath, _requestedEntryType); } } internal class MapPathBasedVirtualPathEnumerator : MarshalByRefObject, IEnumerator, IDisposable { VirtualPath _virtualPath; // virtual path we are enumerating Hashtable _exclude; // names of files and dirs to exclude Hashtable _virtualPaths; // names of virtual directories to include IEnumerator _fileEnumerator; // the physical file enumerator IEnumerator _virtualEnumerator; // the virtual file enumerator bool _useFileEnumerator; // use the file enumerator RequestedEntryType _requestedEntryType; IServerConfig2 _serverConfig2; internal MapPathBasedVirtualPathEnumerator(VirtualPath virtualPath, RequestedEntryType requestedEntryType) { if (virtualPath.IsRelative) { throw new ArgumentException(SR.GetString(SR.Invalid_app_VirtualPath), "virtualPath"); } _virtualPath = virtualPath; _requestedEntryType = requestedEntryType; string physicalPath; if (!ServerConfig.UseServerConfig) { // Use the hosting environment to map the virtual path physicalPath = _virtualPath.MapPathInternal(); } else { IServerConfig serverConfig = ServerConfig.GetInstance(); _serverConfig2 = serverConfig as IServerConfig2; // Use serverConfig to map the virtual path physicalPath = serverConfig.MapPath(null, _virtualPath); if (_requestedEntryType != RequestedEntryType.Files) { // For MetabaseServerConfig, get the subdirs that are not in the application, and add them to the exclude list. if (_serverConfig2 == null) { string [] virtualSubdirsNotInApp = serverConfig.GetVirtualSubdirs(_virtualPath, false); if (virtualSubdirsNotInApp != null) { _exclude = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (string subdir in virtualSubdirsNotInApp) { _exclude[subdir] = subdir; } } } // Get subdirs that are virtual directories, and record their physical mappings. // Ignore the virtualPaths if we only need files, since it only contains directories string [] virtualSubdirsInApp = serverConfig.GetVirtualSubdirs(_virtualPath, true); if (virtualSubdirsInApp != null) { _virtualPaths = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (string subdir in virtualSubdirsInApp) { VirtualPath subpath = _virtualPath.SimpleCombineWithDir(subdir); string subPhysicalPath = serverConfig.MapPath(null, subpath); if (FileUtil.DirectoryExists(subPhysicalPath)) { _virtualPaths[subdir] = new MapPathBasedVirtualDirectory(subpath.VirtualPathString); } } // Create enumerator for the virtual paths _virtualEnumerator = _virtualPaths.Values.GetEnumerator(); } } } // Create an enumerator for the physical files and directories at this path _fileEnumerator = FileEnumerator.Create(physicalPath); // Reset the enumerator. Note that we don't support the Reset method. _useFileEnumerator = false; } public override Object InitializeLifetimeService(){ return null; // never expire lease } // Dispose the file enumerator void IDisposable.Dispose() { if (_fileEnumerator != null) { ((IDisposable)_fileEnumerator).Dispose(); _fileEnumerator = null; } } // First MoveNext() with the file enumerator, then with the virtual directories // that have not been enumerated. bool IEnumerator.MoveNext() { bool more = false; if (_virtualEnumerator != null) more = _virtualEnumerator.MoveNext(); if (!more) { _useFileEnumerator = true; for (;;) { more = _fileEnumerator.MoveNext(); if (!more) break; FileData fileData = (FileData) _fileEnumerator.Current; // Ignore all hidden files and directories if (fileData.IsHidden) continue; // Ignore it if it's not of the right type (i.e. directory vs file) if (fileData.IsDirectory) { if (_requestedEntryType == RequestedEntryType.Files) continue; // Check whether the file is the same as a virtual path // that we have already enumerated string name = fileData.Name; if (_virtualPaths != null && _virtualPaths.Contains(name)) continue; // Check whether the file should be excluded because it is // not part of this app. // MetabaseServerConfig if (_exclude != null && _exclude.Contains(name)) continue; // IServerConfig2 if (_serverConfig2 != null && !_serverConfig2.IsWithinApp(UrlPath.SimpleCombine(_virtualPath.VirtualPathString, name))) { continue; } } else { if (_requestedEntryType == RequestedEntryType.Directories) continue; } // We've found the file break; } } return more; } internal VirtualFileBase Current { get { if (_useFileEnumerator) { FileData fileData = (FileData) _fileEnumerator.Current; VirtualPath childVirtualPath; if (fileData.IsDirectory) { childVirtualPath = _virtualPath.SimpleCombineWithDir(fileData.Name); return new MapPathBasedVirtualDirectory(childVirtualPath.VirtualPathString); } else { childVirtualPath = _virtualPath.SimpleCombine(fileData.Name); FindFileData ffd = fileData.GetFindFileData(); return new MapPathBasedVirtualFile(childVirtualPath.VirtualPathString, fileData.FullName, ffd); } } else { return (VirtualFileBase) _virtualEnumerator.Current; } } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { // We don't support reset, though it would be easy to add if needed throw new InvalidOperationException(); } } #if NO // TEST CODE public class TestEnum { public static void Enum(HttpResponse response) { VirtualDirectory vdir = HostingEnvironment.VirtualPathProvider.GetDirectory( "~"); EnumRecursive(response, vdir); } static void EnumRecursive(HttpResponse response, VirtualDirectory vdir) { foreach (VirtualFile vfile in vdir.Files) { response.Write("File: " + vfile.VirtualPath + "<br>\r\n"); } foreach (VirtualDirectory childVdir in vdir.Directories) { response.Write("Directory: " + childVdir.VirtualPath + "<br>\r\n"); EnumRecursive(response, childVdir); } } } #endif }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ElementAccessExpressionSignatureHelpProvider(); } #region "Regular tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn1() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WorkItem(636117)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnExpression() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Foo() { C[] c = new C[1]; c[0][$$ } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlCommentsOn1() { var markup = @" class C { /// <summary> /// Summary for this. /// </summary> /// <param name=""a"">Param a</param> public string this[int a] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersOn2() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[22, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithParametersXmlComentsOn2() { var markup = @" class C { /// <summary> /// Summary for this. /// </summary> /// <param name=""a"">Param a</param> /// <param name=""b"">Param b</param> public string this[int a, bool b] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[22, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingBracketWithParameters() { var markup = @"class C { public string this[int a] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[$$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationWithoutClosingBracketWithParametersOn2() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[22, $$ |]} }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems); } #endregion #region "Current Parameter Name" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestCurrentParameterName() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[b: false, a: $$42|]]; } }"; VerifyCurrentParameterName(markup, "a"); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerBracket() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocationOnTriggerComma() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[42,$$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1)); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestNoInvocationOnSpace() { var markup = @" class C { public string this[int a, bool b] { get { return null; } set { } } } class D { void Foo() { var c = new C(); var x = [|c[42, $$|]]; } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '[' }; char[] unexpectedCharacters = { ' ', '(', '<' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_PropertyAlways() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_PropertyNever() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_PropertyAdvanced() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int this[int x] { get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int this[int x] { get { return 5; } set { } } public int this[double d] { get { return 5; } set { } } }"; var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>(); expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Foo[double d]", string.Empty, string.Empty, currentParameterIndex: 0)); var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem> { new SignatureHelpTestItem("int Foo[double d]", string.Empty, string.Empty, currentParameterIndex: 0), new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0), }; TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_GetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { public int this[int x] { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_SetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { public int this[int x] { get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored() { var markup = @" class Program { void M() { new Foo()[$$ } }"; var referencedCode = @" public class Foo { public int this[int x] { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int Foo[int x]", string.Empty, string.Empty, currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion #region Indexed Property tests [WorkItem(530811)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void IndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.IndexProp[$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; var metadataItems = new List<SignatureHelpTestItem>(); metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0)); var projectReferenceItems = new List<SignatureHelpTestItem>(); projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0)); TestSignatureHelpInEditorBrowsableContexts(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: metadataItems, expectedOrderedItemsSameSolution: projectReferenceItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } #endregion [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO public int this[int z] { get { return 0; } } #endif void foo() { var x = this[$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO public int this[int z] { get { return 0; } } #endif #if BAR void foo() { var x = this[$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false); } public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new ElementAccessExpressionSignatureHelpProvider(); } [WorkItem(636117)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestInvocation() { var markup = @" class C { public string this[int a] { get { return null; } set { } } } class D { void Foo() { var c = new C(); c[$$] } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WorkItem(939417)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void ConditionalIndexer() { var markup = @" public class P { public int this[int z] { get { return 0; } } public void foo() { P p = null; p?[$$] } } "; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0)); Test(markup, expectedOrderedItems); } [WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void NonIdentifierConditionalIndexer() { var expected = new[] { new SignatureHelpTestItem("char string[int index]") }; Test(@"class C { void M() { """"?[$$ } }", expected); // inline with a string literal Test(@"class C { void M() { """"?[/**/$$ } }", expected); // inline with a string literal and multiline comment Test(@"class C { void M() { ("""")?[$$ } }", expected); // parenthesized expression Test(@"class C { void M() { new System.String(' ', 1)?[$$ } }", expected); // new object expression // more complicated parenthesized expression Test(@"class C { void M() { (null as System.Collections.Generic.List<int>)?[$$ } }", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") }); } [WorkItem(1067933)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void InvokedWithNoToken() { var markup = @" // foo[$$"; Test(markup); } [WorkItem(2482, "https://github.com/dotnet/roslyn/issues/2482")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName() { var markup = @" class WithIndexer { public int this[int index] { get { return 0; } } } class TestClass { public WithIndexer Item { get; set; } public void Method(TestClass tc) { // `tc.Item[]` parses as ArrayTypeSyntax with an ElementType of QualifiedNameSyntax tc.Item[$$] } } "; Test(markup, new[] { new SignatureHelpTestItem("int WithIndexer[int index]") }, usePreviousCharAsTrigger: true); } } } }
namespace Mapack { using System; /// <summary>Determines the eigenvalues and eigenvectors of a real square matrix.</summary> /// <remarks> /// If <c>A</c> is symmetric, then <c>A = V * D * V'</c> and <c>A = V * V'</c> /// where the eigenvalue matrix <c>D</c> is diagonal and the eigenvector matrix <c>V</c> is orthogonal. /// If <c>A</c> is not symmetric, the eigenvalue matrix <c>D</c> is block diagonal /// with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, /// <c>lambda+i*mu</c>, in 2-by-2 blocks, <c>[lambda, mu; -mu, lambda]</c>. /// The columns of <c>V</c> represent the eigenvectors in the sense that <c>A * V = V * D</c>. /// The matrix V may be badly conditioned, or even singular, so the validity of the equation /// <c>A=V*D*inverse(V)</c> depends upon the condition of <c>V</c>. /// </remarks> public class EigenvalueDecomposition { private int n; // matrix dimension private double[] d, e; // storage of eigenvalues. private Matrix V; // storage of eigenvectors. private Matrix H; // storage of non-symmetric Hessenberg form. private double[] ort; // storage for non-symmetric algorithm. private double cdivr, cdivi; private bool symmetric; /// <summary>Construct an eigenvalue decomposition.</summary> public EigenvalueDecomposition(Matrix value) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Rows != value.Columns) { throw new ArgumentException("Matrix is not a square matrix.", "value"); } n = value.Columns; V = new Matrix(n,n); d = new double[n]; e = new double[n]; // Check for symmetry. this.symmetric = value.Symmetric; if (this.symmetric) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { V[i,j] = value[i,j]; } } // Tridiagonalize. this.tred2(); // Diagonalize. this.tql2(); } else { H = new Matrix(n,n); ort = new double[n]; for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { H[i,j] = value[i,j]; } } // Reduce to Hessenberg form. this.orthes(); // Reduce Hessenberg to real Schur form. this.hqr2(); } } private void tred2() { // Symmetric Householder reduction to tridiagonal form. // This is derived from the Algol procedures tred2 by Bowdler, Martin, Reinsch, and Wilkinson, // Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutine in EISPACK. for (int j = 0; j < n; j++) d[j] = V[n-1,j]; // Householder reduction to tridiagonal form. for (int i = n-1; i > 0; i--) { // Scale to avoid under/overflow. double scale = 0.0; double h = 0.0; for (int k = 0; k < i; k++) scale = scale + Math.Abs(d[k]); if (scale == 0.0) { e[i] = d[i-1]; for (int j = 0; j < i; j++) { d[j] = V[i-1,j]; V[i,j] = 0.0; V[j,i] = 0.0; } } else { // Generate Householder vector. for (int k = 0; k < i; k++) { d[k] /= scale; h += d[k] * d[k]; } double f = d[i-1]; double g = Math.Sqrt(h); if (f > 0) g = -g; e[i] = scale * g; h = h - f * g; d[i-1] = f - g; for (int j = 0; j < i; j++) e[j] = 0.0; // Apply similarity transformation to remaining columns. for (int j = 0; j < i; j++) { f = d[j]; V[j,i] = f; g = e[j] + V[j,j] * f; for (int k = j+1; k <= i-1; k++) { g += V[k,j] * d[k]; e[k] += V[k,j] * f; } e[j] = g; } f = 0.0; for (int j = 0; j < i; j++) { e[j] /= h; f += e[j] * d[j]; } double hh = f / (h + h); for (int j = 0; j < i; j++) e[j] -= hh * d[j]; for (int j = 0; j < i; j++) { f = d[j]; g = e[j]; for (int k = j; k <= i-1; k++) V[k,j] -= (f * e[k] + g * d[k]); d[j] = V[i-1,j]; V[i,j] = 0.0; } } d[i] = h; } // Accumulate transformations. for (int i = 0; i < n-1; i++) { V[n-1,i] = V[i,i]; V[i,i] = 1.0; double h = d[i+1]; if (h != 0.0) { for (int k = 0; k <= i; k++) d[k] = V[k,i+1] / h; for (int j = 0; j <= i; j++) { double g = 0.0; for (int k = 0; k <= i; k++) g += V[k,i+1] * V[k,j]; for (int k = 0; k <= i; k++) V[k,j] -= g * d[k]; } } for (int k = 0; k <= i; k++) V[k,i+1] = 0.0; } for (int j = 0; j < n; j++) { d[j] = V[n-1,j]; V[n-1,j] = 0.0; } V[n-1,n-1] = 1.0; e[0] = 0.0; } private void tql2() { // Symmetric tridiagonal QL algorithm. // This is derived from the Algol procedures tql2, by Bowdler, Martin, Reinsch, and Wilkinson, // Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutine in EISPACK. for (int i = 1; i < n; i++) e[i-1] = e[i]; e[n-1] = 0.0; double f = 0.0; double tst1 = 0.0; double eps = Math.Pow(2.0,-52.0); for (int l = 0; l < n; l++) { // Find small subdiagonal element. tst1 = Math.Max(tst1,Math.Abs(d[l]) + Math.Abs(e[l])); int m = l; while (m < n) { if (Math.Abs(e[m]) <= eps*tst1) break; m++; } // If m == l, d[l] is an eigenvalue, otherwise, iterate. if (m > l) { int iter = 0; do { iter = iter + 1; // (Could check iteration count here.) // Compute implicit shift double g = d[l]; double p = (d[l+1] - g) / (2.0 * e[l]); double r = Hypotenuse(p,1.0); if (p < 0) { r = -r; } d[l] = e[l] / (p + r); d[l+1] = e[l] * (p + r); double dl1 = d[l+1]; double h = g - d[l]; for (int i = l+2; i < n; i++) { d[i] -= h; } f = f + h; // Implicit QL transformation. p = d[m]; double c = 1.0; double c2 = c; double c3 = c; double el1 = e[l+1]; double s = 0.0; double s2 = 0.0; for (int i = m-1; i >= l; i--) { c3 = c2; c2 = c; s2 = s; g = c * e[i]; h = c * p; r = Hypotenuse(p,e[i]); e[i+1] = s * r; s = e[i] / r; c = p / r; p = c * d[i] - s * g; d[i+1] = h + s * (c * g + s * d[i]); // Accumulate transformation. for (int k = 0; k < n; k++) { h = V[k,i+1]; V[k,i+1] = s * V[k,i] + c * h; V[k,i] = c * V[k,i] - s * h; } } p = -s * s2 * c3 * el1 * e[l] / dl1; e[l] = s * p; d[l] = c * p; // Check for convergence. } while (Math.Abs(e[l]) > eps*tst1); } d[l] = d[l] + f; e[l] = 0.0; } // Sort eigenvalues and corresponding vectors. for (int i = 0; i < n-1; i++) { int k = i; double p = d[i]; for (int j = i+1; j < n; j++) { if (d[j] < p) { k = j; p = d[j]; } } if (k != i) { d[k] = d[i]; d[i] = p; for (int j = 0; j < n; j++) { p = V[j,i]; V[j,i] = V[j,k]; V[j,k] = p; } } } } private void orthes() { // Nonsymmetric reduction to Hessenberg form. // This is derived from the Algol procedures orthes and ortran, by Martin and Wilkinson, // Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutines in EISPACK. int low = 0; int high = n-1; for (int m = low+1; m <= high-1; m++) { // Scale column. double scale = 0.0; for (int i = m; i <= high; i++) scale = scale + Math.Abs(H[i,m-1]); if (scale != 0.0) { // Compute Householder transformation. double h = 0.0; for (int i = high; i >= m; i--) { ort[i] = H[i,m-1]/scale; h += ort[i] * ort[i]; } double g = Math.Sqrt(h); if (ort[m] > 0) g = -g; h = h - ort[m] * g; ort[m] = ort[m] - g; // Apply Householder similarity transformation // H = (I - u * u' / h) * H * (I - u * u') / h) for (int j = m; j < n; j++) { double f = 0.0; for (int i = high; i >= m; i--) f += ort[i]*H[i,j]; f = f/h; for (int i = m; i <= high; i++) H[i,j] -= f*ort[i]; } for (int i = 0; i <= high; i++) { double f = 0.0; for (int j = high; j >= m; j--) f += ort[j]*H[i,j]; f = f/h; for (int j = m; j <= high; j++) H[i,j] -= f*ort[j]; } ort[m] = scale*ort[m]; H[m,m-1] = scale*g; } } // Accumulate transformations (Algol's ortran). for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) V[i,j] = (i == j ? 1.0 : 0.0); for (int m = high-1; m >= low+1; m--) { if (H[m,m-1] != 0.0) { for (int i = m+1; i <= high; i++) ort[i] = H[i,m-1]; for (int j = m; j <= high; j++) { double g = 0.0; for (int i = m; i <= high; i++) g += ort[i] * V[i,j]; // Double division avoids possible underflow. g = (g / ort[m]) / H[m,m-1]; for (int i = m; i <= high; i++) V[i,j] += g * ort[i]; } } } } private void cdiv(double xr, double xi, double yr, double yi) { // Complex scalar division. double r; double d; if (Math.Abs(yr) > Math.Abs(yi)) { r = yi/yr; d = yr + r*yi; cdivr = (xr + r*xi)/d; cdivi = (xi - r*xr)/d; } else { r = yr/yi; d = yi + r*yr; cdivr = (r*xr + xi)/d; cdivi = (r*xi - xr)/d; } } private void hqr2() { // Nonsymmetric reduction from Hessenberg to real Schur form. // This is derived from the Algol procedure hqr2, by Martin and Wilkinson, Handbook for Auto. Comp., // Vol.ii-Linear Algebra, and the corresponding Fortran subroutine in EISPACK. int nn = this.n; int n = nn-1; int low = 0; int high = nn-1; double eps = Math.Pow(2.0,-52.0); double exshift = 0.0; double p = 0; double q = 0; double r = 0; double s = 0; double z = 0; double t; double w; double x; double y; // Store roots isolated by balanc and compute matrix norm double norm = 0.0; for (int i = 0; i < nn; i++) { if (i < low | i > high) { d[i] = H[i,i]; e[i] = 0.0; } for (int j = Math.Max(i-1,0); j < nn; j++) norm = norm + Math.Abs(H[i,j]); } // Outer loop over eigenvalue index int iter = 0; while (n >= low) { // Look for single small sub-diagonal element int l = n; while (l > low) { s = Math.Abs(H[l-1,l-1]) + Math.Abs(H[l,l]); if (s == 0.0) s = norm; if (Math.Abs(H[l,l-1]) < eps * s) break; l--; } // Check for convergence if (l == n) { // One root found H[n,n] = H[n,n] + exshift; d[n] = H[n,n]; e[n] = 0.0; n--; iter = 0; } else if (l == n-1) { // Two roots found w = H[n,n-1] * H[n-1,n]; p = (H[n-1,n-1] - H[n,n]) / 2.0; q = p * p + w; z = Math.Sqrt(Math.Abs(q)); H[n,n] = H[n,n] + exshift; H[n-1,n-1] = H[n-1,n-1] + exshift; x = H[n,n]; if (q >= 0) { // Real pair z = (p >= 0) ? (p + z) : (p - z); d[n-1] = x + z; d[n] = d[n-1]; if (z != 0.0) d[n] = x - w / z; e[n-1] = 0.0; e[n] = 0.0; x = H[n,n-1]; s = Math.Abs(x) + Math.Abs(z); p = x / s; q = z / s; r = Math.Sqrt(p * p+q * q); p = p / r; q = q / r; // Row modification for (int j = n-1; j < nn; j++) { z = H[n-1,j]; H[n-1,j] = q * z + p * H[n,j]; H[n,j] = q * H[n,j] - p * z; } // Column modification for (int i = 0; i <= n; i++) { z = H[i,n-1]; H[i,n-1] = q * z + p * H[i,n]; H[i,n] = q * H[i,n] - p * z; } // Accumulate transformations for (int i = low; i <= high; i++) { z = V[i,n-1]; V[i,n-1] = q * z + p * V[i,n]; V[i,n] = q * V[i,n] - p * z; } } else { // Complex pair d[n-1] = x + p; d[n] = x + p; e[n-1] = z; e[n] = -z; } n = n - 2; iter = 0; } else { // No convergence yet // Form shift x = H[n,n]; y = 0.0; w = 0.0; if (l < n) { y = H[n-1,n-1]; w = H[n,n-1] * H[n-1,n]; } // Wilkinson's original ad hoc shift if (iter == 10) { exshift += x; for (int i = low; i <= n; i++) H[i,i] -= x; s = Math.Abs(H[n,n-1]) + Math.Abs(H[n-1,n-2]); x = y = 0.75 * s; w = -0.4375 * s * s; } // MATLAB's new ad hoc shift if (iter == 30) { s = (y - x) / 2.0; s = s * s + w; if (s > 0) { s = Math.Sqrt(s); if (y < x) s = -s; s = x - w / ((y - x) / 2.0 + s); for (int i = low; i <= n; i++) H[i,i] -= s; exshift += s; x = y = w = 0.964; } } iter = iter + 1; // Look for two consecutive small sub-diagonal elements int m = n-2; while (m >= l) { z = H[m,m]; r = x - z; s = y - z; p = (r * s - w) / H[m+1,m] + H[m,m+1]; q = H[m+1,m+1] - z - r - s; r = H[m+2,m+1]; s = Math.Abs(p) + Math.Abs(q) + Math.Abs(r); p = p / s; q = q / s; r = r / s; if (m == l) break; if (Math.Abs(H[m,m-1]) * (Math.Abs(q) + Math.Abs(r)) < eps * (Math.Abs(p) * (Math.Abs(H[m-1,m-1]) + Math.Abs(z) + Math.Abs(H[m+1,m+1])))) break; m--; } for (int i = m+2; i <= n; i++) { H[i,i-2] = 0.0; if (i > m+2) H[i,i-3] = 0.0; } // Double QR step involving rows l:n and columns m:n for (int k = m; k <= n-1; k++) { bool notlast = (k != n-1); if (k != m) { p = H[k,k-1]; q = H[k+1,k-1]; r = (notlast ? H[k+2,k-1] : 0.0); x = Math.Abs(p) + Math.Abs(q) + Math.Abs(r); if (x != 0.0) { p = p / x; q = q / x; r = r / x; } } if (x == 0.0) break; s = Math.Sqrt(p * p + q * q + r * r); if (p < 0) s = -s; if (s != 0) { if (k != m) H[k,k-1] = -s * x; else if (l != m) H[k,k-1] = -H[k,k-1]; p = p + s; x = p / s; y = q / s; z = r / s; q = q / p; r = r / p; // Row modification for (int j = k; j < nn; j++) { p = H[k,j] + q * H[k+1,j]; if (notlast) { p = p + r * H[k+2,j]; H[k+2,j] = H[k+2,j] - p * z; } H[k,j] = H[k,j] - p * x; H[k+1,j] = H[k+1,j] - p * y; } // Column modification for (int i = 0; i <= Math.Min(n,k+3); i++) { p = x * H[i,k] + y * H[i,k+1]; if (notlast) { p = p + z * H[i,k+2]; H[i,k+2] = H[i,k+2] - p * r; } H[i,k] = H[i,k] - p; H[i,k+1] = H[i,k+1] - p * q; } // Accumulate transformations for (int i = low; i <= high; i++) { p = x * V[i,k] + y * V[i,k+1]; if (notlast) { p = p + z * V[i,k+2]; V[i,k+2] = V[i,k+2] - p * r; } V[i,k] = V[i,k] - p; V[i,k+1] = V[i,k+1] - p * q; } } } } } // Backsubstitute to find vectors of upper triangular form if (norm == 0.0) { return; } for (n = nn-1; n >= 0; n--) { p = d[n]; q = e[n]; // Real vector if (q == 0) { int l = n; H[n,n] = 1.0; for (int i = n-1; i >= 0; i--) { w = H[i,i] - p; r = 0.0; for (int j = l; j <= n; j++) r = r + H[i,j] * H[j,n]; if (e[i] < 0.0) { z = w; s = r; } else { l = i; if (e[i] == 0.0) { H[i,n] = (w != 0.0) ? (-r / w) : (-r / (eps * norm)); } else { // Solve real equations x = H[i,i+1]; y = H[i+1,i]; q = (d[i] - p) * (d[i] - p) + e[i] * e[i]; t = (x * s - z * r) / q; H[i,n] = t; H[i+1,n] = (Math.Abs(x) > Math.Abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z); } // Overflow control t = Math.Abs(H[i,n]); if ((eps * t) * t > 1) for (int j = i; j <= n; j++) H[j,n] = H[j,n] / t; } } } else if (q < 0) { // Complex vector int l = n-1; // Last vector component imaginary so matrix is triangular if (Math.Abs(H[n,n-1]) > Math.Abs(H[n-1,n])) { H[n-1,n-1] = q / H[n,n-1]; H[n-1,n] = -(H[n,n] - p) / H[n,n-1]; } else { cdiv(0.0,-H[n-1,n],H[n-1,n-1]-p,q); H[n-1,n-1] = cdivr; H[n-1,n] = cdivi; } H[n,n-1] = 0.0; H[n,n] = 1.0; for (int i = n-2; i >= 0; i--) { double ra,sa,vr,vi; ra = 0.0; sa = 0.0; for (int j = l; j <= n; j++) { ra = ra + H[i,j] * H[j,n-1]; sa = sa + H[i,j] * H[j,n]; } w = H[i,i] - p; if (e[i] < 0.0) { z = w; r = ra; s = sa; } else { l = i; if (e[i] == 0) { cdiv(-ra,-sa,w,q); H[i,n-1] = cdivr; H[i,n] = cdivi; } else { // Solve complex equations x = H[i,i+1]; y = H[i+1,i]; vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q; vi = (d[i] - p) * 2.0 * q; if (vr == 0.0 & vi == 0.0) vr = eps * norm * (Math.Abs(w) + Math.Abs(q) + Math.Abs(x) + Math.Abs(y) + Math.Abs(z)); cdiv(x*r-z*ra+q*sa,x*s-z*sa-q*ra,vr,vi); H[i,n-1] = cdivr; H[i,n] = cdivi; if (Math.Abs(x) > (Math.Abs(z) + Math.Abs(q))) { H[i+1,n-1] = (-ra - w * H[i,n-1] + q * H[i,n]) / x; H[i+1,n] = (-sa - w * H[i,n] - q * H[i,n-1]) / x; } else { cdiv(-r-y*H[i,n-1],-s-y*H[i,n],z,q); H[i+1,n-1] = cdivr; H[i+1,n] = cdivi; } } // Overflow control t = Math.Max(Math.Abs(H[i,n-1]),Math.Abs(H[i,n])); if ((eps * t) * t > 1) for (int j = i; j <= n; j++) { H[j,n-1] = H[j,n-1] / t; H[j,n] = H[j,n] / t; } } } } } // Vectors of isolated roots for (int i = 0; i < nn; i++) if (i < low | i > high) for (int j = i; j < nn; j++) V[i,j] = H[i,j]; // Back transformation to get eigenvectors of original matrix for (int j = nn-1; j >= low; j--) for (int i = low; i <= high; i++) { z = 0.0; for (int k = low; k <= Math.Min(j,high); k++) z = z + V[i,k] * H[k,j]; V[i,j] = z; } } /// <summary>Returns the real parts of the eigenvalues.</summary> public double[] RealEigenvalues { get { return this.d; } } /// <summary>Returns the imaginary parts of the eigenvalues.</summary> public double[] ImaginaryEigenvalues { get { return this.e; } } /// <summary>Returns the eigenvector matrix.</summary> public Matrix EigenvectorMatrix { get { return this.V; } } /// <summary>Returns the block diagonal eigenvalue matrix.</summary> public Matrix DiagonalMatrix { get { Matrix X = new Matrix(n, n); double[][] x = X.Array; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) x[i][j] = 0.0; x[i][i] = d[i]; if (e[i] > 0) { x[i][i+1] = e[i]; } else if (e[i] < 0) { x[i][i-1] = e[i]; } } return X; } } private static double Hypotenuse(double a, double b) { if (Math.Abs(a) > Math.Abs(b)) { double r = b / a; return Math.Abs(a) * Math.Sqrt(1 + r * r); } if (b != 0) { double r = a / b; return Math.Abs(b) * Math.Sqrt(1 + r * r); } return 0.0; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Debugging { internal partial class CSharpProximityExpressionsService { private static string ConvertToString(ExpressionSyntax expression) { var converted = expression.ConvertToSingleLine(); return converted.ToString(); } private static void AddExpressionTerms(ExpressionSyntax expression, IList<string> terms) { // Check here rather than at all the call sites... if (expression == null) { return; } // Collect terms from this expression, which returns flags indicating the validity // of this expression as a whole. var expressionType = ExpressionType.Invalid; AddSubExpressionTerms(expression, terms, ref expressionType); AddIfValidTerm(expression, expressionType, terms); } private static void AddIfValidTerm(ExpressionSyntax expression, ExpressionType type, IList<string> terms) { if (IsValidTerm(type)) { // If this expression identified itself as a valid term, add it to the // term table terms.Add(ConvertToString(expression)); } } private static bool IsValidTerm(ExpressionType type) { return (type & ExpressionType.ValidTerm) == ExpressionType.ValidTerm; } private static bool IsValidExpression(ExpressionType type) { return (type & ExpressionType.ValidExpression) == ExpressionType.ValidExpression; } private static void AddSubExpressionTerms(ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType) { // Check here rather than at all the call sites... if (expression == null) { return; } switch (expression.Kind()) { case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: // an op term is ok if it's a "this" or "base" op it allows us to see // "this.foo" in the autos window note: it's not a VALIDTERM since we don't // want "this" showing up in the auto's window twice. expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.IdentifierName: // Name nodes are always valid terms expressionType = ExpressionType.ValidTerm; return; case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: // Constants can make up a valid term, but we don't consider them valid // terms themselves (since we don't want them to show up in the autos window // on their own). expressionType = ExpressionType.ValidExpression; return; case SyntaxKind.CastExpression: AddCastExpressionTerms((CastExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: AddMemberAccessExpressionTerms((MemberAccessExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.ObjectCreationExpression: AddObjectCreationExpressionTerms((ObjectCreationExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.ArrayCreationExpression: AddArrayCreationExpressionTerms((ArrayCreationExpressionSyntax)expression, terms, ref expressionType); return; case SyntaxKind.InvocationExpression: AddInvocationExpressionTerms((InvocationExpressionSyntax)expression, terms, ref expressionType); return; } // +, -, ++, --, !, etc. // // This is a valid expression if it doesn't have obvious side effects (i.e. ++, --) if (expression is PrefixUnaryExpressionSyntax) { AddPrefixUnaryExpressionTerms((PrefixUnaryExpressionSyntax)expression, terms, ref expressionType); return; } if (expression is AwaitExpressionSyntax) { AddAwaitExpressionTerms((AwaitExpressionSyntax)expression, terms, ref expressionType); return; } if (expression is PostfixUnaryExpressionSyntax) { AddPostfixUnaryExpressionTerms((PostfixUnaryExpressionSyntax)expression, terms, ref expressionType); return; } if (expression is BinaryExpressionSyntax) { var binaryExpression = (BinaryExpressionSyntax)expression; AddBinaryExpressionTerms(expression, binaryExpression.Left, binaryExpression.Right, terms, ref expressionType); return; } if (expression is AssignmentExpressionSyntax) { var assignmentExpression = (AssignmentExpressionSyntax)expression; AddBinaryExpressionTerms(expression, assignmentExpression.Left, assignmentExpression.Right, terms, ref expressionType); return; } if (expression is ConditionalExpressionSyntax) { AddConditionalExpressionTerms((ConditionalExpressionSyntax)expression, terms, ref expressionType); return; } var parenthesizedExpression = expression as ParenthesizedExpressionSyntax; if (parenthesizedExpression != null) { AddSubExpressionTerms(parenthesizedExpression.Expression, terms, ref expressionType); } expressionType = ExpressionType.Invalid; } private static void AddCastExpressionTerms(CastExpressionSyntax castExpression, IList<string> terms, ref ExpressionType expressionType) { // For a cast, just add the nested expression. Note: this is technically // unsafe as the cast *may* have side effects. However, in practice this is // extremely rare, so we allow for this since it's ok in the common case. var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(castExpression.Expression, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(castExpression.Expression, flags, terms); // If the subexpression is a valid term, so is the cast expression expressionType = flags; } private static void AddMemberAccessExpressionTerms(MemberAccessExpressionSyntax memberAccessExpression, IList<string> terms, ref ExpressionType expressionType) { var flags = ExpressionType.Invalid; // These operators always have a RHS of a name node, which we know would // "claim" to be a valid term, but is not valid without the LHS present. // So, we don't bother collecting anything from the RHS... AddSubExpressionTerms(memberAccessExpression.Expression, terms, ref flags); // If the LHS says it's a valid term, then we add it ONLY if our PARENT // is NOT another dot/arrow. This allows the expression 'a.b.c.d' to // add both 'a.b.c.d' and 'a.b.c', but not 'a.b' and 'a'. if (IsValidTerm(flags) && !memberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) && !memberAccessExpression.IsParentKind(SyntaxKind.PointerMemberAccessExpression)) { terms.Add(ConvertToString(memberAccessExpression.Expression)); } // And this expression itself is a valid term if the LHS is a valid // expression, and its PARENT is not an invocation. if (IsValidExpression(flags) && !memberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression)) { expressionType = ExpressionType.ValidTerm; } else { expressionType = ExpressionType.ValidExpression; } } private static void AddObjectCreationExpressionTerms(ObjectCreationExpressionSyntax objectionCreationExpression, IList<string> terms, ref ExpressionType expressionType) { // Object creation can *definitely* cause side effects. So we initially // mark this as something invalid. We allow it as a valid expr if all // the sub arguments are valid terms. expressionType = ExpressionType.Invalid; if (objectionCreationExpression.ArgumentList != null) { var flags = ExpressionType.Invalid; AddArgumentTerms(objectionCreationExpression.ArgumentList, terms, ref flags); // If all arguments are terms, then this is possibly a valid expr that can be used // somewhere higher in the stack. if (IsValidTerm(flags)) { expressionType = ExpressionType.ValidExpression; } } } private static void AddArrayCreationExpressionTerms( ArrayCreationExpressionSyntax arrayCreationExpression, IList<string> terms, ref ExpressionType expressionType) { var validTerm = true; if (arrayCreationExpression.Initializer != null) { var flags = ExpressionType.Invalid; arrayCreationExpression.Initializer.Expressions.Do(e => AddSubExpressionTerms(e, terms, ref flags)); validTerm &= IsValidTerm(flags); } if (validTerm) { expressionType = ExpressionType.ValidExpression; } else { expressionType = ExpressionType.Invalid; } } private static void AddInvocationExpressionTerms(InvocationExpressionSyntax invocationExpression, IList<string> terms, ref ExpressionType expressionType) { // Invocations definitely have side effects. So we assume this // is invalid initially; expressionType = ExpressionType.Invalid; ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; AddSubExpressionTerms(invocationExpression.Expression, terms, ref leftFlags); AddArgumentTerms(invocationExpression.ArgumentList, terms, ref rightFlags); AddIfValidTerm(invocationExpression.Expression, leftFlags, terms); // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; } private static void AddPrefixUnaryExpressionTerms(PrefixUnaryExpressionSyntax prefixUnaryExpression, IList<string> terms, ref ExpressionType expressionType) { expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(prefixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(prefixUnaryExpression.Operand, flags, terms); if (prefixUnaryExpression.IsKind(SyntaxKind.LogicalNotExpression, SyntaxKind.BitwiseNotExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression)) { // We're a valid expression if our subexpression is... expressionType = flags & ExpressionType.ValidExpression; } } private static void AddAwaitExpressionTerms(AwaitExpressionSyntax awaitExpression, IList<string> terms, ref ExpressionType expressionType) { expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(awaitExpression.Expression, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(awaitExpression.Expression, flags, terms); } private static void AddPostfixUnaryExpressionTerms(PostfixUnaryExpressionSyntax postfixUnaryExpression, IList<string> terms, ref ExpressionType expressionType) { // ++ and -- are the only postfix operators. Since they always have side // effects, we never consider this an expression. expressionType = ExpressionType.Invalid; var flags = ExpressionType.Invalid; // Ask our subexpression for terms AddSubExpressionTerms(postfixUnaryExpression.Operand, terms, ref flags); // Is our expression a valid term? AddIfValidTerm(postfixUnaryExpression.Operand, flags, terms); } private static void AddConditionalExpressionTerms(ConditionalExpressionSyntax conditionalExpression, IList<string> terms, ref ExpressionType expressionType) { ExpressionType conditionFlags = ExpressionType.Invalid, trueFlags = ExpressionType.Invalid, falseFlags = ExpressionType.Invalid; AddSubExpressionTerms(conditionalExpression.Condition, terms, ref conditionFlags); AddSubExpressionTerms(conditionalExpression.WhenTrue, terms, ref trueFlags); AddSubExpressionTerms(conditionalExpression.WhenFalse, terms, ref falseFlags); AddIfValidTerm(conditionalExpression.Condition, conditionFlags, terms); AddIfValidTerm(conditionalExpression.WhenTrue, trueFlags, terms); AddIfValidTerm(conditionalExpression.WhenFalse, falseFlags, terms); // We're valid if all children are... expressionType = (conditionFlags & trueFlags & falseFlags) & ExpressionType.ValidExpression; } private static void AddBinaryExpressionTerms(ExpressionSyntax binaryExpression, ExpressionSyntax left, ExpressionSyntax right, IList<string> terms, ref ExpressionType expressionType) { ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid; AddSubExpressionTerms(left, terms, ref leftFlags); AddSubExpressionTerms(right, terms, ref rightFlags); if (IsValidTerm(leftFlags)) { terms.Add(ConvertToString(left)); } if (IsValidTerm(rightFlags)) { terms.Add(ConvertToString(right)); } // Many sorts of binops (like +=) will definitely have side effects. We only // consider this valid if it's a simple expression like +, -, etc. switch (binaryExpression.Kind()) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LogicalOrExpression: case SyntaxKind.LogicalAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.IsExpression: case SyntaxKind.AsExpression: case SyntaxKind.CoalesceExpression: // We're valid if both children are... expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression; return; default: expressionType = ExpressionType.Invalid; return; } } private static void AddArgumentTerms(ArgumentListSyntax argumentList, IList<string> terms, ref ExpressionType expressionType) { var validExpr = true; var validTerm = true; // Process the list of expressions. This is probably a list of // arguments to a function call(or a list of array index expressions) foreach (var arg in argumentList.Arguments) { var flags = ExpressionType.Invalid; if (arg.Expression != null) { AddSubExpressionTerms(arg.Expression, terms, ref flags); if (IsValidTerm(flags)) { terms.Add(ConvertToString(arg.Expression)); } } validExpr &= IsValidExpression(flags); validTerm &= IsValidTerm(flags); } // We're never a valid term if all arguments were valid terms. If not, we're a valid // expression if all arguments where. Otherwise, we're just invalid. expressionType = validTerm ? ExpressionType.ValidTerm : validExpr ? ExpressionType.ValidExpression : ExpressionType.Invalid; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests { sealed public class CombinePath_Tests { /// <summary> /// Base path is relative. Paths are relative. /// </summary> [Fact] public void RelativeRelative1() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.BasePath = Path.Combine("abc", "def"); string path1 = "ghi.txt"; string fullPath1 = Path.Combine(t.BasePath, path1); string path2 = Path.Combine("jkl", "mno.txt"); string fullPath2 = Path.Combine(t.BasePath, path2); t.Paths = new ITaskItem[] { new TaskItem(path1), new TaskItem(path2) }; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(string.Format("{0}\r\n{1}", fullPath1, fullPath2), t.CombinedPaths, true); } /// <summary> /// Base path is relative. Paths are absolute. /// </summary> [Fact] public void RelativeAbsolute1() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.BasePath = Path.Combine("abc", "def"); string path1 = NativeMethodsShared.IsWindows ? @"c:\ghi.txt" : "/ghi.txt"; string path2 = NativeMethodsShared.IsWindows ? @"d:\jkl\mno.txt" : "/jkl/mno.txt"; string path3 = @"\\myserver\myshare"; string pathsToMatch = string.Format(NativeMethodsShared.IsWindows ? @" {0} {1} {2} " : @" {0} {1} ", path1, path2, path3); t.Paths = NativeMethodsShared.IsWindows ? new ITaskItem[] { new TaskItem(path1), new TaskItem(path2), new TaskItem(path3) } : new ITaskItem[] { new TaskItem(path1), new TaskItem(path2) }; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(pathsToMatch, t.CombinedPaths, true); } /// <summary> /// Base path is absolute. Paths are relative. /// </summary> [Fact] public void AbsoluteRelative1() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.BasePath = NativeMethodsShared.IsWindows ? @"c:\abc\def" : "/abc/def"; string path1 = Path.DirectorySeparatorChar + Path.Combine("ghi", "jkl.txt"); string path2 = Path.Combine("mno", "qrs.txt"); string fullPath2 = Path.Combine(t.BasePath, path2); t.Paths = new ITaskItem[] { new TaskItem(path1), new TaskItem(path2) }; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(string.Format("{0}\r\n{1}", path1, fullPath2), t.CombinedPaths, true); } /// <summary> /// Base path is absolute. Paths are absolute. /// </summary> [Fact] public void AbsoluteAbsolute1() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.BasePath = NativeMethodsShared.IsWindows ? @"\\fileserver\public" : "/rootdir/public"; string path1 = NativeMethodsShared.IsWindows ? @"c:\ghi.txt" : "/ghi.txt"; string path2 = NativeMethodsShared.IsWindows ? @"d:\jkl\mno.txt" : "/jkl/mno.txt"; string path3 = @"\\myserver\myshare"; string pathsToMatch = string.Format(NativeMethodsShared.IsWindows ? @" {0} {1} {2} " : @" {0} {1} ", path1, path2, path3); t.Paths = NativeMethodsShared.IsWindows ? new ITaskItem[] { new TaskItem(path1), new TaskItem(path2), new TaskItem(path3) } : new ITaskItem[] { new TaskItem(path1), new TaskItem(path2) }; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(pathsToMatch, t.CombinedPaths, true); } /// <summary> /// All item metadata from the paths should be preserved when producing the output items. /// </summary> [Fact] public void MetadataPreserved() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); string expected; if (NativeMethodsShared.IsWindows) { t.BasePath = @"c:\abc\def\"; t.Paths = new ITaskItem[] { new TaskItem(@"jkl\mno.txt") }; expected = @" c:\abc\def\jkl\mno.txt : Culture=english "; } else { t.BasePath = "/abc/def/"; t.Paths = new ITaskItem[] { new TaskItem("jkl/mno.txt") }; expected = @" /abc/def/jkl/mno.txt : Culture=english "; } t.Paths[0].SetMetadata("Culture", "english"); Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(expected, t.CombinedPaths, true); } /// <summary> /// No base path passed in should be treated as a blank base path, which means that /// the original paths are returned untouched. /// </summary> [Fact] public void NoBasePath() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.Paths = new ITaskItem[] { new TaskItem(@"jkl\mno.txt"), new TaskItem(@"c:\abc\def\ghi.txt") }; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(@" jkl\mno.txt c:\abc\def\ghi.txt ", t.CombinedPaths, true); } /// <summary> /// Passing in an array of zero paths. Task should succeed and return zero paths. /// </summary> [Fact] public void NoPaths() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.BasePath = @"c:\abc\def"; t.Paths = new ITaskItem[0]; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(@" ", t.CombinedPaths, true); } /// <summary> /// Passing in a (blank) path. Task should simply return the base path. /// </summary> [Fact] public void BlankPath() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(); t.BasePath = @"c:\abc\def"; t.Paths = new ITaskItem[] { new TaskItem("") }; Assert.True(t.Execute()); // "success" ObjectModelHelpers.AssertItemsMatch(@" c:\abc\def ", t.CombinedPaths, true); } /// <summary> /// Specified paths contain invalid characters. Task should continue processing remaining items. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // No invalid characters on Unix [SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp)] public void InvalidPath() { CombinePath t = new CombinePath(); t.BuildEngine = new MockEngine(true); t.BasePath = @"c:\abc\def"; t.Paths = new ITaskItem[] { new TaskItem("ghi.txt"), new TaskItem("|.txt"), new TaskItem("jkl.txt") }; Assert.False(t.Execute()); // "should have failed" ((MockEngine)t.BuildEngine).AssertLogContains("MSB3095"); ObjectModelHelpers.AssertItemsMatch(@" c:\abc\def\ghi.txt c:\abc\def\jkl.txt ", t.CombinedPaths, true); } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ // Contributed by: Mitch Thompson #define SPINE_SKELETON_ANIMATOR using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; using Spine; namespace Spine.Unity.Editor { using Event = UnityEngine.Event; using Icons = SpineEditorUtilities.Icons; [CustomEditor(typeof(SkeletonDataAsset)), CanEditMultipleObjects] public class SkeletonDataAssetInspector : UnityEditor.Editor { static bool showAnimationStateData = true; static bool showAnimationList = true; static bool showSlotList = false; static bool showAttachments = false; SerializedProperty atlasAssets, skeletonJSON, scale, fromAnimation, toAnimation, duration, defaultMix; #if SPINE_TK2D SerializedProperty spriteCollection; #endif #if SPINE_SKELETON_ANIMATOR static bool isMecanimExpanded = false; SerializedProperty controller; #endif bool m_initialized = false; SkeletonDataAsset m_skeletonDataAsset; SkeletonData m_skeletonData; string m_skeletonDataAssetGUID; bool needToSerialize; readonly List<string> warnings = new List<string>(); GUIStyle activePlayButtonStyle, idlePlayButtonStyle; readonly GUIContent DefaultMixLabel = new GUIContent("Default Mix Duration", "Sets 'SkeletonDataAsset.defaultMix' in the asset and 'AnimationState.data.defaultMix' at runtime load time."); void OnEnable () { SpineEditorUtilities.ConfirmInitialization(); m_skeletonDataAsset = (SkeletonDataAsset)target; bool newAtlasAssets = atlasAssets == null; if (newAtlasAssets) atlasAssets = serializedObject.FindProperty("atlasAssets"); skeletonJSON = serializedObject.FindProperty("skeletonJSON"); scale = serializedObject.FindProperty("scale"); fromAnimation = serializedObject.FindProperty("fromAnimation"); toAnimation = serializedObject.FindProperty("toAnimation"); duration = serializedObject.FindProperty("duration"); defaultMix = serializedObject.FindProperty("defaultMix"); #if SPINE_SKELETON_ANIMATOR controller = serializedObject.FindProperty("controller"); #endif #if SPINE_TK2D if (newAtlasAssets) atlasAssets.isExpanded = false; spriteCollection = serializedObject.FindProperty("spriteCollection"); #else if (newAtlasAssets) atlasAssets.isExpanded = true; #endif m_skeletonDataAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_skeletonDataAsset)); EditorApplication.update -= EditorUpdate; EditorApplication.update += EditorUpdate; RepopulateWarnings(); if (m_skeletonDataAsset.skeletonJSON == null) { m_skeletonData = null; return; } m_skeletonData = warnings.Count == 0 ? m_skeletonDataAsset.GetSkeletonData(false) : null; } void OnDestroy () { m_initialized = false; EditorApplication.update -= EditorUpdate; this.DestroyPreviewInstances(); if (this.m_previewUtility != null) { this.m_previewUtility.Cleanup(); this.m_previewUtility = null; } } override public void OnInspectorGUI () { if (serializedObject.isEditingMultipleObjects) { using (new SpineInspectorUtility.BoxScope()) { EditorGUILayout.LabelField("SkeletonData", EditorStyles.boldLabel); EditorGUILayout.PropertyField(skeletonJSON, SpineInspectorUtility.TempContent(skeletonJSON.displayName, Icons.spine)); EditorGUILayout.PropertyField(scale); } using (new SpineInspectorUtility.BoxScope()) { EditorGUILayout.LabelField("Atlas", EditorStyles.boldLabel); #if !SPINE_TK2D EditorGUILayout.PropertyField(atlasAssets, true); #else using (new EditorGUI.DisabledGroupScope(spriteCollection.objectReferenceValue != null)) { EditorGUILayout.PropertyField(atlasAssets, true); } EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel); EditorGUILayout.PropertyField(spriteCollection, true); #endif } using (new SpineInspectorUtility.BoxScope()) { EditorGUILayout.LabelField("Mix Settings", EditorStyles.boldLabel); SpineInspectorUtility.PropertyFieldWideLabel(defaultMix, DefaultMixLabel, 160); EditorGUILayout.Space(); } return; } { // Lazy initialization because accessing EditorStyles values in OnEnable during a recompile causes UnityEditor to throw null exceptions. (Unity 5.3.5) idlePlayButtonStyle = idlePlayButtonStyle ?? new GUIStyle(EditorStyles.miniButton); if (activePlayButtonStyle == null) { activePlayButtonStyle = new GUIStyle(idlePlayButtonStyle); activePlayButtonStyle.normal.textColor = Color.red; } } serializedObject.Update(); EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(target.name + " (SkeletonDataAsset)", Icons.spine), EditorStyles.whiteLargeLabel); if (m_skeletonData != null) { EditorGUILayout.LabelField("(Drag and Drop to instantiate.)", EditorStyles.miniLabel); } EditorGUI.BeginChangeCheck(); // SkeletonData using (new SpineInspectorUtility.BoxScope()) { using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.LabelField("SkeletonData", EditorStyles.boldLabel); if (m_skeletonData != null) { var sd = m_skeletonData; string m = string.Format("{8} - {0} {1}\nBones: {2}\nConstraints: \n {5} IK \n {6} Path \n {7} Transform\n\nSlots: {3}\nSkins: {4}\n\nAnimations: {9}", sd.Version, string.IsNullOrEmpty(sd.Version) ? "" : "export ", sd.Bones.Count, sd.Slots.Count, sd.Skins.Count, sd.IkConstraints.Count, sd.PathConstraints.Count, sd.TransformConstraints.Count, skeletonJSON.objectReferenceValue.name, sd.Animations.Count); EditorGUILayout.LabelField(GUIContent.none, new GUIContent(Icons.info, m), GUILayout.Width(30f)); } } EditorGUILayout.PropertyField(skeletonJSON, SpineInspectorUtility.TempContent(skeletonJSON.displayName, Icons.spine)); EditorGUILayout.PropertyField(scale); } // if (m_skeletonData != null) { // if (SpineInspectorUtility.CenteredButton(new GUIContent("Instantiate", Icons.spine, "Creates a new Spine GameObject in the active scene using this Skeleton Data.\nYou can also instantiate by dragging the SkeletonData asset from Project view into Scene View."))) // SpineEditorUtilities.ShowInstantiateContextMenu(this.m_skeletonDataAsset, Vector3.zero); // } // Atlas using (new SpineInspectorUtility.BoxScope()) { EditorGUILayout.LabelField("Atlas", EditorStyles.boldLabel); #if !SPINE_TK2D EditorGUILayout.PropertyField(atlasAssets, true); #else using (new EditorGUI.DisabledGroupScope(spriteCollection.objectReferenceValue != null)) { EditorGUILayout.PropertyField(atlasAssets, true); } EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel); EditorGUILayout.PropertyField(spriteCollection, true); #endif { bool hasNulls = false; foreach (var a in m_skeletonDataAsset.atlasAssets) { if (a == null) { hasNulls = true; break; } } if (hasNulls) { if (m_skeletonDataAsset.atlasAssets.Length == 1) { EditorGUILayout.HelpBox("Atlas array cannot have null entries!", MessageType.None); } else { EditorGUILayout.HelpBox("Atlas array should not have null entries!", MessageType.Error); if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Remove null entries"))) { var trimmedAtlasAssets = new List<AtlasAsset>(); foreach (var a in m_skeletonDataAsset.atlasAssets) { if (a != null) trimmedAtlasAssets.Add(a); } m_skeletonDataAsset.atlasAssets = trimmedAtlasAssets.ToArray(); serializedObject.Update(); } } } } } if (EditorGUI.EndChangeCheck()) { if (serializedObject.ApplyModifiedProperties()) { if (m_previewUtility != null) { m_previewUtility.Cleanup(); m_previewUtility = null; } m_skeletonDataAsset.Clear(); m_skeletonData = null; OnEnable(); // Should call RepopulateWarnings. return; } } // Some code depends on the existence of m_skeletonAnimation instance. // If m_skeletonAnimation is lazy-instantiated elsewhere, this can cause contents to change between Layout and Repaint events, causing GUILayout control count errors. InitPreview(); if (m_skeletonData != null) { GUILayout.Space(20f); using (new SpineInspectorUtility.BoxScope(false)) { EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Mix Settings", Icons.animationRoot), EditorStyles.boldLabel); DrawAnimationStateInfo(); EditorGUILayout.Space(); } EditorGUILayout.LabelField("Preview", EditorStyles.boldLabel); DrawAnimationList(); EditorGUILayout.Space(); DrawSlotList(); EditorGUILayout.Space(); DrawUnityTools(); } else { #if !SPINE_TK2D // Reimport Button using (new EditorGUI.DisabledGroupScope(skeletonJSON.objectReferenceValue == null)) { if (GUILayout.Button(SpineInspectorUtility.TempContent("Attempt Reimport", Icons.warning))) { DoReimport(); } } #else EditorGUILayout.HelpBox("Couldn't load SkeletonData.", MessageType.Error); #endif // List warnings. foreach (var line in warnings) EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(line, Icons.warning)); } if (!Application.isPlaying) serializedObject.ApplyModifiedProperties(); } void DrawUnityTools () { #if SPINE_SKELETON_ANIMATOR using (new SpineInspectorUtility.BoxScope()) { isMecanimExpanded = EditorGUILayout.Foldout(isMecanimExpanded, SpineInspectorUtility.TempContent("SkeletonAnimator", SpineInspectorUtility.UnityIcon<SceneAsset>())); if (isMecanimExpanded) { EditorGUI.indentLevel++; EditorGUILayout.PropertyField(controller, SpineInspectorUtility.TempContent("Controller", SpineInspectorUtility.UnityIcon<Animator>())); if (controller.objectReferenceValue == null) { // Generate Mecanim Controller Button using (new GUILayout.HorizontalScope()) { GUILayout.Space(EditorGUIUtility.labelWidth); if (GUILayout.Button(SpineInspectorUtility.TempContent("Generate Mecanim Controller"), GUILayout.Height(20))) SkeletonBaker.GenerateMecanimAnimationClips(m_skeletonDataAsset); } EditorGUILayout.HelpBox("SkeletonAnimator is the Mecanim alternative to SkeletonAnimation.\nIt is not required.", MessageType.Info); } else { // Update AnimationClips button. using (new GUILayout.HorizontalScope()) { GUILayout.Space(EditorGUIUtility.labelWidth); if (GUILayout.Button(SpineInspectorUtility.TempContent("Force Update AnimationClips"), GUILayout.Height(20))) SkeletonBaker.GenerateMecanimAnimationClips(m_skeletonDataAsset); } } EditorGUI.indentLevel--; } } #endif } void DoReimport () { SpineEditorUtilities.ImportSpineContent(new string[] { AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue) }, true); if (m_previewUtility != null) { m_previewUtility.Cleanup(); m_previewUtility = null; } OnEnable(); // Should call RepopulateWarnings. EditorUtility.SetDirty(m_skeletonDataAsset); } void DrawAnimationStateInfo () { using (new SpineInspectorUtility.IndentScope()) showAnimationStateData = EditorGUILayout.Foldout(showAnimationStateData, "Animation State Data"); if (!showAnimationStateData) return; EditorGUI.BeginChangeCheck(); using (new SpineInspectorUtility.IndentScope()) SpineInspectorUtility.PropertyFieldWideLabel(defaultMix, DefaultMixLabel, 160); // Do not use EditorGUIUtility.indentLevel. It will add spaces on every field. for (int i = 0; i < fromAnimation.arraySize; i++) { SerializedProperty from = fromAnimation.GetArrayElementAtIndex(i); SerializedProperty to = toAnimation.GetArrayElementAtIndex(i); SerializedProperty durationProp = duration.GetArrayElementAtIndex(i); using (new EditorGUILayout.HorizontalScope()) { GUILayout.Space(16f); EditorGUILayout.PropertyField(from, GUIContent.none); EditorGUILayout.PropertyField(to, GUIContent.none); durationProp.floatValue = EditorGUILayout.FloatField(durationProp.floatValue, GUILayout.MinWidth(25f), GUILayout.MaxWidth(60f)); if (GUILayout.Button("Delete", EditorStyles.miniButton)) { duration.DeleteArrayElementAtIndex(i); toAnimation.DeleteArrayElementAtIndex(i); fromAnimation.DeleteArrayElementAtIndex(i); } } } using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.Space(); if (GUILayout.Button("Add Mix")) { duration.arraySize++; toAnimation.arraySize++; fromAnimation.arraySize++; } EditorGUILayout.Space(); } if (EditorGUI.EndChangeCheck()) { m_skeletonDataAsset.FillStateData(); EditorUtility.SetDirty(m_skeletonDataAsset); serializedObject.ApplyModifiedProperties(); needToSerialize = true; } } void DrawAnimationList () { showAnimationList = EditorGUILayout.Foldout(showAnimationList, SpineInspectorUtility.TempContent(string.Format("Animations [{0}]", m_skeletonData.Animations.Count), Icons.animationRoot)); if (!showAnimationList) return; if (m_skeletonAnimation != null && m_skeletonAnimation.state != null) { if (GUILayout.Button(SpineInspectorUtility.TempContent("Setup Pose", Icons.skeleton), GUILayout.Width(105), GUILayout.Height(18))) { StopAnimation(); m_skeletonAnimation.skeleton.SetToSetupPose(); m_requireRefresh = true; } } else { EditorGUILayout.HelpBox("Animations can be previewed if you expand the Preview window below.", MessageType.Info); } EditorGUILayout.LabelField("Name", " Duration"); foreach (Spine.Animation animation in m_skeletonData.Animations) { using (new GUILayout.HorizontalScope()) { if (m_skeletonAnimation != null && m_skeletonAnimation.state != null) { var activeTrack = m_skeletonAnimation.state.GetCurrent(0); if (activeTrack != null && activeTrack.Animation == animation) { if (GUILayout.Button("\u25BA", activePlayButtonStyle, GUILayout.Width(24))) { StopAnimation(); } } else { if (GUILayout.Button("\u25BA", idlePlayButtonStyle, GUILayout.Width(24))) { PlayAnimation(animation.Name, true); } } } else { GUILayout.Label("-", GUILayout.Width(24)); } EditorGUILayout.LabelField(new GUIContent(animation.Name, Icons.animation), SpineInspectorUtility.TempContent(animation.Duration.ToString("f3") + "s" + ("(" + (Mathf.RoundToInt(animation.Duration * 30)) + ")").PadLeft(12, ' '))); } } } void DrawSlotList () { showSlotList = EditorGUILayout.Foldout(showSlotList, SpineInspectorUtility.TempContent("Slots", Icons.slotRoot)); if (!showSlotList) return; if (m_skeletonAnimation == null || m_skeletonAnimation.skeleton == null) return; EditorGUI.indentLevel++; showAttachments = EditorGUILayout.ToggleLeft("Show Attachments", showAttachments); var slotAttachments = new List<Attachment>(); var slotAttachmentNames = new List<string>(); var defaultSkinAttachmentNames = new List<string>(); var defaultSkin = m_skeletonData.Skins.Items[0]; Skin skin = m_skeletonAnimation.skeleton.Skin ?? defaultSkin; var slotsItems = m_skeletonAnimation.skeleton.Slots.Items; for (int i = m_skeletonAnimation.skeleton.Slots.Count - 1; i >= 0; i--) { Slot slot = slotsItems[i]; EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot)); if (showAttachments) { EditorGUI.indentLevel++; slotAttachments.Clear(); slotAttachmentNames.Clear(); defaultSkinAttachmentNames.Clear(); skin.FindNamesForSlot(i, slotAttachmentNames); skin.FindAttachmentsForSlot(i, slotAttachments); if (skin != defaultSkin) { defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames); defaultSkin.FindNamesForSlot(i, slotAttachmentNames); defaultSkin.FindAttachmentsForSlot(i, slotAttachments); } else { defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames); } for (int a = 0; a < slotAttachments.Count; a++) { Attachment attachment = slotAttachments[a]; string attachmentName = slotAttachmentNames[a]; Texture2D icon = Icons.GetAttachmentIcon(attachment); bool initialState = slot.Attachment == attachment; bool toggled = EditorGUILayout.ToggleLeft(SpineInspectorUtility.TempContent(attachmentName, icon), slot.Attachment == attachment); if (!defaultSkinAttachmentNames.Contains(attachmentName)) { Rect skinPlaceHolderIconRect = GUILayoutUtility.GetLastRect(); skinPlaceHolderIconRect.width = Icons.skinPlaceholder.width; skinPlaceHolderIconRect.height = Icons.skinPlaceholder.height; GUI.DrawTexture(skinPlaceHolderIconRect, Icons.skinPlaceholder); } if (toggled != initialState) { slot.Attachment = toggled ? attachment : null; m_requireRefresh = true; } } EditorGUI.indentLevel--; } } EditorGUI.indentLevel--; } void RepopulateWarnings () { warnings.Clear(); if (skeletonJSON.objectReferenceValue == null) { warnings.Add("Missing Skeleton JSON"); } else { if (SpineEditorUtilities.IsSpineData((TextAsset)skeletonJSON.objectReferenceValue) == false) { warnings.Add("Skeleton data file is not a valid JSON or binary file."); } else { #if SPINE_TK2D bool searchForSpineAtlasAssets = true; bool isSpriteCollectionNull = spriteCollection.objectReferenceValue == null; if (!isSpriteCollectionNull) searchForSpineAtlasAssets = false; #else const bool searchForSpineAtlasAssets = true; #endif if (searchForSpineAtlasAssets) { bool detectedNullAtlasEntry = false; var atlasList = new List<Atlas>(); var actualAtlasAssets = m_skeletonDataAsset.atlasAssets; for (int i = 0; i < actualAtlasAssets.Length; i++) { if (m_skeletonDataAsset.atlasAssets[i] == null) { detectedNullAtlasEntry = true; break; } else { atlasList.Add(actualAtlasAssets[i].GetAtlas()); } } if (detectedNullAtlasEntry) { warnings.Add("AtlasAsset elements should not be null."); } else { // Get requirements. var missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath((TextAsset)skeletonJSON.objectReferenceValue)); foreach (var atlas in atlasList) { for (int i = 0; i < missingPaths.Count; i++) { if (atlas.FindRegion(missingPaths[i]) != null) { missingPaths.RemoveAt(i); i--; } } } #if SPINE_TK2D if (missingPaths.Count > 0) warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets."); #endif foreach (var str in missingPaths) warnings.Add("Missing Region: '" + str + "'"); } } } } } #region Preview Window PreviewRenderUtility m_previewUtility; GameObject m_previewInstance; Vector2 previewDir; SkeletonAnimation m_skeletonAnimation; static readonly int SliderHash = "Slider".GetHashCode(); float m_lastTime; bool m_playing; bool m_requireRefresh; Color m_originColor = new Color(0.3f, 0.3f, 0.3f, 1); void StopAnimation () { if (m_skeletonAnimation == null) { Debug.LogWarning("Animation was stopped but preview doesn't exist. It's possible that the Preview Panel is closed."); } m_skeletonAnimation.state.ClearTrack(0); m_playing = false; } List<Spine.Event> m_animEvents = new List<Spine.Event>(); List<float> m_animEventFrames = new List<float>(); void PlayAnimation (string animName, bool loop) { m_animEvents.Clear(); m_animEventFrames.Clear(); m_skeletonAnimation.state.SetAnimation(0, animName, loop); Spine.Animation a = m_skeletonAnimation.state.GetCurrent(0).Animation; foreach (Timeline t in a.Timelines) { if (t.GetType() == typeof(EventTimeline)) { var et = (EventTimeline)t; for (int i = 0; i < et.Events.Length; i++) { m_animEvents.Add(et.Events[i]); m_animEventFrames.Add(et.Frames[i]); } } } m_playing = true; } void InitPreview () { if (this.m_previewUtility == null) { this.m_lastTime = Time.realtimeSinceStartup; this.m_previewUtility = new PreviewRenderUtility(true); var c = this.m_previewUtility.camera; c.orthographic = true; c.orthographicSize = 1; c.cullingMask = -2147483648; c.nearClipPlane = 0.01f; c.farClipPlane = 1000f; this.CreatePreviewInstances(); } } void CreatePreviewInstances () { this.DestroyPreviewInstances(); if (warnings.Count > 0) { m_skeletonDataAsset.Clear(); return; } var skeletonDataAsset = (SkeletonDataAsset)target; if (skeletonDataAsset.GetSkeletonData(false) == null) return; if (this.m_previewInstance == null) { string skinName = EditorPrefs.GetString(m_skeletonDataAssetGUID + "_lastSkin", ""); try { m_previewInstance = SpineEditorUtilities.InstantiateSkeletonAnimation(skeletonDataAsset, skinName).gameObject; if (m_previewInstance != null) { m_previewInstance.hideFlags = HideFlags.HideAndDontSave; m_previewInstance.layer = 0x1f; m_skeletonAnimation = m_previewInstance.GetComponent<SkeletonAnimation>(); m_skeletonAnimation.initialSkinName = skinName; m_skeletonAnimation.LateUpdate(); m_skeletonData = m_skeletonAnimation.skeletonDataAsset.GetSkeletonData(true); m_previewInstance.GetComponent<Renderer>().enabled = false; m_initialized = true; } AdjustCameraGoals(true); } catch { DestroyPreviewInstances(); } } } void DestroyPreviewInstances () { if (this.m_previewInstance != null) { DestroyImmediate(this.m_previewInstance); m_previewInstance = null; } m_initialized = false; } public override bool HasPreviewGUI () { if (serializedObject.isEditingMultipleObjects) { // JOHN: Implement multi-preview. return false; } for (int i = 0; i < atlasAssets.arraySize; i++) { var prop = atlasAssets.GetArrayElementAtIndex(i); if (prop.objectReferenceValue == null) return false; } return skeletonJSON.objectReferenceValue != null; } Texture m_previewTex = new Texture(); public override void OnInteractivePreviewGUI (Rect r, GUIStyle background) { this.InitPreview(); if (Event.current.type == EventType.Repaint) { if (m_requireRefresh) { this.m_previewUtility.BeginPreview(r, background); this.DoRenderPreview(true); this.m_previewTex = this.m_previewUtility.EndPreview(); m_requireRefresh = false; } if (this.m_previewTex != null) GUI.DrawTexture(r, m_previewTex, ScaleMode.StretchToFill, false); } DrawSkinToolbar(r); NormalizedTimeBar(r); // MITCH: left a todo: Implement panning // this.previewDir = Drag2D(this.previewDir, r); MouseScroll(r); } float m_orthoGoal = 1; Vector3 m_posGoal = new Vector3(0, 0, -10); double m_adjustFrameEndTime = 0; void AdjustCameraGoals (bool calculateMixTime) { if (this.m_previewInstance == null) return; if (calculateMixTime) { if (m_skeletonAnimation.state.GetCurrent(0) != null) m_adjustFrameEndTime = EditorApplication.timeSinceStartup + m_skeletonAnimation.state.GetCurrent(0).Alpha; } GameObject go = this.m_previewInstance; Bounds bounds = go.GetComponent<Renderer>().bounds; m_orthoGoal = bounds.size.y; m_posGoal = bounds.center + new Vector3(0, 0, -10f); } void AdjustCameraGoals () { AdjustCameraGoals(false); } void AdjustCamera () { if (m_previewUtility == null) return; if (EditorApplication.timeSinceStartup < m_adjustFrameEndTime) AdjustCameraGoals(); float orthoSet = Mathf.Lerp(this.m_previewUtility.camera.orthographicSize, m_orthoGoal, 0.1f); this.m_previewUtility.camera.orthographicSize = orthoSet; float dist = Vector3.Distance(m_previewUtility.camera.transform.position, m_posGoal); if(dist > 0f) { Vector3 pos = Vector3.Lerp(this.m_previewUtility.camera.transform.position, m_posGoal, 0.1f); pos.x = 0; this.m_previewUtility.camera.transform.position = pos; this.m_previewUtility.camera.transform.rotation = Quaternion.identity; m_requireRefresh = true; } } void DoRenderPreview (bool drawHandles) { GameObject go = this.m_previewInstance; if (m_requireRefresh && go != null) { go.GetComponent<Renderer>().enabled = true; if (!EditorApplication.isPlaying) m_skeletonAnimation.Update((Time.realtimeSinceStartup - m_lastTime)); m_lastTime = Time.realtimeSinceStartup; if (!EditorApplication.isPlaying) m_skeletonAnimation.LateUpdate(); if (drawHandles) { Handles.SetCamera(m_previewUtility.camera); Handles.color = m_originColor; Handles.DrawLine(new Vector3(-1000 * m_skeletonDataAsset.scale, 0, 0), new Vector3(1000 * m_skeletonDataAsset.scale, 0, 0)); Handles.DrawLine(new Vector3(0, 1000 * m_skeletonDataAsset.scale, 0), new Vector3(0, -1000 * m_skeletonDataAsset.scale, 0)); } this.m_previewUtility.camera.Render(); if (drawHandles) { Handles.SetCamera(m_previewUtility.camera); SpineHandles.DrawBoundingBoxes(m_skeletonAnimation.transform, m_skeletonAnimation.skeleton); if (showAttachments) SpineHandles.DrawPaths(m_skeletonAnimation.transform, m_skeletonAnimation.skeleton); } go.GetComponent<Renderer>().enabled = false; } } void EditorUpdate () { AdjustCamera(); if (m_playing) { m_requireRefresh = true; Repaint(); } else if (m_requireRefresh) { Repaint(); } //else { //only needed if using smooth menus //} if (needToSerialize) { needToSerialize = false; serializedObject.ApplyModifiedProperties(); } } void DrawSkinToolbar (Rect r) { if (m_skeletonAnimation == null) return; if (m_skeletonAnimation.skeleton != null) { string label = (m_skeletonAnimation.skeleton != null && m_skeletonAnimation.skeleton.Skin != null) ? m_skeletonAnimation.skeleton.Skin.Name : "default"; Rect popRect = new Rect(r); popRect.y += 32; popRect.x += 4; popRect.height = 24; popRect.width = 40; EditorGUI.DropShadowLabel(popRect, SpineInspectorUtility.TempContent("Skin")); popRect.y += 11; popRect.width = 150; popRect.x += 44; if (GUI.Button(popRect, SpineInspectorUtility.TempContent(label, Icons.skin), EditorStyles.popup)) { DrawSkinDropdown(); } } } void NormalizedTimeBar (Rect r) { if (m_skeletonAnimation == null) return; Rect barRect = new Rect(r); barRect.height = 32; barRect.x += 4; barRect.width -= 4; GUI.Box(barRect, ""); Rect lineRect = new Rect(barRect); float width = lineRect.width; TrackEntry t = m_skeletonAnimation.state.GetCurrent(0); if (t != null) { int loopCount = (int)(t.TrackTime / t.TrackEnd); float currentTime = t.TrackTime - (t.TrackEnd * loopCount); float normalizedTime = currentTime / t.Animation.Duration; float wrappedTime = normalizedTime % 1; lineRect.x = barRect.x + (width * wrappedTime) - 0.5f; lineRect.width = 2; GUI.color = Color.red; GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture); GUI.color = Color.white; for (int i = 0; i < m_animEvents.Count; i++) { float fr = m_animEventFrames[i]; var evRect = new Rect(barRect); evRect.x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (Icons.userEvent.width / 2), barRect.x, float.MaxValue); evRect.width = Icons.userEvent.width; evRect.height = Icons.userEvent.height; evRect.y += Icons.userEvent.height; GUI.DrawTexture(evRect, Icons.userEvent); Event ev = Event.current; if (ev.type == EventType.Repaint) { if (evRect.Contains(ev.mousePosition)) { Rect tooltipRect = new Rect(evRect); GUIStyle tooltipStyle = EditorStyles.helpBox; tooltipRect.width = tooltipStyle.CalcSize(new GUIContent(m_animEvents[i].Data.Name)).x; tooltipRect.y -= 4; tooltipRect.x += 4; GUI.Label(tooltipRect, m_animEvents[i].Data.Name, tooltipStyle); GUI.tooltip = m_animEvents[i].Data.Name; } } } } } void MouseScroll (Rect position) { Event current = Event.current; int controlID = GUIUtility.GetControlID(SliderHash, FocusType.Passive); switch (current.GetTypeForControl(controlID)) { case EventType.ScrollWheel: if (position.Contains(current.mousePosition)) { m_orthoGoal += current.delta.y * 0.06f; m_orthoGoal = Mathf.Max(0.01f, m_orthoGoal); GUIUtility.hotControl = controlID; current.Use(); } break; } } // MITCH: left todo: Implement preview panning /* static Vector2 Drag2D(Vector2 scrollPosition, Rect position) { int controlID = GUIUtility.GetControlID(sliderHash, FocusType.Passive); UnityEngine.Event current = UnityEngine.Event.current; switch (current.GetTypeForControl(controlID)) { case EventType.MouseDown: if (position.Contains(current.mousePosition) && (position.width > 50f)) { GUIUtility.hotControl = controlID; current.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } return scrollPosition; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; } EditorGUIUtility.SetWantsMouseJumping(0); return scrollPosition; case EventType.MouseMove: return scrollPosition; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { scrollPosition -= (Vector2) (((current.delta * (!current.shift ? ((float) 1) : ((float) 3))) / Mathf.Min(position.width, position.height)) * 140f); scrollPosition.y = Mathf.Clamp(scrollPosition.y, -90f, 90f); current.Use(); GUI.changed = true; } return scrollPosition; } return scrollPosition; } */ public override GUIContent GetPreviewTitle () { return SpineInspectorUtility.TempContent("Preview"); } public override void OnPreviewSettings () { const float SliderWidth = 100; if (!m_initialized) { GUILayout.HorizontalSlider(0, 0, 2, GUILayout.MaxWidth(SliderWidth)); } else { float speed = GUILayout.HorizontalSlider(m_skeletonAnimation.timeScale, 0, 2, GUILayout.MaxWidth(SliderWidth)); const float SliderSnap = 0.25f; float y = speed / SliderSnap; int q = Mathf.RoundToInt(y); speed = q * SliderSnap; m_skeletonAnimation.timeScale = speed; } } public override Texture2D RenderStaticPreview (string assetPath, UnityEngine.Object[] subAssets, int width, int height) { var tex = new Texture2D(width, height, TextureFormat.ARGB32, false); this.InitPreview(); if (this.m_previewUtility.camera == null) return null; m_requireRefresh = true; this.DoRenderPreview(false); AdjustCameraGoals(false); this.m_previewUtility.camera.orthographicSize = m_orthoGoal / 2; this.m_previewUtility.camera.transform.position = m_posGoal; this.m_previewUtility.BeginStaticPreview(new Rect(0, 0, width, height)); this.DoRenderPreview(false); tex = this.m_previewUtility.EndStaticPreview(); return tex; } #endregion #region Skin Dropdown Context Menu void DrawSkinDropdown () { var menu = new GenericMenu(); foreach (Skin s in m_skeletonData.Skins) menu.AddItem(new GUIContent(s.Name, Icons.skin), this.m_skeletonAnimation.skeleton.Skin == s, SetSkin, s); menu.ShowAsContext(); } void SetSkin (object o) { Skin skin = (Skin)o; m_skeletonAnimation.initialSkinName = skin.Name; m_skeletonAnimation.Initialize(true); m_requireRefresh = true; EditorPrefs.SetString(m_skeletonDataAssetGUID + "_lastSkin", skin.Name); } #endregion } }
/************************************************************************************ 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. ************************************************************************************/ //#define OVR_USE_PROJ_MATRIX using System; using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> [ExecuteInEditMode] public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> public float movement_gain = 1.0f; private Camera leftEyeCamera; /// <summary> /// The right eye camera. /// </summary> private Camera rightEyeCamera; /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } private bool needsCameraConfigure; #region Unity Messages private void Awake() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; needsCameraConfigure = true; } private void Start() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } private void LateUpdate() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateCameras(); UpdateAnchors(); } #endregion private void UpdateAnchors() { OVRPose leftEye = OVRManager.display.GetEyePose(OVREye.Left); OVRPose rightEye = OVRManager.display.GetEyePose(OVREye.Right); leftEyeAnchor.localRotation = leftEye.orientation; centerEyeAnchor.localRotation = leftEye.orientation; // using left eye for now rightEyeAnchor.localRotation = rightEye.orientation; Vector3 dif = (leftEye.position - rightEye.position) * 0.5f; Vector3 center = movement_gain* 0.5f * (leftEye.position + rightEye.position); leftEyeAnchor.localPosition = dif + center; centerEyeAnchor.localPosition = center; rightEyeAnchor.localPosition = center - dif; } private void UpdateCameras() { if (needsCameraConfigure) { leftEyeCamera = ConfigureCamera(OVREye.Left); rightEyeCamera = ConfigureCamera(OVREye.Right); #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX OVRManager.display.ForceSymmetricProj(false); #else OVRManager.display.ForceSymmetricProj(true); #endif needsCameraConfigure = false; #endif } } private void EnsureGameObjectIntegrity() { if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(OVREye.Left); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(OVREye.Center); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(OVREye.Right); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.GetComponent<Camera>(); if (leftEyeCamera == null) { leftEyeCamera = leftEyeAnchor.gameObject.AddComponent<Camera>(); } } if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.GetComponent<Camera>(); if (rightEyeCamera == null) { rightEyeCamera = rightEyeAnchor.gameObject.AddComponent<Camera>(); } } } private Transform ConfigureEyeAnchor(OVREye eye) { string name = eye.ToString() + "EyeAnchor"; Transform anchor = transform.Find(name); if (anchor == null) { string oldName = "Camera" + eye.ToString(); anchor = transform.Find(oldName); } if (anchor == null) anchor = new GameObject(name).transform; anchor.parent = transform; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Camera ConfigureCamera(OVREye eye) { Transform anchor = (eye == OVREye.Left) ? leftEyeAnchor : rightEyeAnchor; Camera cam = anchor.GetComponent<Camera>(); OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(eye); cam.fieldOfView = eyeDesc.fov.y; cam.aspect = eyeDesc.resolution.x / eyeDesc.resolution.y; cam.rect = new Rect(0f, 0f, OVRManager.instance.virtualTextureScale, OVRManager.instance.virtualTextureScale); cam.targetTexture = OVRManager.display.GetEyeTexture(eye); #if !UNITY_ANDROID || UNITY_EDITOR #if OVR_USE_PROJ_MATRIX cam.projectionMatrix = OVRManager.display.GetProjection((int)eye, cam.nearClipPlane, cam.farClipPlane); #endif #endif return cam; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; using System.Threading; #if MERGED_DLL using Microsoft.Cci.MutableCodeModel; #endif #if !NO_METADATA_HELPER using Microsoft.Cci.UtilityDataStructures; #endif namespace Microsoft.Cci { /// <summary> /// Fixed size array wrapped as IReadOnlyList{T} /// Construct with known size N, call Add N times, Freeze, and then use as IReadOnlyList{T} or IEnumerable{T} /// </summary> /// <typeparam name="T"></typeparam> /// <remarks>Optimization for List list = new List{T}(); list.Add() list.Add() ...; list.TrimExcess(); list.AsReadOnly() </remarks> internal class ReadOnlyList<T> : IReadOnlyList<T> { T[] m_data; int m_count; // item count during construction, -1 for frozen state /// <summary> /// Constructor /// </summary> public ReadOnlyList(int capacity) { if (capacity == 0) { m_data = ArrayT<T>.Empty; } else { m_data = new T[capacity]; } } /// <summary> /// Creation helper /// </summary> public static ReadOnlyList<T> Create(uint uCount) { int count = (int) uCount; if (count <= 0) { return null; } else { return new ReadOnlyList<T>(count); } } /// <summary> /// Creation helper from IEnumerable{T} /// </summary> public static ReadOnlyList<T> Create(IEnumerable<T> list) { return Create(IteratorHelper.EnumerableCount<T>(list)); } /// <summary> /// Freeze to be read-only /// </summary> public static IEnumerable<T> Freeze(ReadOnlyList<T> list) { if (list == null) { return Enumerable<T>.Empty; } else { Debug.Assert(list.m_data.Length == list.m_count); list.m_count = -1; return list; } } /// <summary> /// Append item /// </summary> public void Add(T item) { if (m_count < 0) { throw new NotSupportedException("ReadOnlyList is frozen"); } m_data[m_count ++] = item; } /// <summary> /// Count of total allowed items /// </summary> public int Count { get { return m_data.Length; } } /// <summary> /// Return an item /// </summary> public T this[int index] { get { return m_data[index]; } } public IEnumerator<T> GetEnumerator() { IEnumerable<T> data = m_data; return data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { IEnumerable data = m_data; return data.GetEnumerator(); } } /// <summary> /// Virtual IReadOnlyList + its enumerator /// </summary> /// <remarks>Borrowed from the internal implementation of "yield return", IEnumerable and IEnumerator are implemented in the /// same class here, to save one extra allocation for the most common usage pattern of single enumerator in the same thread. /// /// This class is used mostly by SingletonList. There are quite a few CCI objects which store single object inside by needs to return IEnumerable from it. /// This is used in super high frequency (e.g. BaseClasses) that we need to reduce memory allocation and CPU cost for it. /// /// This solution is better replacement for GetSingletonEnumerable which just uses "yield return": /// 1) There only needs to be single implementation. /// 2) All the source code is here. /// 3) IReadOnlyList is implemented so caller can query for Count and this[index] without going through enumerator at all. /// </remarks> /// <typeparam name="T"></typeparam> internal abstract class VirtualReadOnlyList<T> : IReadOnlyList<T>, IEnumerator<T>, IEnumerator { const int GetEnumeratorNotCalled = -2; int m_initialThreadId; int m_count; int m_index; public VirtualReadOnlyList(int count) { m_count = count; m_index = GetEnumeratorNotCalled; m_initialThreadId = Environment.CurrentManagedThreadId; } public int Count { get { return m_count; } } /// <summary> /// One method to be implemented in derived classes /// </summary> public abstract T GetItem(int index); public T this[int index] { get { return GetItem(index); } } public bool MoveNext() { if (this.m_index == GetEnumeratorNotCalled) { throw new InvalidOperationException("GetEnumerator not called"); } m_index ++; return (m_index >= 0) && (m_index < Count); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { // First time calling GetEnumerator from the same thread, return itself if ((Environment.CurrentManagedThreadId == m_initialThreadId) && (this.m_index == GetEnumeratorNotCalled)) { m_index = -1; return this; } // Need to create a new enumerator return new ReadOnlyListEnumerator<T>(this); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } void IEnumerator.Reset() { if (this.m_index == GetEnumeratorNotCalled) { throw new InvalidOperationException("GetEnumerator not called"); } m_index = -1; } void IDisposable.Dispose() { } T IEnumerator<T>.Current { get { return GetItem(m_index); } } object IEnumerator.Current { get { return GetItem(m_index); } } } /// <summary> /// Enumerator for IReadOnlyList /// </summary> /// <typeparam name="T"></typeparam> internal struct ReadOnlyListEnumerator<T> : IEnumerator<T>, IEnumerator { IReadOnlyList<T> m_list; int m_index; public ReadOnlyListEnumerator(IReadOnlyList<T> list) { m_list = list; m_index = -1; } public int Count { get { return m_list.Count; } } public T this[int index] { get { return m_list[index]; } } public bool MoveNext() { m_index ++; return (m_index >= 0) && (m_index < m_list.Count); } void IEnumerator.Reset() { m_index = -1; } void IDisposable.Dispose() { m_list = null; } T IEnumerator<T>.Current { get { return m_list[m_index]; } } object IEnumerator.Current { get { return m_list[m_index]; } } } /// <summary> /// IReadOnlyList wrapper for single item, + its enumerator (similar to yield return) /// </summary> /// <typeparam name="T"></typeparam> internal class SingletonList<T> : VirtualReadOnlyList<T> { T m_current; public SingletonList(T value) : base(1) { m_current = value; } public override T GetItem(int index) { if (index == 0) { return m_current; } else { throw new ArgumentOutOfRangeException("index"); } } } /// <summary> /// Caching 10 StringBuilders per thread (for nested usage) /// </summary> internal static class StringBuilderCache { [ThreadStatic] private static StringBuilder[] ts_CachedInstances; private static int s_Capacity = 64; /// <summary> /// Get StringBuilder array /// </summary> private static StringBuilder[] GetList() { StringBuilder[] list = ts_CachedInstances; if (list == null) { list = new StringBuilder[10]; ts_CachedInstances = list; } return list; } /// <summary> /// Acquire a StringBuilder /// </summary> public static StringBuilder Acquire() { StringBuilder[] list = GetList(); // Grab from cache for (int i = 0; i < list.Length; i++) { if (list[i] != null) { StringBuilder sb = list[i]; list[i] = null; sb.Clear(); return sb; } } // Create new one return new StringBuilder(s_Capacity); } /// <summary> /// Release StringBuilder to cache /// </summary> public static void Release(StringBuilder sb) { // If the StringBuilder's capacity is larger than our capacity, then it could be multi-chunk StringBuilder // Which is inefficient to use. Reject it, but enlarge our capacity, so that new StringBuilder created here will be larger. if (sb.Capacity > s_Capacity) { s_Capacity = sb.Capacity; } else // return to cache { StringBuilder[] list = GetList(); for (int i = 0; i < list.Length; i++) { if (list[i] == null) { list[i] = sb; break; } } } } /// <summary> /// Release StringBuilder to cache, after getting string from it /// </summary> public static string GetStringAndRelease(StringBuilder sb) { string result = sb.ToString(); Release(sb); return result; } public static void FastAppend(this StringBuilder sb, int val) { if ((val >= 0) && (val < 10)) { sb.Append((char)('0' + val)); } else { sb.Append(val); } } } #if !NO_METADATA_HELPER /// <summary> /// Reusing Containers /// </summary> internal static class ContainerCache { internal class Containers { internal Dictionary<object, object> m_objectDictionary; internal SetOfObjects m_setOfObjects; internal Hashtable<object, object> m_hashTable1; internal Hashtable<object, object> m_hashTable2; internal Hashtable<IReference, object> m_refHashTable; } internal static T Acquire<T>(ref T field) where T : class { T result = field; if (result != null) { field = null; } return result; } internal static T Acquire<T>(ref T field1, ref T field2) where T : class { T result = field1; if (result != null) { field1 = null; } else { result = field2; if (result != null) { field2 = null; } } return result; } internal static void Release<T>(ref T field1, ref T field2, T container) where T : class { if (field1 == null) { field1 = container; } else { field2 = container; } } [ThreadStatic] private static Containers ts_CachedContainers; internal static Containers GetContainers() { if (ts_CachedContainers == null) { ts_CachedContainers = new Containers(); } return ts_CachedContainers; } /// <summary> /// Acquire a Dictionary /// </summary> public static Dictionary<object, object> AcquireObjectDictionary() { Dictionary<object, object> result = Acquire(ref GetContainers().m_objectDictionary); if (result != null) { result.Clear(); } else { result = new Dictionary<object, object>(); } return result; } /// <summary> /// Release Dictionary to cache /// </summary> public static void Release(Dictionary<object, object> dic) { if (dic != null) { dic.Clear(); GetContainers().m_objectDictionary = dic; } } public static SetOfObjects AcquireSetOfObjects(uint capacity) { SetOfObjects result = Acquire(ref GetContainers().m_setOfObjects); if (result != null) { result.Clear(); } else { result = new SetOfObjects(capacity); } return result; } public static void ReleaseSetOfObjects(ref SetOfObjects setOfObjects) { if (setOfObjects != null) { setOfObjects.Clear(); GetContainers().m_setOfObjects = setOfObjects; setOfObjects = null; } } public static Hashtable<object, object> AcquireHashtable(uint capacity) { Containers cache = GetContainers(); Hashtable<object, object> result = Acquire(ref cache.m_hashTable1, ref cache.m_hashTable2); if (result != null) { result.Clear(); } else { result = new Hashtable<object, object>(capacity); } return result; } public static void ReleaseHashtable(ref Hashtable<object, object> hashTable) { if (hashTable != null) { Containers cache = GetContainers(); hashTable.Clear(); Release(ref cache.m_hashTable1, ref cache.m_hashTable2, hashTable); hashTable = null; } } public static Hashtable<IReference, object> AcquireRefHashtable(uint capacity) { Containers cache = GetContainers(); Hashtable<IReference, object> result = Acquire(ref cache.m_refHashTable); if (result != null) { // Console.WriteLine("AcquireRefHashtable"); result.Clear(); } else { result = new Hashtable<IReference, object>(capacity); } return result; } public static void ReleaseRefHashtable(ref Hashtable<IReference, object> hashTable) { if (hashTable != null) { // Console.WriteLine("ReleaseRefHashTable"); hashTable.Clear(); GetContainers().m_refHashTable = hashTable; hashTable = null; } } } #endif /// <summary> /// Array related helpers /// </summary> /// <typeparam name="T"></typeparam> internal static class ArrayT<T> { readonly static T[] s_empty = new T[0]; static internal T[] Empty { get { return s_empty; } } static internal T[] Create(int count) { if (count == 0) { return s_empty; } else { return new T[count]; } } } internal static partial class Toolbox { internal static string GetString(uint n) { switch (n) { case 0: return "0"; case 1: return "1"; case 2: return "2"; case 3: return "3"; case 4: return "4"; case 5: return "5"; case 6: return "6"; case 7: return "7"; case 8: return "8"; case 9: return "9"; default: return n.ToString(); } } internal static string GetLocalName(uint n) { switch (n) { case 0: return "local_0"; case 1: return "local_1"; case 2: return "local_2"; case 3: return "local_3"; case 4: return "local_4"; case 5: return "local_5"; case 6: return "local_6"; case 7: return "local_7"; case 8: return "local_8"; case 9: return "local_9"; default: return "local_" + n; } } public static EnumerableAdapter<T> Adapter<T>(this IEnumerable<T> en) { return new EnumerableAdapter<T>(en); } public static void IncreaseCapacity<T>(this List<T> list, int count) { list.Capacity = list.Count + count; } /// <summary> /// Getting read-only IEnumerable{T} from List{T} /// Read-only is only enforced in DEBUG build to catch programming errors. In release mode, we just return the original list for performance /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> internal static IEnumerable<T> ToReadOnly<T>(this List<T> list) { if (list == null) return Enumerable<T>.Empty; else #if DEBUG return list.AsReadOnly(); #else return list; #endif } } /// <summary> /// Wrapper around IEnumerable{T}, optimized for IReadOnlyList{T} /// </summary> /// <typeparam name="T"></typeparam> internal struct EnumerableAdapter<T> { IEnumerator<T> m_enum; IReadOnlyList<T> m_list; int m_pos; public EnumerableAdapter(IEnumerable<T> en) { m_list = en as IReadOnlyList<T>; m_pos = -1; if (m_list == null) { m_enum = en.GetEnumerator(); } else { m_enum = null; } } public T Current { get { if (m_list != null) { return m_list[m_pos]; } else { return m_enum.Current; } } } public bool MoveNext() { if (m_list != null) { m_pos++; return m_pos < m_list.Count; } else { return m_enum.MoveNext(); } } public void Dispose() { } public EnumerableAdapter<T> GetEnumerator() { return this; } } #if MERGED_DLL /// <summary> /// Fast visitor: Assembly -> Module -> Namespace -> TypeDef -> MethodDef /// </summary> internal class MethodVisitor { protected IMetadataHost host; public MethodVisitor(IMetadataHost host = null) { this.host = host; } public virtual void VisitAssembly(Assembly assembly) { if (assembly.MemberModules != null) { for (int i = 0; i < assembly.MemberModules.Count; i++) { VisitModule(assembly.MemberModules[i] as Module); } } VisitModule(assembly); } public virtual void VisitModule(Module module) { VisitNamespace(module.UnitNamespaceRoot as UnitNamespace); } public virtual void VisitNamespace(UnitNamespace unitNamespace) { if (unitNamespace.Members == null) { return; } for (int i = 0; i < unitNamespace.Members.Count; i++) { INamespaceMember member = unitNamespace.Members[i]; MethodDefinition methodDef = member as MethodDefinition; if (methodDef != null) { VisitMethod(methodDef, null); continue; } NamespaceTypeDefinition typeDef = member as NamespaceTypeDefinition; if (typeDef != null) { VisitType(typeDef); continue; } UnitNamespace ns = member as UnitNamespace; if (ns != null) { VisitNamespace(ns); } else { throw new InvalidOperationException("INamespaceMember"); } } } public virtual void VisitType(NamedTypeDefinition typeDef) { if (typeDef.Methods != null) { for (int i = 0; i < typeDef.Methods.Count; i++) { VisitMethod(typeDef.Methods[i] as MethodDefinition, typeDef); } } if (typeDef.NestedTypes != null) { for (int i = 0; i < typeDef.NestedTypes.Count; i++) { VisitType(typeDef.NestedTypes[i] as NamedTypeDefinition); } } } public virtual void VisitMethod(MethodDefinition methodDef, NamedTypeDefinition typeDef) { } } #endif [Flags] internal enum OperationValueKind { None = 0x000, Scalar = 0x001, String = 0x002, JumpOffset = 0x004, JumpOffsetArray = 0x008, Parameter = 0x010, Local = 0x020, Field = 0x040, Extra = 0x080, Type = 0x100, Method = 0x200, TypeMember = 0x400, // ITypeMemeberReference FunctionPointerType = Type | Extra, // Treat it asITypeReference RuntimeHandle = Type | Field | Method | TypeMember, Any = 0xFFFF } internal static partial class Toolbox { internal static bool MaybeType(this OperationValueKind kind) { return (kind & OperationValueKind.Type) == OperationValueKind.Type; } internal static bool MaybeField(this OperationValueKind kind) { return (kind & OperationValueKind.Field) == OperationValueKind.Field; } internal static bool MaybeMethod(this OperationValueKind kind) { return (kind & OperationValueKind.Method) == OperationValueKind.Method; } internal static bool MaybeParameter(this OperationValueKind kind) { return (kind & OperationValueKind.Parameter) == OperationValueKind.Parameter; } internal static bool MaybeLocal(this OperationValueKind kind) { return (kind & OperationValueKind.Local) == OperationValueKind.Local; } internal static OperationValueKind ValueKind(this OperationCode cilOpCode) { switch (cilOpCode) { case OperationCode.Nop: case OperationCode.Break: break; case OperationCode.Ldarg_0: case OperationCode.Ldarg_1: case OperationCode.Ldarg_2: case OperationCode.Ldarg_3: return OperationValueKind.Parameter; case OperationCode.Ldloc_0: case OperationCode.Ldloc_1: case OperationCode.Ldloc_2: case OperationCode.Ldloc_3: return OperationValueKind.Local; case OperationCode.Stloc_0: case OperationCode.Stloc_1: case OperationCode.Stloc_2: case OperationCode.Stloc_3: return OperationValueKind.Local; case OperationCode.Ldarg_S: case OperationCode.Ldarga_S: case OperationCode.Starg_S: return OperationValueKind.Parameter; case OperationCode.Ldloc_S: case OperationCode.Ldloca_S: case OperationCode.Stloc_S: return OperationValueKind.Local; case OperationCode.Ldnull: break; case OperationCode.Ldc_I4_M1: case OperationCode.Ldc_I4_0: case OperationCode.Ldc_I4_1: case OperationCode.Ldc_I4_2: case OperationCode.Ldc_I4_3: case OperationCode.Ldc_I4_4: case OperationCode.Ldc_I4_5: case OperationCode.Ldc_I4_6: case OperationCode.Ldc_I4_7: case OperationCode.Ldc_I4_8: return OperationValueKind.Scalar; case OperationCode.Ldc_I4_S: return OperationValueKind.Scalar; case OperationCode.Ldc_I4: return OperationValueKind.Scalar; case OperationCode.Ldc_I8: return OperationValueKind.Scalar; case OperationCode.Ldc_R4: return OperationValueKind.Scalar; case OperationCode.Ldc_R8: return OperationValueKind.Scalar; case OperationCode.Dup: case OperationCode.Pop: break; case OperationCode.Jmp: return OperationValueKind.Method; // For Get(), Set() and Address() on arrays, the runtime provides method implementations. // Hence, CCI2 replaces these with pseudo instructions Array_Set, Array_Get and Array_Addr. // All other methods on arrays will not use pseudo instruction and will have methodReference as their operand. case OperationCode.Array_Set: case OperationCode.Array_Get: case OperationCode.Array_Addr: case OperationCode.Array_Create_WithLowerBound: case OperationCode.Array_Create: return OperationValueKind.Type; case OperationCode.Call: return OperationValueKind.Method; case OperationCode.Calli: return OperationValueKind.FunctionPointerType; case OperationCode.Ret: break; case OperationCode.Br_S: case OperationCode.Brfalse_S: case OperationCode.Brtrue_S: case OperationCode.Beq_S: case OperationCode.Bge_S: case OperationCode.Bgt_S: case OperationCode.Ble_S: case OperationCode.Blt_S: case OperationCode.Bne_Un_S: case OperationCode.Bge_Un_S: case OperationCode.Bgt_Un_S: case OperationCode.Ble_Un_S: case OperationCode.Blt_Un_S: return OperationValueKind.JumpOffset; case OperationCode.Br: case OperationCode.Brfalse: case OperationCode.Brtrue: case OperationCode.Beq: case OperationCode.Bge: case OperationCode.Bgt: case OperationCode.Ble: case OperationCode.Blt: case OperationCode.Bne_Un: case OperationCode.Bge_Un: case OperationCode.Bgt_Un: case OperationCode.Ble_Un: case OperationCode.Blt_Un: return OperationValueKind.JumpOffset; case OperationCode.Switch: return OperationValueKind.JumpOffsetArray; case OperationCode.Ldind_I1: case OperationCode.Ldind_U1: case OperationCode.Ldind_I2: case OperationCode.Ldind_U2: case OperationCode.Ldind_I4: case OperationCode.Ldind_U4: case OperationCode.Ldind_I8: case OperationCode.Ldind_I: case OperationCode.Ldind_R4: case OperationCode.Ldind_R8: case OperationCode.Ldind_Ref: case OperationCode.Stind_Ref: case OperationCode.Stind_I1: case OperationCode.Stind_I2: case OperationCode.Stind_I4: case OperationCode.Stind_I8: case OperationCode.Stind_R4: case OperationCode.Stind_R8: case OperationCode.Add: case OperationCode.Sub: case OperationCode.Mul: case OperationCode.Div: case OperationCode.Div_Un: case OperationCode.Rem: case OperationCode.Rem_Un: case OperationCode.And: case OperationCode.Or: case OperationCode.Xor: case OperationCode.Shl: case OperationCode.Shr: case OperationCode.Shr_Un: case OperationCode.Neg: case OperationCode.Not: case OperationCode.Conv_I1: case OperationCode.Conv_I2: case OperationCode.Conv_I4: case OperationCode.Conv_I8: case OperationCode.Conv_R4: case OperationCode.Conv_R8: case OperationCode.Conv_U4: case OperationCode.Conv_U8: break; case OperationCode.Callvirt: return OperationValueKind.Method; case OperationCode.Cpobj: case OperationCode.Ldobj: return OperationValueKind.Type; case OperationCode.Ldstr: return OperationValueKind.String; case OperationCode.Newobj: return OperationValueKind.Method; case OperationCode.Castclass: case OperationCode.Isinst: return OperationValueKind.Type; case OperationCode.Conv_R_Un: break; case OperationCode.Unbox: return OperationValueKind.Type; case OperationCode.Throw: break; case OperationCode.Ldfld: case OperationCode.Ldflda: case OperationCode.Stfld: return OperationValueKind.Field; case OperationCode.Ldsfld: case OperationCode.Ldsflda: case OperationCode.Stsfld: return OperationValueKind.Field; case OperationCode.Stobj: return OperationValueKind.Type; case OperationCode.Conv_Ovf_I1_Un: case OperationCode.Conv_Ovf_I2_Un: case OperationCode.Conv_Ovf_I4_Un: case OperationCode.Conv_Ovf_I8_Un: case OperationCode.Conv_Ovf_U1_Un: case OperationCode.Conv_Ovf_U2_Un: case OperationCode.Conv_Ovf_U4_Un: case OperationCode.Conv_Ovf_U8_Un: case OperationCode.Conv_Ovf_I_Un: case OperationCode.Conv_Ovf_U_Un: break; case OperationCode.Box: return OperationValueKind.Type; case OperationCode.Newarr: return OperationValueKind.Type; case OperationCode.Ldlen: break; case OperationCode.Ldelema: return OperationValueKind.Type; case OperationCode.Ldelem_I1: case OperationCode.Ldelem_U1: case OperationCode.Ldelem_I2: case OperationCode.Ldelem_U2: case OperationCode.Ldelem_I4: case OperationCode.Ldelem_U4: case OperationCode.Ldelem_I8: case OperationCode.Ldelem_I: case OperationCode.Ldelem_R4: case OperationCode.Ldelem_R8: case OperationCode.Ldelem_Ref: case OperationCode.Stelem_I: case OperationCode.Stelem_I1: case OperationCode.Stelem_I2: case OperationCode.Stelem_I4: case OperationCode.Stelem_I8: case OperationCode.Stelem_R4: case OperationCode.Stelem_R8: case OperationCode.Stelem_Ref: break; case OperationCode.Ldelem: return OperationValueKind.Type; case OperationCode.Stelem: return OperationValueKind.Type; case OperationCode.Unbox_Any: return OperationValueKind.Type; case OperationCode.Conv_Ovf_I1: case OperationCode.Conv_Ovf_U1: case OperationCode.Conv_Ovf_I2: case OperationCode.Conv_Ovf_U2: case OperationCode.Conv_Ovf_I4: case OperationCode.Conv_Ovf_U4: case OperationCode.Conv_Ovf_I8: case OperationCode.Conv_Ovf_U8: break; case OperationCode.Refanyval: return OperationValueKind.Type; case OperationCode.Ckfinite: break; case OperationCode.Mkrefany: return OperationValueKind.Type; case OperationCode.Ldtoken: return OperationValueKind.RuntimeHandle; case OperationCode.Conv_U2: case OperationCode.Conv_U1: case OperationCode.Conv_I: case OperationCode.Conv_Ovf_I: case OperationCode.Conv_Ovf_U: case OperationCode.Add_Ovf: case OperationCode.Add_Ovf_Un: case OperationCode.Mul_Ovf: case OperationCode.Mul_Ovf_Un: case OperationCode.Sub_Ovf: case OperationCode.Sub_Ovf_Un: case OperationCode.Endfinally: break; case OperationCode.Leave: return OperationValueKind.JumpOffset; case OperationCode.Leave_S: return OperationValueKind.JumpOffset; case OperationCode.Stind_I: case OperationCode.Conv_U: case OperationCode.Arglist: case OperationCode.Ceq: case OperationCode.Cgt: case OperationCode.Cgt_Un: case OperationCode.Clt: case OperationCode.Clt_Un: break; case OperationCode.Ldftn: case OperationCode.Ldvirtftn: return OperationValueKind.Method; case OperationCode.Ldarg: case OperationCode.Ldarga: case OperationCode.Starg: return OperationValueKind.Parameter; case OperationCode.Ldloc: case OperationCode.Ldloca: case OperationCode.Stloc: return OperationValueKind.Local; case OperationCode.Localloc: break; case OperationCode.Endfilter: break; case OperationCode.Unaligned_: return OperationValueKind.Scalar; case OperationCode.Volatile_: case OperationCode.Tail_: break; case OperationCode.Initobj: return OperationValueKind.Type; case OperationCode.Constrained_: return OperationValueKind.Type; case OperationCode.Cpblk: case OperationCode.Initblk: break; case OperationCode.No_: return OperationValueKind.Scalar; case OperationCode.Rethrow: break; case OperationCode.Sizeof: return OperationValueKind.Type; case OperationCode.Refanytype: case OperationCode.Readonly_: break; default: return OperationValueKind.Any; } return OperationValueKind.None; } } }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGAlignItemsTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGAlignItemsTest { [Test] public void Test_align_items_stretch() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_items_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_items_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexStart; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_items_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexEnd; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_baseline() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); } [Test] public void Test_align_baseline_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_child_multiline() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexDirection = YogaFlexDirection.Row; root_child1.Wrap = YogaWrap.Wrap; root_child1.Width = 50; root_child1.Height = 25; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 25; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child1_child1 = new YogaNode(config); root_child1_child1.Width = 25; root_child1_child1.Height = 10; root_child1.Insert(1, root_child1_child1); YogaNode root_child1_child2 = new YogaNode(config); root_child1_child2.Width = 25; root_child1_child2.Height = 20; root_child1.Insert(2, root_child1_child2); YogaNode root_child1_child3 = new YogaNode(config); root_child1_child3.Width = 25; root_child1_child3.Height = 10; root_child1.Insert(3, root_child1_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(25f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(25f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(0f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); } [Test] public void Test_align_baseline_child_multiline_override() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexDirection = YogaFlexDirection.Row; root_child1.Wrap = YogaWrap.Wrap; root_child1.Width = 50; root_child1.Height = 25; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 25; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child1_child1 = new YogaNode(config); root_child1_child1.AlignSelf = YogaAlign.Baseline; root_child1_child1.Width = 25; root_child1_child1.Height = 10; root_child1.Insert(1, root_child1_child1); YogaNode root_child1_child2 = new YogaNode(config); root_child1_child2.Width = 25; root_child1_child2.Height = 20; root_child1.Insert(2, root_child1_child2); YogaNode root_child1_child3 = new YogaNode(config); root_child1_child3.AlignSelf = YogaAlign.Baseline; root_child1_child3.Width = 25; root_child1_child3.Height = 10; root_child1.Insert(3, root_child1_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(25f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(25f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(0f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); } [Test] public void Test_align_baseline_child_multiline_no_override_on_secondline() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexDirection = YogaFlexDirection.Row; root_child1.Wrap = YogaWrap.Wrap; root_child1.Width = 50; root_child1.Height = 25; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 25; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child1_child1 = new YogaNode(config); root_child1_child1.Width = 25; root_child1_child1.Height = 10; root_child1.Insert(1, root_child1_child1); YogaNode root_child1_child2 = new YogaNode(config); root_child1_child2.Width = 25; root_child1_child2.Height = 20; root_child1.Insert(2, root_child1_child2); YogaNode root_child1_child3 = new YogaNode(config); root_child1_child3.AlignSelf = YogaAlign.Baseline; root_child1_child3.Width = 25; root_child1_child3.Height = 10; root_child1.Insert(3, root_child1_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(25f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(25f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(0f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); } [Test] public void Test_align_baseline_child_top() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Top = 10; root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_child_top2() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Top = 5; root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(45f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(45f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_double_nested_child() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 50; root_child0_child0.Height = 20; root_child0.Insert(0, root_child0_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 15; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(50f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(15f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(50f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(15f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); } [Test] public void Test_align_baseline_child_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.MarginLeft = 5; root_child0.MarginTop = 5; root_child0.MarginRight = 5; root_child0.MarginBottom = 5; root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.MarginLeft = 1; root_child1_child0.MarginTop = 1; root_child1_child0.MarginRight = 1; root_child1_child0.MarginBottom = 1; root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(5f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(60f, root_child1.LayoutX); Assert.AreEqual(44f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(1f, root_child1_child0.LayoutX); Assert.AreEqual(1f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(-10f, root_child1.LayoutX); Assert.AreEqual(44f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(-1f, root_child1_child0.LayoutX); Assert.AreEqual(1f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_child_padding() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.PaddingLeft = 5; root.PaddingTop = 5; root.PaddingRight = 5; root.PaddingBottom = 5; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.PaddingLeft = 5; root_child1.PaddingTop = 5; root_child1.PaddingRight = 5; root_child1.PaddingBottom = 5; root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(5f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(55f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(5f, root_child1_child0.LayoutX); Assert.AreEqual(5f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(-5f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(-5f, root_child1_child0.LayoutX); Assert.AreEqual(5f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_multiline() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 50; root_child2.Height = 20; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(config); root_child2_child0.Width = 50; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 50; root_child3.Height = 50; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(50f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(50f, root_child3.LayoutHeight); } [Test] public void Test_align_baseline_multiline_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 20; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 40; root_child2.Height = 70; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(config); root_child2_child0.Width = 10; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 50; root_child3.Height = 20; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(70f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(30f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); } [Test] public void Test_align_baseline_multiline_column2() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 20; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 40; root_child2.Height = 70; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(config); root_child2_child0.Width = 10; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 50; root_child3.Height = 20; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(70f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(30f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); } [Test] public void Test_align_baseline_multiline_row_and_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(config); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 50; root_child2.Height = 20; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(config); root_child2_child0.Width = 50; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 50; root_child3.Height = 20; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(90f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(90f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); } [Test] public void Test_align_items_center_child_with_margin_bigger_than_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.Width = 52; root.Height = 52; YogaNode root_child0 = new YogaNode(config); root_child0.AlignItems = YogaAlign.Center; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.MarginLeft = 10; root_child0_child0.MarginRight = 10; root_child0_child0.Width = 52; root_child0_child0.Height = 52; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(52f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(52f, root_child0_child0.LayoutWidth); Assert.AreEqual(52f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(52f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(52f, root_child0_child0.LayoutWidth); Assert.AreEqual(52f, root_child0_child0.LayoutHeight); } [Test] public void Test_align_items_flex_end_child_with_margin_bigger_than_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.Width = 52; root.Height = 52; YogaNode root_child0 = new YogaNode(config); root_child0.AlignItems = YogaAlign.FlexEnd; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.MarginLeft = 10; root_child0_child0.MarginRight = 10; root_child0_child0.Width = 52; root_child0_child0.Height = 52; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(52f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(52f, root_child0_child0.LayoutWidth); Assert.AreEqual(52f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(52f, root_child0.LayoutHeight); Assert.AreEqual(10f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(52f, root_child0_child0.LayoutWidth); Assert.AreEqual(52f, root_child0_child0.LayoutHeight); } [Test] public void Test_align_items_center_child_without_margin_bigger_than_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.Width = 52; root.Height = 52; YogaNode root_child0 = new YogaNode(config); root_child0.AlignItems = YogaAlign.Center; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 72; root_child0_child0.Height = 72; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(-10f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(72f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(72f, root_child0_child0.LayoutWidth); Assert.AreEqual(72f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(-10f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(72f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(72f, root_child0_child0.LayoutWidth); Assert.AreEqual(72f, root_child0_child0.LayoutHeight); } [Test] public void Test_align_items_flex_end_child_without_margin_bigger_than_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignItems = YogaAlign.Center; root.Width = 52; root.Height = 52; YogaNode root_child0 = new YogaNode(config); root_child0.AlignItems = YogaAlign.FlexEnd; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 72; root_child0_child0.Height = 72; root_child0.Insert(0, root_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(-10f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(72f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(72f, root_child0_child0.LayoutWidth); Assert.AreEqual(72f, root_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(52f, root.LayoutWidth); Assert.AreEqual(52f, root.LayoutHeight); Assert.AreEqual(-10f, root_child0.LayoutX); Assert.AreEqual(-10f, root_child0.LayoutY); Assert.AreEqual(72f, root_child0.LayoutWidth); Assert.AreEqual(72f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(72f, root_child0_child0.LayoutWidth); Assert.AreEqual(72f, root_child0_child0.LayoutHeight); } [Test] public void Test_align_center_should_size_based_on_content() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.MarginTop = 20; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.JustifyContent = YogaJustify.Center; root_child0.FlexShrink = 1; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.FlexShrink = 1; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 20; root_child0_child0_child0.Height = 20; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(20f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(40f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(20f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(20f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(20f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(40f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(20f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(20f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(20f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0_child0.LayoutHeight); } [Test] public void Test_align_strech_should_size_based_on_parent() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.MarginTop = 20; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.JustifyContent = YogaJustify.Center; root_child0.FlexShrink = 1; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.FlexShrink = 1; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 20; root_child0_child0_child0.Height = 20; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(20f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(20f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(20f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(20f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(80f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(20f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0_child0.LayoutHeight); } [Test] public void Test_align_flex_start_with_shrinking_children() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.AlignItems = YogaAlign.FlexStart; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.FlexShrink = 1; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.FlexGrow = 1; root_child0_child0_child0.FlexShrink = 1; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(500f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(500f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(500f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0_child0.LayoutHeight); } [Test] public void Test_align_flex_start_with_stretching_children() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.FlexShrink = 1; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.FlexGrow = 1; root_child0_child0_child0.FlexShrink = 1; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(500f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(500f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(500f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(500f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(500f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(500f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0_child0.LayoutHeight); } [Test] public void Test_align_flex_start_with_shrinking_children_with_stretch() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.AlignItems = YogaAlign.FlexStart; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.FlexGrow = 1; root_child0_child0.FlexShrink = 1; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.FlexGrow = 1; root_child0_child0_child0.FlexShrink = 1; root_child0_child0.Insert(0, root_child0_child0_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(500f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(500f, root_child0.LayoutWidth); Assert.AreEqual(0f, root_child0.LayoutHeight); Assert.AreEqual(500f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(0f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(0f, root_child0_child0_child0.LayoutHeight); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Runtime; namespace Orleans { /// <summary> /// Factory for accessing grains. /// </summary> internal class GrainFactory : IInternalGrainFactory { /// <summary> /// The mapping between concrete grain interface types and delegate /// </summary> private readonly ConcurrentDictionary<Type, GrainReferenceCaster> casters = new ConcurrentDictionary<Type, GrainReferenceCaster>(); /// <summary> /// The collection of <see cref="IGrainMethodInvoker"/>s for their corresponding grain interface type. /// </summary> private readonly ConcurrentDictionary<Type, IGrainMethodInvoker> invokers = new ConcurrentDictionary<Type, IGrainMethodInvoker>(); /// <summary> /// The cache of typed system target references. /// </summary> private readonly Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>> typedSystemTargetReferenceCache = new Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>>(); /// <summary> /// The cache of type metadata. /// </summary> private readonly TypeMetadataCache typeCache; /// <summary> /// The runtime client. /// </summary> private readonly IRuntimeClient runtimeClient; // Make this internal so that client code is forced to access the IGrainFactory using the // GrainClient (to make sure they don't forget to initialize the client). public GrainFactory(IRuntimeClient runtimeClient, TypeMetadataCache typeCache) { this.runtimeClient = runtimeClient; this.typeCache = typeCache; } /// <summary> /// Casts an <see cref="IAddressable"/> to a concrete <see cref="GrainReference"/> implementaion. /// </summary> /// <param name="existingReference">The existing <see cref="IAddressable"/> reference.</param> /// <returns>The concrete <see cref="GrainReference"/> implementation.</returns> internal delegate object GrainReferenceCaster(IAddressable existingReference); /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidKey { Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, null); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerKey { Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, null); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithStringKey { Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="keyExtension">The key extention of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidCompoundKey { GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension); Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, keyExtension); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Gets a reference to a grain. /// </summary> /// <typeparam name="TGrainInterface">The interface to get.</typeparam> /// <param name="primaryKey">The primary key of the grain.</param> /// <param name="keyExtension">The key extention of the grain.</param> /// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param> /// <returns>A reference to the specified grain.</returns> public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerCompoundKey { GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension); Type interfaceType = typeof(TGrainInterface); var implementation = this.GetGrainClassData(interfaceType, grainClassNamePrefix); var grainId = GrainId.GetGrainId(implementation.GetTypeCode(interfaceType), primaryKey, keyExtension); return this.Cast<TGrainInterface>(this.MakeGrainReferenceFromType(interfaceType, grainId)); } /// <summary> /// Creates a reference to the provided <paramref name="obj"/>. /// </summary> /// <typeparam name="TGrainObserverInterface"> /// The specific <see cref="IGrainObserver"/> type of <paramref name="obj"/>. /// </typeparam> /// <param name="obj">The object to create a reference to.</param> /// <returns>The reference to <paramref name="obj"/>.</returns> public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj) where TGrainObserverInterface : IGrainObserver { return Task.FromResult(this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj)); } /// <summary> /// Deletes the provided object reference. /// </summary> /// <typeparam name="TGrainObserverInterface"> /// The specific <see cref="IGrainObserver"/> type of <paramref name="obj"/>. /// </typeparam> /// <param name="obj">The reference being deleted.</param> /// <returns>A <see cref="Task"/> representing the work performed.</returns> public Task DeleteObjectReference<TGrainObserverInterface>( IGrainObserver obj) where TGrainObserverInterface : IGrainObserver { this.runtimeClient.DeleteObjectReference(obj); return TaskDone.Done; } public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable { return this.CreateObjectReferenceImpl<TGrainObserverInterface>(obj); } private TGrainObserverInterface CreateObjectReferenceImpl<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable { var interfaceType = typeof(TGrainObserverInterface); var interfaceTypeInfo = interfaceType.GetTypeInfo(); if (!interfaceTypeInfo.IsInterface) { throw new ArgumentException( $"The provided type parameter must be an interface. '{interfaceTypeInfo.FullName}' is not an interface."); } if (!interfaceTypeInfo.IsInstanceOfType(obj)) { throw new ArgumentException($"The provided object must implement '{interfaceTypeInfo.FullName}'.", nameof(obj)); } IGrainMethodInvoker invoker; if (!this.invokers.TryGetValue(interfaceType, out invoker)) { invoker = this.MakeInvoker(interfaceType); this.invokers.TryAdd(interfaceType, invoker); } return this.Cast<TGrainObserverInterface>(this.runtimeClient.CreateObjectReference(obj, invoker)); } private IAddressable MakeGrainReferenceFromType(Type interfaceType, GrainId grainId) { var typeInfo = interfaceType.GetTypeInfo(); return GrainReference.FromGrainId( grainId, typeInfo.IsGenericType ? TypeUtils.GenericTypeArgsString(typeInfo.UnderlyingSystemType.FullName) : null); } private GrainClassData GetGrainClassData(Type interfaceType, string grainClassNamePrefix) { if (!GrainInterfaceUtils.IsGrainType(interfaceType)) { throw new ArgumentException("Cannot fabricate grain-reference for non-grain type: " + interfaceType.FullName); } var grainTypeResolver = this.runtimeClient.GrainTypeResolver; GrainClassData implementation; if (!grainTypeResolver.TryGetGrainClassData(interfaceType, out implementation, grainClassNamePrefix)) { var loadedAssemblies = grainTypeResolver.GetLoadedGrainAssemblies(); var assembliesString = string.IsNullOrEmpty(loadedAssemblies) ? string.Empty : " Loaded grain assemblies: " + loadedAssemblies; var grainClassPrefixString = string.IsNullOrEmpty(grainClassNamePrefix) ? string.Empty : ", grainClassNamePrefix: " + grainClassNamePrefix; throw new ArgumentException( $"Cannot find an implementation class for grain interface: {interfaceType}{grainClassPrefixString}. " + "Make sure the grain assembly was correctly deployed and loaded in the silo." + assembliesString); } return implementation; } private IGrainMethodInvoker MakeInvoker(Type interfaceType) { var invokerType = this.typeCache.GetGrainMethodInvokerType(interfaceType); return (IGrainMethodInvoker)Activator.CreateInstance(invokerType); } #region Interface Casting /// <summary> /// Casts the provided <paramref name="grain"/> to the specified interface /// </summary> /// <typeparam name="TGrainInterface">The target grain interface type.</typeparam> /// <param name="grain">The grain reference being cast.</param> /// <returns> /// A reference to <paramref name="grain"/> which implements <typeparamref name="TGrainInterface"/>. /// </returns> public TGrainInterface Cast<TGrainInterface>(IAddressable grain) { var interfaceType = typeof(TGrainInterface); return (TGrainInterface)this.Cast(grain, interfaceType); } /// <summary> /// Casts the provided <paramref name="grain"/> to the provided <paramref name="interfaceType"/>. /// </summary> /// <param name="grain">The grain.</param> /// <param name="interfaceType">The resulting interface type.</param> /// <returns>A reference to <paramref name="grain"/> which implements <paramref name="interfaceType"/>.</returns> public object Cast(IAddressable grain, Type interfaceType) { GrainReferenceCaster caster; if (!this.casters.TryGetValue(interfaceType, out caster)) { // Create and cache a caster for the interface type. caster = this.casters.GetOrAdd(interfaceType, this.MakeCaster); } return caster(grain); } /// <summary> /// Creates and returns a new grain reference caster. /// </summary> /// <param name="interfaceType">The interface which the result will cast to.</param> /// <returns>A new grain reference caster.</returns> private GrainReferenceCaster MakeCaster(Type interfaceType) { var grainReferenceType = this.typeCache.GetGrainReferenceType(interfaceType); return GrainCasterFactory.CreateGrainReferenceCaster(interfaceType, grainReferenceType); } #endregion #region SystemTargets /// <summary> /// Gets a reference to the specified system target. /// </summary> /// <typeparam name="TGrainInterface">The system target interface.</typeparam> /// <param name="grainId">The id of the target.</param> /// <param name="destination">The destination silo.</param> /// <returns>A reference to the specified system target.</returns> public TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId, SiloAddress destination) where TGrainInterface : ISystemTarget { Dictionary<SiloAddress, ISystemTarget> cache; Tuple<GrainId, Type> key = Tuple.Create(grainId, typeof(TGrainInterface)); lock (this.typedSystemTargetReferenceCache) { if (this.typedSystemTargetReferenceCache.ContainsKey(key)) cache = this.typedSystemTargetReferenceCache[key]; else { cache = new Dictionary<SiloAddress, ISystemTarget>(); this.typedSystemTargetReferenceCache[key] = cache; } } ISystemTarget reference; lock (cache) { if (cache.ContainsKey(destination)) { reference = cache[destination]; } else { reference = this.Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, null, destination)); cache[destination] = reference; // Store for next time } } return (TGrainInterface)reference; } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- datablock SFXProfile(TargetAquiredSound) { filename = ""; description = AudioClose3D; preload = false; }; datablock SFXProfile(TargetLostSound) { filename = ""; description = AudioClose3D; preload = false; }; datablock SFXProfile(TurretDestroyed) { filename = ""; description = AudioClose3D; preload = false; }; datablock SFXProfile(TurretThrown) { filename = ""; description = AudioClose3D; preload = false; }; datablock SFXProfile(TurretFireSound) { filename = "art/sound/turret/wpn_turret_fire"; description = AudioClose3D; preload = true; }; datablock SFXProfile(TurretActivatedSound) { filename = "art/sound/turret/wpn_turret_deploy"; description = AudioClose3D; preload = true; }; datablock SFXProfile(TurretScanningSound) { filename = "art/sound/turret/wpn_turret_scan"; description = AudioCloseLoop3D; preload = true; }; datablock SFXProfile(TurretSwitchinSound) { filename = "art/sound/turret/wpn_turret_switchin"; description = AudioClose3D; preload = true; }; //----------------------------------------------------------------------------- // Turret Bullet Projectile //----------------------------------------------------------------------------- datablock ProjectileData( TurretBulletProjectile ) { projectileShapeName = ""; directDamage = 5; radiusDamage = 0; damageRadius = 0.5; areaImpulse = 0.5; impactForce = 1; damageType = "TurretDamage"; // Type of damage applied by this weapon explosion = BulletDirtExplosion; decal = BulletHoleDecal; muzzleVelocity = 120; velInheritFactor = 1; armingDelay = 0; lifetime = 992; fadeDelay = 1472; bounceElasticity = 0; bounceFriction = 0; isBallistic = false; gravityMod = 1; }; function TurretBulletProjectile::onCollision(%this,%obj,%col,%fade,%pos,%normal) { // Apply impact force from the projectile. // Apply damage to the object all shape base objects if ( %col.getType() & $TypeMasks::GameBaseObjectType ) %col.damage(%obj,%pos,%this.directDamage,%this.damageType); } //----------------------------------------------------------------------------- // Turret Bullet Ammo //----------------------------------------------------------------------------- datablock ItemData(AITurretAmmo) { // Mission editor category category = "Ammo"; // Add the Ammo namespace as a parent. The ammo namespace provides // common ammo related functions and hooks into the inventory system. className = "Ammo"; // Basic Item properties shapeFile = "art/shapes/weapons/Turret/Turret_Legs.DAE"; mass = 1; elasticity = 0.2; friction = 0.6; // Dynamic properties defined by the scripts pickUpName = "turret ammo"; }; //----------------------------------------------------------------------------- // AI Turret Weapon //----------------------------------------------------------------------------- datablock ItemData(AITurretHead) { // Mission editor category category = "Weapon"; // Hook into Item Weapon class hierarchy. The weapon namespace // provides common weapon handling functions in addition to hooks // into the inventory system. className = "Weapon"; // Basic Item properties shapeFile = "art/shapes/weapons/Turret/Turret_Head.DAE"; mass = 1; elasticity = 0.2; friction = 0.6; emap = true; // Dynamic properties defined by the scripts pickUpName = "an AI turret head"; description = "AI Turret Head"; image = AITurretHeadImage; reticle = "crossHair"; }; datablock ShapeBaseImageData(AITurretHeadImage) { // Basic Item properties shapeFile = "art/shapes/weapons/Turret/Turret_Head.DAE"; emap = true; // Specify mount point mountPoint = 0; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. class = "WeaponImage"; className = "WeaponImage"; // Projectiles and Ammo. item = AITurretHead; ammo = AITurretAmmo; projectile = TurretBulletProjectile; projectileType = Projectile; projectileSpread = "0.02"; casing = BulletShell; shellExitDir = "1.0 0.3 1.0"; shellExitOffset = "0.15 -0.56 -0.1"; shellExitVariance = 15.0; shellVelocity = 3.0; // Weapon lights up while firing lightType = "WeaponFireLight"; lightColor = "0.992126 0.968504 0.708661 1"; lightRadius = "4"; lightDuration = "100"; lightBrightness = 2; // Shake camera while firing. shakeCamera = false; camShakeFreq = "0 0 0"; camShakeAmp = "0 0 0"; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. useRemainderDT = true; // Initial start up state stateName[0] = "Preactivate"; stateIgnoreLoadedForReady[0] = false; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNotLoaded[0] = "WaitingDeployment"; // If the turret weapon is not loaded then it has not yet been deployed stateTransitionOnNoAmmo[0] = "NoAmmo"; // Activating the gun. Called when the weapon is first // mounted and there is ammo. stateName[1] = "Activate"; stateTransitionGeneric0In[1] = "Destroyed"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.5; stateSequence[1] = "Activate"; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionGeneric0In[2] = "Destroyed"; stateTransitionOnNoAmmo[2] = "NoAmmo"; stateTransitionOnTriggerDown[2] = "Fire"; stateSequence[2] = "scan"; // Fire the weapon. Calls the fire script which does // the actual work. stateName[3] = "Fire"; stateTransitionGeneric0In[3] = "Destroyed"; stateTransitionOnTimeout[3] = "Reload"; stateTimeoutValue[3] = 0.2; stateFire[3] = true; stateRecoil[3] = "LightRecoil"; stateAllowImageChange[3] = false; stateSequence[3] = "fire"; stateSequenceRandomFlash[3] = true; // use muzzle flash sequence stateScript[3] = "onFire"; stateSound[3] = TurretFireSound; stateEmitter[3] = GunFireSmokeEmitter; stateEmitterTime[3] = 0.025; stateEjectShell[3] = true; // Play the reload animation, and transition into stateName[4] = "Reload"; stateTransitionGeneric0In[4] = "Destroyed"; stateTransitionOnNoAmmo[4] = "NoAmmo"; stateTransitionOnTimeout[4] = "Ready"; stateWaitForTimeout[4] = "0"; stateTimeoutValue[4] = 0.0; stateAllowImageChange[4] = false; stateSequence[4] = "Reload"; // No ammo in the weapon, just idle until something // shows up. Play the dry fire sound if the trigger is // pulled. stateName[5] = "NoAmmo"; stateTransitionGeneric0In[5] = "Destroyed"; stateTransitionOnAmmo[5] = "Reload"; stateSequence[5] = "NoAmmo"; stateTransitionOnTriggerDown[5] = "DryFire"; // No ammo dry fire stateName[6] = "DryFire"; stateTransitionGeneric0In[6] = "Destroyed"; stateTimeoutValue[6] = 1.0; stateTransitionOnTimeout[6] = "NoAmmo"; stateScript[6] = "onDryFire"; // Waiting for the turret to be deployed stateName[7] = "WaitingDeployment"; stateTransitionGeneric0In[7] = "Destroyed"; stateTransitionOnLoaded[7] = "Deployed"; stateSequence[7] = "wait_deploy"; // Turret has been deployed stateName[8] = "Deployed"; stateTransitionGeneric0In[8] = "Destroyed"; stateTransitionOnTimeout[8] = "Ready"; stateWaitForTimeout[8] = true; stateTimeoutValue[8] = 2.5; // Same length as turret base's Deploy state stateSequence[8] = "deploy"; // Turret has been destroyed stateName[9] = "Destroyed"; stateSequence[9] = "destroyed"; }; //----------------------------------------------------------------------------- // AI Turret //----------------------------------------------------------------------------- datablock AITurretShapeData(AITurret) { category = "Turrets"; shapeFile = "art/shapes/weapons/Turret/Turret_Legs.DAE"; maxDamage = 70; destroyedLevel = 70; explosion = GrenadeExplosion; simpleServerCollision = false; zRotOnly = false; // Rotation settings minPitch = 15; maxPitch = 80; maxHeading = 90; headingRate = 50; pitchRate = 50; // Scan settings maxScanPitch = 10; maxScanHeading = 30; maxScanDistance = 20; trackLostTargetTime = 2; maxWeaponRange = 30; weaponLeadVelocity = 0; // Weapon mounting numWeaponMountPoints = 1; weapon[0] = AITurretHead; weaponAmmo[0] = AITurretAmmo; weaponAmmoAmount[0] = 10000; maxInv[AITurretHead] = 1; maxInv[AITurretAmmo] = 10000; // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnAtRest[0] = "Scanning"; stateTransitionOnNotAtRest[0] = "Thrown"; // Scan for targets stateName[1] = "Scanning"; stateScan[1] = true; stateTransitionOnTarget[1] = "Target"; stateSequence[1] = "scan"; stateScript[1] = "OnScanning"; // Have a target stateName[2] = "Target"; stateTransitionOnNoTarget[2] = "NoTarget"; stateTransitionOnTimeout[2] = "Firing"; stateTimeoutValue[2] = 2.0; stateScript[2] = "OnTarget"; // Fire at target stateName[3] = "Firing"; stateFire[3] = true; stateTransitionOnNoTarget[3] = "NoTarget"; stateScript[3] = "OnFiring"; // Lost target stateName[4] = "NoTarget"; stateTransitionOnTimeout[4] = "Scanning"; stateTimeoutValue[4] = 2.0; stateScript[4] = "OnNoTarget"; // Player thrown turret stateName[5] = "Thrown"; stateTransitionOnAtRest[5] = "Deploy"; stateSequence[5] = "throw"; stateScript[5] = "OnThrown"; // Player thrown turret is deploying stateName[6] = "Deploy"; stateTransitionOnTimeout[6] = "Scanning"; stateTimeoutValue[6] = 2.5; stateSequence[6] = "deploy"; stateScaleAnimation[6] = true; stateScript[6] = "OnDeploy"; // Special state that is set when the turret is destroyed. // This state is set in the onDestroyed() callback. stateName[7] = "Destroyed"; stateSequence[7] = "destroyed"; }; //----------------------------------------------------------------------------- // Deployable AI Turret //----------------------------------------------------------------------------- datablock AITurretShapeData(DeployableTurret : AITurret) { // Mission editor category category = "Weapon"; className = "DeployableTurretWeapon"; startLoaded = false; // Basic Item properties mass = 1.5; elasticity = 0.1; friction = 0.6; simpleServerCollision = false; // Dynamic properties defined by the scripts PreviewImage = 'turret.png'; pickUpName = "a deployable turret"; description = "Deployable Turret"; image = DeployableTurretImage; reticle = "blank"; zoomReticle = 'blank'; }; datablock ShapeBaseImageData(DeployableTurretImage) { // Basic Item properties shapeFile = "art/shapes/weapons/Turret/TP_Turret.DAE"; shapeFileFP = "art/shapes/weapons/Turret/FP_Turret.DAE"; emap = true; imageAnimPrefix = "Turret"; imageAnimPrefixFP = "Turret"; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; firstPerson = true; useEyeNode = true; // Don't allow a player to sprint with a turret sprintDisallowed = true; class = "DeployableTurretWeaponImage"; className = "DeployableTurretWeaponImage"; // Projectiles and Ammo. item = DeployableTurret; // Shake camera while firing. shakeCamera = false; camShakeFreq = "0 0 0"; camShakeAmp = "0 0 0"; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Preactivate"; stateTransitionOnLoaded[0] = "Activate"; stateTransitionOnNoAmmo[0] = "Activate"; // Activating the gun. Called when the weapon is first // mounted and there is ammo. stateName[1] = "Activate"; stateTransitionGeneric0In[1] = "SprintEnter"; stateTransitionOnTimeout[1] = "Ready"; stateTimeoutValue[1] = 0.66; stateSequence[1] = "switch_in"; stateSound[1] = TurretSwitchinSound; // Ready to fire, just waiting for the trigger stateName[2] = "Ready"; stateTransitionGeneric0In[2] = "SprintEnter"; stateTransitionOnMotion[2] = "ReadyMotion"; stateTransitionOnTriggerDown[2] = "Fire"; stateScaleAnimation[2] = false; stateScaleAnimationFP[2] = false; stateSequence[2] = "idle"; // Ready to fire with player moving stateName[3] = "ReadyMotion"; stateTransitionGeneric0In[3] = "SprintEnter"; stateTransitionOnNoMotion[3] = "Ready"; stateScaleAnimation[3] = false; stateScaleAnimationFP[3] = false; stateSequenceTransitionIn[3] = true; stateSequenceTransitionOut[3] = true; stateTransitionOnTriggerDown[3] = "Fire"; stateSequence[3] = "run"; // Wind up to throw the Turret stateName[4] = "Fire"; stateTransitionGeneric0In[4] = "SprintEnter"; stateTransitionOnTimeout[4] = "Fire2"; stateTimeoutValue[4] = 0.66; stateFire[4] = true; stateRecoil[4] = ""; stateAllowImageChange[4] = false; stateSequence[4] = "Fire"; stateSequenceNeverTransition[4] = true; stateShapeSequence[4] = "Recoil"; // Throw the actual Turret stateName[5] = "Fire2"; stateTransitionGeneric0In[5] = "SprintEnter"; stateTransitionOnTriggerUp[5] = "Reload"; stateTimeoutValue[5] = 0.1; stateAllowImageChange[5] = false; stateScript[5] = "onFire"; stateShapeSequence[5] = "Fire_Release"; // Play the reload animation, and transition into stateName[6] = "Reload"; stateTransitionGeneric0In[6] = "SprintEnter"; stateTransitionOnTimeout[6] = "Ready"; stateWaitForTimeout[6] = true; stateTimeoutValue[6] = 0.66; stateSequence[6] = "switch_in"; // Start Sprinting stateName[7] = "SprintEnter"; stateTransitionGeneric0Out[7] = "SprintExit"; stateTransitionOnTimeout[7] = "Sprinting"; stateWaitForTimeout[7] = false; stateTimeoutValue[7] = 0.25; stateWaitForTimeout[7] = false; stateScaleAnimation[7] = true; stateScaleAnimationFP[7] = true; stateSequenceTransitionIn[7] = true; stateSequenceTransitionOut[7] = true; stateAllowImageChange[7] = false; stateSequence[7] = "sprint"; // Sprinting stateName[8] = "Sprinting"; stateTransitionGeneric0Out[8] = "SprintExit"; stateWaitForTimeout[8] = false; stateScaleAnimation[8] = false; stateScaleAnimationFP[8] = false; stateSequenceTransitionIn[8] = true; stateSequenceTransitionOut[8] = true; stateAllowImageChange[8] = false; stateSequence[8] = "sprint"; // Stop Sprinting stateName[9] = "SprintExit"; stateTransitionGeneric0In[9] = "SprintEnter"; stateTransitionOnTimeout[9] = "Ready"; stateWaitForTimeout[9] = false; stateTimeoutValue[9] = 0.5; stateSequenceTransitionIn[9] = true; stateSequenceTransitionOut[9] = true; stateAllowImageChange[9] = false; stateSequence[9] = "sprint"; };
using System; using System.ComponentModel.Design; using System.Diagnostics; using System.IO; using System.Xml; namespace Microsoft.Web.XmlTransform.Extended { public class XmlTransformation : IServiceProvider, IDisposable { internal static readonly string TransformNamespace = "http://schemas.microsoft.com/XML-Document-Transform"; internal static readonly string SupressWarnings = "SupressWarnings"; #region private data members private readonly string _transformFile; private XmlDocument _xmlTransformation; private XmlDocument _xmlTarget; private XmlTransformableDocument _xmlTransformable; private readonly XmlTransformationLogger _logger; private NamedTypeFactory _namedTypeFactory; private ServiceContainer _transformationServiceContainer = new ServiceContainer(); private ServiceContainer _documentServiceContainer; private bool _hasTransformNamespace; #endregion public XmlTransformation(string transformFile) : this(transformFile, true, null) { } public XmlTransformation(string transform, IXmlTransformationLogger logger) : this(transform, true, logger) { } public XmlTransformation(string transform, bool isTransformAFile, IXmlTransformationLogger logger) { _transformFile = transform; _logger = new XmlTransformationLogger(logger); _xmlTransformation = new XmlFileInfoDocument(); if (isTransformAFile) _xmlTransformation.Load(transform); else _xmlTransformation.LoadXml(transform); InitializeTransformationServices(); PreprocessTransformDocument(); } public XmlTransformation(Stream transformStream, IXmlTransformationLogger logger) { _logger = new XmlTransformationLogger(logger); _transformFile = String.Empty; _xmlTransformation = new XmlFileInfoDocument(); _xmlTransformation.Load(transformStream); InitializeTransformationServices(); PreprocessTransformDocument(); } public bool HasTransformNamespace { get { return _hasTransformNamespace; } } private void InitializeTransformationServices() { // Initialize NamedTypeFactory _namedTypeFactory = new NamedTypeFactory(_transformFile); _transformationServiceContainer.AddService(_namedTypeFactory.GetType(), _namedTypeFactory); // Initialize TransformationLogger _transformationServiceContainer.AddService(_logger.GetType(), _logger); } private void InitializeDocumentServices(XmlDocument document) { Debug.Assert(_documentServiceContainer == null); _documentServiceContainer = new ServiceContainer(); if (document is IXmlOriginalDocumentService) { _documentServiceContainer.AddService(typeof(IXmlOriginalDocumentService), document); } } private void ReleaseDocumentServices() { if (_documentServiceContainer == null) return; _documentServiceContainer.RemoveService(typeof(IXmlOriginalDocumentService)); _documentServiceContainer = null; } private void PreprocessTransformDocument() { _hasTransformNamespace = false; foreach (XmlAttribute attribute in _xmlTransformation.SelectNodes("//namespace::*")) { if (!attribute.Value.Equals(TransformNamespace, StringComparison.Ordinal)) continue; _hasTransformNamespace = true; break; } if (!_hasTransformNamespace) return; // This will look for all nodes from our namespace in the document, // and do any initialization work var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("xdt", TransformNamespace); var namespaceNodes = _xmlTransformation.SelectNodes("//xdt:*", namespaceManager); foreach (XmlNode node in namespaceNodes) { var element = node as XmlElement; if (element == null) { Debug.Fail("The XPath for elements returned something that wasn't an element?"); continue; } XmlElementContext context = null; try { switch (element.LocalName) { case "Import": context = CreateElementContext(null, element); PreprocessImportElement(context); break; default: _logger.LogWarning(element, SR.XMLTRANSFORMATION_UnknownXdtTag, element.Name); break; } } catch (Exception ex) { if (context != null) { ex = WrapException(ex, context); } _logger.LogErrorFromException(ex); throw new XmlTransformationException(SR.XMLTRANSFORMATION_FatalTransformSyntaxError, ex); } finally { context = null; } } } public void AddTransformationService(Type serviceType, object serviceInstance) { _transformationServiceContainer.AddService(serviceType, serviceInstance); } public void RemoveTransformationService(Type serviceType) { _transformationServiceContainer.RemoveService(serviceType); } public bool Apply(XmlDocument xmlTarget) { Debug.Assert(_xmlTarget == null, "This method should not be called recursively"); if (_xmlTarget != null) return false; // Reset the error state _logger.HasLoggedErrors = false; _xmlTarget = xmlTarget; _xmlTransformable = xmlTarget as XmlTransformableDocument; try { if (_hasTransformNamespace) { InitializeDocumentServices(xmlTarget); TransformLoop(_xmlTransformation); } else { _logger.LogMessage(MessageType.Normal, "The expected namespace {0} was not found in the transform file", TransformNamespace); } } catch (Exception ex) { HandleException(ex); } finally { ReleaseDocumentServices(); _xmlTarget = null; _xmlTransformable = null; } return !_logger.HasLoggedErrors; } private void TransformLoop(XmlDocument xmlSource) { TransformLoop(new XmlNodeContext(xmlSource)); } private void TransformLoop(XmlNodeContext parentContext) { foreach (XmlNode node in parentContext.Node.ChildNodes) { var element = node as XmlElement; if (element == null) { continue; } var context = CreateElementContext(parentContext as XmlElementContext, element); try { HandleElement(context); } catch (Exception ex) { HandleException(ex, context); } } } private XmlElementContext CreateElementContext(XmlElementContext parentContext, XmlElement element) { return new XmlElementContext(parentContext, element, _xmlTarget, this); } private void HandleException(Exception ex) { _logger.LogErrorFromException(ex); } private void HandleException(Exception ex, XmlNodeContext context) { HandleException(WrapException(ex, context)); } private Exception WrapException(Exception ex, XmlNodeContext context) { return XmlNodeException.Wrap(ex, context.Node); } private void HandleElement(XmlElementContext context) { string argumentString; var transform = context.ConstructTransform(out argumentString); if (transform != null) { var fOriginalSupressWarning = _logger.SupressWarnings; var supressWarningsAttribute = context.Element.Attributes.GetNamedItem(SupressWarnings, TransformNamespace) as XmlAttribute; if (supressWarningsAttribute != null) { var fSupressWarning = Convert.ToBoolean(supressWarningsAttribute.Value, System.Globalization.CultureInfo.InvariantCulture); _logger.SupressWarnings = fSupressWarning; } try { OnApplyingTransform(); transform.Execute(context, argumentString); OnAppliedTransform(); } catch (Exception ex) { HandleException(ex, context); } finally { // reset back the SupressWarnings back per node _logger.SupressWarnings = fOriginalSupressWarning; } } // process children TransformLoop(context); } private void OnApplyingTransform() { if (_xmlTransformable != null) _xmlTransformable.OnBeforeChange(); } private void OnAppliedTransform() { if (_xmlTransformable != null) _xmlTransformable.OnAfterChange(); } private void PreprocessImportElement(XmlElementContext context) { string assemblyName = null; string nameSpace = null; string path = null; foreach (XmlAttribute attribute in context.Element.Attributes) { if (attribute.NamespaceURI.Length != 0) throw new XmlNodeException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_ImportUnknownAttribute, attribute.Name), attribute); switch (attribute.Name) { case "assembly": assemblyName = attribute.Value; continue; case "namespace": nameSpace = attribute.Value; continue; case "path": path = attribute.Value; continue; } throw new XmlNodeException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_ImportUnknownAttribute, attribute.Name), attribute); } if (assemblyName != null && path != null) { throw new XmlNodeException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_ImportAttributeConflict), context.Element); } if (assemblyName == null && path == null) { throw new XmlNodeException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_ImportMissingAssembly), context.Element); } if (nameSpace == null) { throw new XmlNodeException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_ImportMissingNamespace), context.Element); } if (assemblyName != null) { _namedTypeFactory.AddAssemblyRegistration(assemblyName, nameSpace); } else { _namedTypeFactory.AddPathRegistration(path, nameSpace); } } #region IServiceProvider Members public object GetService(Type serviceType) { if (_documentServiceContainer == null) return (_transformationServiceContainer.GetService(serviceType)); return _documentServiceContainer.GetService(serviceType) ?? (_transformationServiceContainer.GetService(serviceType)); } #endregion #region Dispose Pattern protected virtual void Dispose(bool disposing) { if (_transformationServiceContainer != null) { _transformationServiceContainer.Dispose(); _transformationServiceContainer = null; } if (_documentServiceContainer != null) { _documentServiceContainer.Dispose(); _documentServiceContainer = null; } if (_xmlTransformable != null) { _xmlTransformable.Dispose(); _xmlTransformable = null; } if (_xmlTransformation as XmlFileInfoDocument != null) { (_xmlTransformation as XmlFileInfoDocument).Dispose(); _xmlTransformation = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~XmlTransformation() { Debug.Fail("call dispose please"); Dispose(false); } #endregion } }
/* Copyright 2006 - 2010 Intel 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.Xml; using System.Text; using System.Collections; using OpenSource.UPnP; using OpenSource.UPnP.AV; using OpenSource.UPnP.AV.CdsMetadata; namespace UPnPValidator { public class CdsResult_BrowseStats : CdsTestResult { public int ExpectedTotalBrowseRequests = 0; public int TotalBrowseRequests = 0; public int TotalContainers = 1; public int TotalItems = 0; } public class CdsResult_BrowseAll : CdsResult_BrowseStats { public IMediaContainer Root; public ArrayList AllObjects = new ArrayList(); public IMediaContainer LargestContainer; public IUPnPMedia MostMetadata; public ArrayList PropertyNames = new ArrayList(); } /// <summary> /// Declares a bunch of inner classes useful for browse tests. /// </summary> public abstract class Cds_BrowseTest : CdsSubTest { public class BrowseInput : InputParams { public System.String ObjectID; public CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag; public System.String Filter; public System.UInt32 StartingIndex; public System.UInt32 RequestedCount; public System.String SortCriteria; public string PrintBrowseParams() { BrowseInput bi = this; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Browse(\"{0}\", {1}, \"{2}\", {3}, {4}, \"{5}\")", bi.ObjectID, bi.BrowseFlag.ToString(), bi.Filter, bi.StartingIndex, bi.RequestedCount, bi.SortCriteria); return sb.ToString(); } } public abstract CdsResult_BrowseStats BrowseStats { get; } public static string GetCSVString(IList values) { StringBuilder sb = new StringBuilder(); int sbi = 0; ArrayList seenAlready = new ArrayList(); foreach (string val in values) { if (sbi > 0) { sb.Append(","); } sb.Append(val); sbi++; } return sb.ToString(); } /// <summary> /// Performs a Browse invocation. /// </summary> /// <param name="input"></param> /// <param name="test"></param> /// <param name="arg"></param> /// <param name="cds"></param> /// <param name="stats"></param> /// <returns></returns> public static CdsBrowseSearchResults Browse(BrowseInput input, CdsSubTest test, CdsSubTestArgument arg, CpContentDirectory cds, CdsResult_BrowseStats stats) { CdsBrowseSearchResults results = new CdsBrowseSearchResults(); results.SetError(UPnPTestStates.Pass); results.ResultErrors = new ArrayList(); arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, "\""+test.Name+"\" about to do " + input.PrintBrowseParams()+ "."); try { cds.Sync_Browse(input.ObjectID, input.BrowseFlag, input.Filter, input.StartingIndex, input.RequestedCount, input.SortCriteria, out results.Result, out results.NumberReturned, out results.TotalMatches, out results.UpdateID); } catch (UPnPInvokeException error) { results.InvokeError = error; } if (results.InvokeError == null) { arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, "\""+test.Name+"\" completed " + input.PrintBrowseParams()+ " with no errors returned by the device."); } else { arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, "\""+test.Name+"\" completed " + input.PrintBrowseParams()+ " with the device returning an error."); } stats.TotalBrowseRequests++; ArrayList branches = null; if (results.InvokeError == null) { try { if (results.Result != null) { if (results.Result != "") { bool schemaOK = CheckDidlLiteSchema(results.Result); if (schemaOK) { results.MediaObjects = branches = MediaBuilder.BuildMediaBranches(results.Result, typeof (MediaItem), typeof(MediaContainer), true); if (branches.Count != results.NumberReturned) { results.ResultErrors.Add (new CdsException(input.PrintBrowseParams() + " has the \"Result\" argument indicating the presence of " +branches.Count+ " media objects but the request returned NumberReturned=" +results.NumberReturned+".")); } if (input.BrowseFlag == CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA) { if (branches.Count != 1) { results.ResultErrors.Add (new CdsException(input.PrintBrowseParams() + " has the \"Result\" argument indicating the presence of " +branches.Count+ " media objects but the request should have only returned 1 media object.")); } } foreach (IUPnPMedia mobj in branches) { IMediaContainer imc = mobj as IMediaContainer; if (imc != null) { if (imc.CompleteList.Count > 0) { StringBuilder offendingList = new StringBuilder(); int offenses = 0; foreach (IUPnPMedia offending in imc.CompleteList) { if (offenses > 0) { offendingList.Append(","); } offendingList.AppendFormat("\"{0}\"", offending.ID); offenses++; } results.ResultErrors.Add (new CdsException(input.PrintBrowseParams() + " has the \"Result\" argument with a declared container (ID=\""+imc.ID+"\") element that also includes its immediate children. Illegally declared media objects in the response are: "+offendingList.ToString())); } } } } } } } catch (Exception error2) { results.ResultErrors.Add (error2); if (results.MediaObjects == null) { results.MediaObjects = new ArrayList(); } } } // log any errors if ((results.InvokeError != null) || (results.ResultErrors.Count > 0)) { LogErrors(arg._TestGroup, test, input, "Browse", results.InvokeError, results.ResultErrors); results.SetError(UPnPTestStates.Failed); } return results; } public static bool CheckDidlLiteSchema (string DidlLiteXml) { // TODO: Add schema validation // TODO: Add check for blank title. // TODO: Add check for upnp:class <==> <container/item> declarator return true; } } /// <summary> /// Summary description for Cds_BrowseAll. /// </summary> public sealed class Cds_BrowseAll : Cds_BrowseTest { private CdsResult_BrowseAll _Details; public override object Details { get { return _Details; } } public override CdsResult_BrowseStats BrowseStats { get { return _Details; } } public override void CalculateExpectedTestingTime(ICollection otherSubTests, ISubTestArgument arg) { } public override UPnPTestStates Run (ICollection otherSubTests, CdsSubTestArgument arg) { // init basic stuff CpContentDirectory CDS = this.GetCDS(arg._Device); _Details = new CdsResult_BrowseAll(); // set up a queue of containers to browse, starting with root container Queue C = new Queue(); _Details.Root = new MediaContainer(); _Details.Root.ID = "0"; _Details.AllObjects.Add(_Details.Root); _Details.TotalContainers = 1; _Details.TotalItems = 0; C.Enqueue(_Details.Root); // if we have containers to browse, do so this._TestState = UPnPTestStates.Running; UPnPTestStates testResult = UPnPTestStates.Ready; arg._TestGroup.AddEvent(LogImportance.Remark, this.Name, "\""+this.Name + "\" started."); while (C.Count > 0) { IMediaContainer c = (IMediaContainer) C.Dequeue(); this._ExpectedTestingTime = _Details.ExpectedTotalBrowseRequests * 30; arg.ActiveTests.UpdateTimeAndProgress( _Details.TotalBrowseRequests * 30); // // get the container's metadata // IUPnPMedia metadata; CdsBrowseSearchResults results = GetContainerMetadataAndValidate(c.ID, CDS, this, arg, _Details, out metadata); testResult = results.WorstError; if (testResult > UPnPTestStates.Warn) { arg._TestGroup.AddEvent(LogImportance.Critical, this.Name, this.Name + " terminating because container metadata could not be obtained or the metadata was not CDS-compliant."); testResult = UPnPTestStates.Failed; this._TestState = testResult; return this._TestState; } if (metadata != null) { try { c.UpdateObject(metadata); c.Tag = results.UpdateID; } catch (Exception e) { UpdateObjectError uoe = new UpdateObjectError(); uoe.UpdateThis = c; uoe.Metadata = metadata; throw new TestException("Critical error updating metadata of a container using UpdateObject()", uoe, e); } } else { string reason = "\"" +this.Name + "\" terminating because container metadata could not be cast into object form."; arg._TestGroup.AddEvent(LogImportance.Critical, this.Name, reason); arg._TestGroup.AddResult("\""+this.Name + "\" test failed. " + reason); testResult = UPnPTestStates.Failed; this._TestState = testResult; return this._TestState; } // // Now get the container's children // ArrayList children = new ArrayList(); try { children = GetContainerChildrenAndValidate(c, CDS, this, arg, _Details, C); if ((_Details.LargestContainer == null) || (children.Count > _Details.LargestContainer.ChildCount)) { _Details.LargestContainer = c; } } catch (TerminateEarly te) { string reason = "\"" +this.Name + "\" terminating early. Reason => " + te.Message; arg._TestGroup.AddEvent(LogImportance.Critical, this.Name, reason); arg._TestGroup.AddResult("\""+this.Name + "\" test failed. " + reason); testResult = UPnPTestStates.Failed; this._TestState = testResult; return this._TestState; } } if (testResult >= UPnPTestStates.Failed) { throw new TestException("Execution should not reach this code if testResult is WARN or worse.", testResult); } if (testResult == UPnPTestStates.Ready) { throw new TestException("We should not return Ready state.", testResult); } StringBuilder sb = new StringBuilder(); sb.Append("\""+this._Name + "\" test finished"); if (testResult == UPnPTestStates.Warn) { sb.Append(" with warnings"); } sb.AppendFormat(" and found {0}/{1}/{2} TotalObjects/TotalContainers/TotalItems.", _Details.AllObjects.Count, _Details.TotalContainers, _Details.TotalItems); arg.TestGroup.AddResult(sb.ToString()); arg._TestGroup.AddEvent(LogImportance.Remark, this.Name, this.Name + " completed."); this._TestState = testResult; if (this._TestState <= UPnPTestStates.Warn) { if (_Details.TotalBrowseRequests != _Details.ExpectedTotalBrowseRequests) { throw new TestException("TotalBrowseRequests="+_Details.TotalBrowseRequests.ToString()+" ExpectedTotal="+_Details.ExpectedTotalBrowseRequests.ToString(), _Details); } } return this._TestState; } /// <summary> /// /// </summary> /// <param name="parent"></param> /// <param name="cds"></param> /// <param name="test"></param> /// <param name="arg"></param> /// <param name="details"></param> /// <param name="C"></param> /// <returns></returns> /// <exception cref="TerminateEarly"> /// </exception> public static ArrayList GetContainerChildrenAndValidate(IMediaContainer parent, CpContentDirectory cds, CdsSubTest test, CdsSubTestArgument arg, CdsResult_BrowseAll details, Queue C) { uint totalExpected = uint.MaxValue; uint currentChild = 0; ArrayList children = new ArrayList(); while (currentChild < totalExpected) { BrowseInput input = new BrowseInput(); input.ObjectID = parent.ID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; input.Filter = "*"; input.StartingIndex = currentChild; input.RequestedCount = 1; input.SortCriteria = ""; string containerID = parent.ID; if (currentChild == 0) { test.SetExpectedTestingTime ((++details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress( details.TotalBrowseRequests * 30); } CdsBrowseSearchResults results = Browse(input, test, arg, cds, details); test.SetExpectedTestingTime ((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress( (details.TotalBrowseRequests) * 30); if (results.WorstError >= UPnPTestStates.Failed) { throw new TerminateEarly("\"" + test.Name + "\" is terminating early because " +input.PrintBrowseParams()+ " returned with an error or had problems with the DIDL-Lite."); } else { if (results.NumberReturned != 1) { if (currentChild != 0) { results.SetError(UPnPTestStates.Failed); arg._TestGroup.AddEvent(LogImportance.Low, test.Name, "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned NumberReturned=" +results.NumberReturned+ " when it should logically be 1."); } } if (results.TotalMatches != totalExpected) { if (currentChild != 0) { results.SetError(UPnPTestStates.Failed); arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned TotalMatches=" +results.TotalMatches+ " when it should logically be " +totalExpected+ " as reported in an earlier Browse request. This portion of the test requires that a MediaServer device not be in a state where its content hierarchy will change."); } else { totalExpected = results.TotalMatches; if (totalExpected > 0) { details.ExpectedTotalBrowseRequests += ((int)results.TotalMatches * 2) - 1; test.SetExpectedTestingTime ((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress( details.TotalBrowseRequests * 30); } } } if (results.MediaObjects != null) { if (results.MediaObjects.Count == 1) { IUPnPMedia child = results.MediaObjects[0] as IUPnPMedia; if (child == null) { throw new TestException("\"" + test.Name + "\"" + " has a TEST LOGIC ERROR. Browse returned without errors but the child object's metadata is not stored in an IUPnPMedia object. The offending type is " + results.MediaObjects[0].GetType().ToString(), results.MediaObjects[0]); } // ensure no duplicates in object ID foreach (IUPnPMedia previousChild in details.AllObjects) { if (previousChild.ID == child.ID) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned an object with ID=\"" +child.ID+ "\" which conflicts with a previously seen media object in ParentContainerID=\"" +previousChild.ParentID+ "\"."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } } // ensure updateID is the same between BrowseDirectChildren and earlier BrowseMetadata. try { uint previousUpdateID = (uint) parent.Tag; if (results.UpdateID != previousUpdateID) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned an UpdateID=" +results.UpdateID+ " whilst an UpdateID=" +previousUpdateID+ " was obtained in a previous call for ContainerID=\"" +parent.ID+ "\" with BrowseMetadata."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } } catch (TerminateEarly te) { throw te; } catch (Exception e) { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Error comparing UpdateID values", parent, e); } // add the child to lists: C, parent's child list, and Allobjects try { parent.AddObject(child, false); } catch (Exception e) { AddObjectError aoe = new AddObjectError(); aoe.Parent = parent; aoe.Child = child; throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but the child object could not be added to its parent.", aoe, e); } details.AllObjects.Add(child); children.Add(child); if (child.IsContainer) { C.Enqueue(child); details.TotalContainers++; } else { details.TotalItems++; } // // Do a BrowseMetadata and check to see if the XML values are the same. // CdsBrowseSearchResults compareResults = CheckMetadata(child, cds, test, arg, details); if (compareResults.InvokeError != null) { arg._TestGroup.AddEvent(LogImportance.High, test.Name, test.Name + ": Browse(BrowseDirectChildren,StartingIndex="+currentChild+",RequestedCount=0) on ContainerID=["+containerID+"] succeeded with warnings because a BrowseMetadata request was rejected by the CDS."); } else if (compareResults.ResultErrors.Count > 0) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " failed because a BrowseMetadata request succeeded but the DIDL-Lite could not be represented in object form. Invalid DIDL-Lite is most likely the cause."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } else if (compareResults.WorstError >= UPnPTestStates.Failed) { string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " failed because one or more child object's failed a comparison of results between BrowseDirectChildren and BrowseMetadata or encountered some other critical error in that process."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } else { //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " succeeded."; //arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, msg); } // // Track the metadata properties found so far // as we may use them in Browse SortCriteria // // standard top-level attributes Tags T = Tags.GetInstance(); AddTo(details.PropertyNames, "@"+T[_ATTRIB.id]); AddTo(details.PropertyNames, "@"+T[_ATTRIB.parentID]); AddTo(details.PropertyNames, "@"+T[_ATTRIB.restricted]); if (child.IsContainer) { if (child.IsSearchable) { AddTo(details.PropertyNames, "@"+T[_ATTRIB.searchable]); AddTo(details.PropertyNames, T[_DIDL.Container]+"@"+T[_ATTRIB.searchable]); } AddTo(details.PropertyNames, T[_DIDL.Container]+"@"+T[_ATTRIB.id]); AddTo(details.PropertyNames, T[_DIDL.Container]+"@"+T[_ATTRIB.parentID]); AddTo(details.PropertyNames, T[_DIDL.Container]+"@"+T[_ATTRIB.restricted]); } else if (child.IsItem) { if (child.IsReference) { AddTo(details.PropertyNames, "@"+T[_ATTRIB.refID]); AddTo(details.PropertyNames, T[_DIDL.Item]+"@"+T[_ATTRIB.refID]); } AddTo(details.PropertyNames, T[_DIDL.Item]+"@"+T[_ATTRIB.id]); AddTo(details.PropertyNames, T[_DIDL.Item]+"@"+T[_ATTRIB.parentID]); AddTo(details.PropertyNames, T[_DIDL.Item]+"@"+T[_ATTRIB.restricted]); } // standard metadata IMediaProperties properties = child.MergedProperties; IList propertyNames = properties.PropertyNames; foreach (string propertyName in propertyNames) { if (details.PropertyNames.Contains(propertyName) == false) { details.PropertyNames.Add(propertyName); // add attributes if they are not added IList propertyValues = properties[propertyName]; foreach (ICdsElement val in propertyValues) { ICollection attributes = val.ValidAttributes; foreach (string attribName in attributes) { StringBuilder sbpn = new StringBuilder(); sbpn.AppendFormat("{0}@{1}", propertyName, attribName); string fullAttribName = sbpn.ToString(); AddTo(details.PropertyNames, fullAttribName); } } } // resources IList resources = child.MergedResources; foreach (IMediaResource res in resources) { ICollection attributes = res.ValidAttributes; foreach (string attribName in attributes) { string name1 = "res@"+attribName; string name2 = "@"+attribName; AddTo(details.PropertyNames, name1); AddTo(details.PropertyNames, name2); } } if (resources.Count > 0) { AddTo(details.PropertyNames, T[_DIDL.Res]); } } } else { if (results.TotalMatches > 0) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " did not yield exactly one CDS-compliant media object in its result. Instantiated a total of " +results.MediaObjects.Count+ " media objects."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); throw new TerminateEarly(msg); } } } else { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but no media objects were instantiated.", null); } } currentChild++; } return children; } private static void AddTo(ArrayList al, string val) { if (al.Contains(val) == false) { al.Add(val); } } public static CdsBrowseSearchResults CheckMetadata(IUPnPMedia checkAgainstThis, CpContentDirectory cds, CdsSubTest test, CdsSubTestArgument arg, CdsResult_BrowseAll details) { // // Save a reference to the media object with the most filterable properties int numProperties = 0; if (details.MostMetadata != null) { numProperties = details.MostMetadata.Properties.Count; if (details.MostMetadata.DescNodes.Count > 0) { numProperties ++; } } int checkValue = 0; if (checkAgainstThis.ID != "0") { if (checkAgainstThis.Resources.Length > 0) { checkValue = checkAgainstThis.Properties.Count; if (checkAgainstThis.DescNodes.Count > 0) { checkValue++; } } } if (checkValue > numProperties) { details.MostMetadata = checkAgainstThis; } // do a browsemetadata on the media object and determine if the metadata matche. BrowseInput input = new BrowseInput(); input.ObjectID = checkAgainstThis.ID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; input.Filter = "*"; input.StartingIndex = 0; input.RequestedCount = 0; input.SortCriteria = ""; IUPnPMedia metadata = null; CdsBrowseSearchResults results = Browse(input, test, arg, cds, details); test.SetExpectedTestingTime ((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress( (details.TotalBrowseRequests) * 30); if (results.WorstError <= UPnPTestStates.Warn) { if (results.NumberReturned != 1) { results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned NumberReturned=" +results.NumberReturned+ " when it should logically be 1. This output parameter is not really useful for BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); } if (results.TotalMatches != 1) { results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned TotalMatches=" +results.TotalMatches+ " when it should logically be 1. This output parameter is not really useful BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); } if (results.MediaObjects != null) { if (results.MediaObjects.Count == 1) { metadata = results.MediaObjects[0] as IUPnPMedia; if (metadata == null) { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but the object's metadata is not stored in an IUPnPMedia object. The offending type is " + results.MediaObjects[0].GetType().ToString(), results.MediaObjects[0]); } if (metadata.ID != input.ObjectID) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with ID=\"" +metadata.ID+ "\" when it should be \"" +input.ObjectID+"\" as indicated by the input parameter."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } if (metadata.ParentID != checkAgainstThis.ParentID) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with parentID=\"" +metadata.ParentID+ "\" when it should be \"" +checkAgainstThis.ParentID+ "\"."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } string original; string received; try { original = checkAgainstThis.ToDidl(); received = metadata.ToDidl(); } catch { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " encountered errors with the DIDL-Lite."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); return results; } if (string.Compare(original, received) == 0) { //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " successfully returned a DIDL-Lite media object that succesfully matches with previously seen metadata."; //arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, msg); } else { System.Xml.XmlDocument doc1 = new XmlDocument(); XmlDocument doc2 = new XmlDocument(); doc1.LoadXml(original); doc2.LoadXml(received); bool isMatch = true; foreach (XmlElement el1 in doc1.GetElementsByTagName("*")) { bool foundElement = false; foreach (XmlElement el2 in doc2.GetElementsByTagName("*")) { if ( (el1.Name != "item") && (el1.Name != "container") && (el1.OuterXml == el2.OuterXml) ) { foundElement = true; break; } else if ( ( (el1.Name == "DIDL-Lite") || (el1.Name == "item") || (el1.Name == "container") ) && (el1.Name == el2.Name) ) { foundElement = true; break; } } if (foundElement == false) { isMatch = false; break; } } if (isMatch==false) { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object that failed to match with previously seen metadata."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, test.Name + ": Original=\""+original+"\" Received=\""+received+"\""); } } } else { results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " did not yield exactly one CDS-compliant media object in its result. Instantiated a total of " +results.MediaObjects.Count+ " media objects."; arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } } else { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but no media objects were instantiated.", null); } } return results; } public static CdsBrowseSearchResults GetContainerMetadataAndValidate(string containerID, CpContentDirectory cds, CdsSubTest test, CdsSubTestArgument arg, CdsResult_BrowseAll details, out IUPnPMedia metadata) { BrowseInput input = new BrowseInput(); input.ObjectID = containerID; input.BrowseFlag = CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; input.Filter = "*"; input.StartingIndex = 0; input.RequestedCount = 0; input.SortCriteria = ""; metadata = null; test.SetExpectedTestingTime ((++details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress( details.TotalBrowseRequests * 30); CdsBrowseSearchResults results = Browse(input, test, arg, cds, details); test.SetExpectedTestingTime ((details.ExpectedTotalBrowseRequests) * 30); arg.ActiveTests.UpdateTimeAndProgress( (details.TotalBrowseRequests) * 30); if (results.InvokeError == null) { if (results.NumberReturned != 1) { //results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned NumberReturned=" +results.NumberReturned+ " when it should logically be 1. This output parameter is not really useful for BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; //arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); results.ResultErrors.Add( new Exception(msg) ); } if (results.TotalMatches != 1) { //results.SetError(UPnPTestStates.Warn); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned TotalMatches=" +results.TotalMatches+ " when it should logically be 1. This output parameter is not really useful BrowseMetadata so this logic error does not prevent towards certification, but it should be fixed."; //arg._TestGroup.AddEvent(LogImportance.Low, test.Name, msg); results.ResultErrors.Add( new Exception(msg) ); } if (results.MediaObjects != null) { if (results.MediaObjects.Count == 1) { metadata = results.MediaObjects[0] as IUPnPMedia; if (metadata == null) { throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but the container's metadata is not stored in an IUPnPMedia object. The offending type is " + results.MediaObjects[0].GetType().ToString(), results.MediaObjects[0]); } IMediaContainer imc = metadata as IMediaContainer; // // check metadata // if (imc == null) { //results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object but it was not declared with a \"container\" element."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); results.ResultErrors.Add( new Exception(msg) ); } else { } if (metadata.ID != containerID) { //results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with ID=\"" +metadata.ID+ "\" when it should be \"" +containerID+"\" as indicated by the input parameter."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); results.ResultErrors.Add( new Exception(msg) ); } if (containerID == "0") { if (metadata.ParentID != "-1") { //results.SetError(UPnPTestStates.Failed); string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " returned a DIDL-Lite media object with parentID=\"" +metadata.ID+ "\" when it must be \"-1\" because the container is the root container."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); results.ResultErrors.Add( new Exception(msg) ); } // no need to check parentID values for other containers because // they get checked when getting the children for this container. } if (results.WorstError < UPnPTestStates.Failed) { //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " succeeded."; //arg._TestGroup.AddEvent(LogImportance.Remark, test.Name, msg); } } else { //results.SetError(UPnPTestStates.Failed); //string msg = "\"" + test.Name + "\": " + input.PrintBrowseParams() + " did not yield exactly one CDS-compliant media object in its result. Instantiated a total of " +results.MediaObjects.Count+ " media objects."; //arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg); } } else { //throw new TestException(test.Name + " has a TEST LOGIC ERROR. Browse returned without errors but no media objects were instantiated.", null); } } if ((results.InvokeError != null) || (results.ResultErrors.Count > 0)) { StringBuilder msg = new StringBuilder(); results.SetError(UPnPTestStates.Failed); msg.AppendFormat("\"{0}\": {1} did not yield exactly one CDS-compliant media object in its result. Instantiated a total of {2} media objects.", test.Name, input.PrintBrowseParams(), results.MediaObjects.Count); msg.AppendFormat("\r\nAdditional Information:"); if (results.InvokeError != null) { msg.AppendFormat("\r\n{0}", results.InvokeError.Message); } foreach (Exception e in results.ResultErrors) { msg.AppendFormat("\r\n{0}", e.Message); } arg._TestGroup.AddEvent(LogImportance.Critical, test.Name, msg.ToString()); } return results; } protected override void SetTestInfo() { this._Name = "Browse All"; this._Description = "Browse entire hierarchy using Filter=\"*\", StartingIndex=?, RequestedCount=1, SortCriteria=\"\"."; this._ExpectedTestingTime = 30; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using GraphQL.Conversion; using GraphQL.StarWars.Types; using GraphQL.Types; using GraphQL.Utilities; using Shouldly; using Xunit; namespace GraphQL.Tests.Types { public class ComplexGraphTypeTests { internal class ComplexType<T> : ObjectGraphType<T> { public ComplexType() { Name = typeof(T).GetFriendlyName().Replace("<", "Of").Replace(">", ""); } } internal class GenericFieldType<T> : FieldType { } [Description("Object for test")] [Obsolete("Obsolete for test")] internal class TestObject { public int? someInt { get; set; } public KeyValuePair<int, string> valuePair { get; set; } public List<int> someList { get; set; } [Description("Super secret")] public string someString { get; set; } [Obsolete("Use someInt")] public bool someBoolean { get; set; } [DefaultValue(typeof(DateTime), "2019/03/14")] public DateTime someDate { get; set; } /// <summary> /// Description from XML comment /// </summary> public short someShort { get; set; } public ushort someUShort { get; set; } public ulong someULong { get; set; } public uint someUInt { get; set; } public IEnumerable someEnumerable { get; set; } public IEnumerable<string> someEnumerableOfString { get; set; } [Required] public string someRequiredString { get; set; } public Direction someEnum { get; set; } public Direction? someNullableEnum { get; set; } public List<int?> someListWithNullable { get; set; } [Required] public List<int> someRequiredList { get; set; } [Required] public List<int?> someRequiredListWithNullable { get; set; } public int someNotNullInt { get; set; } public Money someMoney { get; set; } } [GraphQLMetadata(InputType = typeof(AutoRegisteringInputObjectGraphType<Money>), OutputType = typeof(AutoRegisteringObjectGraphType<Money>))] internal class Money { public decimal Amount { get; set; } public string Currency { get; set; } } internal enum Direction { Asc, /// <summary> /// Descending Order /// </summary> Desc, [Obsolete("Do not use Random. This makes no sense!")] Random } [Fact] public void auto_register_object_graph_type() { var schema = new Schema(); var type = new AutoRegisteringObjectGraphType<TestObject>(o => o.valuePair, o => o.someEnumerable); schema.Query = type; schema.Initialize(); type.Name.ShouldBe(nameof(TestObject)); type.Description.ShouldBe("Object for test"); type.DeprecationReason.ShouldBe("Obsolete for test"); type.Fields.Count.ShouldBe(18); type.Fields.First(f => f.Name == nameof(TestObject.someString)).Description.ShouldBe("Super secret"); type.Fields.First(f => f.Name == nameof(TestObject.someString)).Type.ShouldBe(typeof(StringGraphType)); type.Fields.First(f => f.Name == nameof(TestObject.someRequiredString)).Type.ShouldBe(typeof(NonNullGraphType<StringGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someInt)).Type.ShouldBe(typeof(IntGraphType)); type.Fields.First(f => f.Name == nameof(TestObject.someNotNullInt)).Type.ShouldBe(typeof(NonNullGraphType<IntGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someBoolean)).DeprecationReason.ShouldBe("Use someInt"); type.Fields.First(f => f.Name == nameof(TestObject.someDate)).DefaultValue.ShouldBe(new DateTime(2019, 3, 14)); // disabled to make tests stable without touch GlobalSwitches //type.Fields.First(f => f.Name == nameof(TestObject.someShort)).Description.ShouldBe("Description from XML comment"); type.Fields.First(f => f.Name == nameof(TestObject.someEnumerableOfString)).Type.ShouldBe(typeof(ListGraphType<StringGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someEnum)).Type.ShouldBe(typeof(NonNullGraphType<EnumerationGraphType<Direction>>)); type.Fields.First(f => f.Name == nameof(TestObject.someNullableEnum)).Type.ShouldBe(typeof(EnumerationGraphType<Direction>)); type.Fields.First(f => f.Name == nameof(TestObject.someList)).Type.ShouldBe(typeof(ListGraphType<NonNullGraphType<IntGraphType>>)); type.Fields.First(f => f.Name == nameof(TestObject.someListWithNullable)).Type.ShouldBe(typeof(ListGraphType<IntGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someRequiredList)).Type.ShouldBe(typeof(NonNullGraphType<ListGraphType<NonNullGraphType<IntGraphType>>>)); type.Fields.First(f => f.Name == nameof(TestObject.someRequiredListWithNullable)).Type.ShouldBe(typeof(NonNullGraphType<ListGraphType<IntGraphType>>)); type.Fields.First(f => f.Name == nameof(TestObject.someMoney)).Type.ShouldBe(typeof(AutoRegisteringObjectGraphType<Money>)); var enumType = new EnumerationGraphType<Direction>(); // disabled to make tests stable without touch GlobalSwitches //enumType.Values["DESC"].Description.ShouldBe("Descending Order"); enumType.Values["RANDOM"].DeprecationReason.ShouldBe("Do not use Random. This makes no sense!"); } [Fact] public void auto_register_input_object_graph_type() { var schema = new Schema(); var type = new AutoRegisteringInputObjectGraphType<TestObject>(o => o.valuePair, o => o.someEnumerable); var query = new ObjectGraphType(); query.Field<StringGraphType>("test", arguments: new QueryArguments(new QueryArgument(type) { Name = "input" })); schema.Query = query; schema.Initialize(); type.Name.ShouldBe(nameof(TestObject)); type.Description.ShouldBe("Object for test"); type.DeprecationReason.ShouldBe("Obsolete for test"); type.Fields.Count.ShouldBe(18); type.Fields.First(f => f.Name == nameof(TestObject.someString)).Description.ShouldBe("Super secret"); type.Fields.First(f => f.Name == nameof(TestObject.someString)).Type.ShouldBe(typeof(StringGraphType)); type.Fields.First(f => f.Name == nameof(TestObject.someRequiredString)).Type.ShouldBe(typeof(NonNullGraphType<StringGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someInt)).Type.ShouldBe(typeof(IntGraphType)); type.Fields.First(f => f.Name == nameof(TestObject.someNotNullInt)).Type.ShouldBe(typeof(NonNullGraphType<IntGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someBoolean)).DeprecationReason.ShouldBe("Use someInt"); type.Fields.First(f => f.Name == nameof(TestObject.someDate)).DefaultValue.ShouldBe(new DateTime(2019, 3, 14)); // disabled to make tests stable without touch GlobalSwitches //type.Fields.First(f => f.Name == nameof(TestObject.someShort)).Description.ShouldBe("Description from XML comment"); type.Fields.First(f => f.Name == nameof(TestObject.someEnumerableOfString)).Type.ShouldBe(typeof(ListGraphType<StringGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someEnum)).Type.ShouldBe(typeof(NonNullGraphType<EnumerationGraphType<Direction>>)); type.Fields.First(f => f.Name == nameof(TestObject.someNullableEnum)).Type.ShouldBe(typeof(EnumerationGraphType<Direction>)); type.Fields.First(f => f.Name == nameof(TestObject.someList)).Type.ShouldBe(typeof(ListGraphType<NonNullGraphType<IntGraphType>>)); type.Fields.First(f => f.Name == nameof(TestObject.someListWithNullable)).Type.ShouldBe(typeof(ListGraphType<IntGraphType>)); type.Fields.First(f => f.Name == nameof(TestObject.someRequiredList)).Type.ShouldBe(typeof(NonNullGraphType<ListGraphType<NonNullGraphType<IntGraphType>>>)); type.Fields.First(f => f.Name == nameof(TestObject.someRequiredListWithNullable)).Type.ShouldBe(typeof(NonNullGraphType<ListGraphType<IntGraphType>>)); type.Fields.First(f => f.Name == nameof(TestObject.someMoney)).Type.ShouldBe(typeof(AutoRegisteringInputObjectGraphType<Money>)); var enumType = new EnumerationGraphType<Direction>(); // disabled to make tests stable without touch GlobalSwitches //enumType.Values["DESC"].Description.ShouldBe("Descending Order"); enumType.Values["RANDOM"].DeprecationReason.ShouldBe("Do not use Random. This makes no sense!"); } [Fact] public void accepts_property_expressions() { var schema = new Schema(); var type = new ComplexType<Droid>(); _ = type.Field(d => d.Name); schema.Query = type; schema.Initialize(); type.Fields.Last().Name.ShouldBe("name"); type.Fields.Last().Type.ShouldBe(typeof(NonNullGraphType<StringGraphType>)); } [Fact] public void allows_custom_name() { var type = new ComplexType<Droid>(); _ = type.Field(d => d.Name) .Name("droid"); type.Fields.Last().Name.ShouldBe("droid"); } [Fact] public void allows_nullable_types() { var schema = new Schema(); var type = new ComplexType<Droid>(); type.Field("appearsIn", d => d.AppearsIn.First(), nullable: true); schema.Query = type; schema.Initialize(); type.Fields.Last().Type.ShouldBe(typeof(IntGraphType)); } [Fact] public void infers_from_nullable_types() { var schema = new Schema(); var type = new ComplexType<TestObject>(); type.Field(d => d.someInt, nullable: true); schema.Query = type; schema.Initialize(); type.Fields.Last().Type.ShouldBe(typeof(IntGraphType)); } [Fact] public void infers_from_list_types() { var schema = new Schema(); var type = new ComplexType<TestObject>(); type.Field(d => d.someList, nullable: true); schema.Query = type; schema.Initialize(); type.Fields.Last().Type.ShouldBe(typeof(ListGraphType<NonNullGraphType<IntGraphType>>)); } [Fact] public void infers_field_description_from_expression() { var type = new ComplexType<TestObject>(); _ = type.Field(d => d.someString); type.Fields.Last().Description.ShouldBe("Super secret"); } [Fact] public void infers_field_deprecation_from_expression() { var type = new ComplexType<TestObject>(); _ = type.Field(d => d.someBoolean); type.Fields.Last().DeprecationReason.ShouldBe("Use someInt"); } [Fact] public void infers_field_default_from_expression() { var type = new ComplexType<TestObject>(); _ = type.Field(d => d.someDate); type.Fields.Last().DefaultValue.ShouldBe(new DateTime(2019, 3, 14)); } [Fact] public void throws_when_name_is_not_inferable() { var type = new ComplexType<Droid>(); var exp = Should.Throw<ArgumentException>(() => type.Field(d => d.AppearsIn.First())); exp.Message.ShouldBe("Cannot infer a Field name from the expression: 'd.AppearsIn.First()' on parent GraphQL type: 'Droid'."); } [Fact] public void throws_when_type_is_not_inferable() { var type = new ComplexType<TestObject>(); type.Field(d => d.valuePair); var schema = new Schema { Query = type }; var exp = Should.Throw<InvalidOperationException>(() => schema.Initialize()); exp.Message.ShouldStartWith($"The GraphQL type for field 'TestObject.valuePair' could not be derived implicitly. Could not find type mapping from CLR type '{typeof(KeyValuePair<int, string>).FullName}' to GraphType. Did you forget to register the type mapping with the 'ISchema.RegisterTypeMapping'?"); } [Fact] public void throws_when_type_is_incompatible() { var type = new ComplexType<TestObject>(); var exp = Should.Throw<ArgumentException>(() => type.Field(d => d.someInt)); exp.InnerException.Message.ShouldStartWith("Explicitly nullable type: Nullable<Int32> cannot be coerced to a non nullable GraphQL type."); } [Fact] public void create_field_with_func_resolver() { var type = new ComplexType<Droid>(); _ = type.Field<StringGraphType>("name", resolve: context => context.Source.Name); type.Fields.Last().Type.ShouldBe(typeof(StringGraphType)); } [Fact] public void throws_informative_exception_when_no_types_defined() { var type = new ComplexType<Droid>(); var fieldType = new FieldType { Name = "name", ResolvedType = null, Type = null, }; var exception = Should.Throw<ArgumentOutOfRangeException>(() => type.AddField(fieldType)); exception.ParamName.ShouldBe("fieldType"); exception.Message.ShouldStartWith("The declared field 'name' on 'Droid' requires a field 'Type' when no 'ResolvedType' is provided."); } [Fact] public void throws_informative_exception_when_no_types_defined_on_more_generic_type() { var type = new ComplexType<List<Droid>>(); var fieldType = new GenericFieldType<List<Droid>> { Name = "genericname", ResolvedType = null, Type = null, }; var exception = Should.Throw<ArgumentOutOfRangeException>(() => type.AddField(fieldType)); exception.ParamName.ShouldBe("fieldType"); exception.Message.ShouldStartWith("The declared field 'genericname' on 'ListOfDroid' requires a field 'Type' when no 'ResolvedType' is provided."); } private static Exception test_field_name(string fieldName) { // test failure return Should.Throw<ArgumentOutOfRangeException>(() => { var type = new ObjectGraphType(); type.Field<StringGraphType>(fieldName); var schema = new Schema { Query = type }; schema.Initialize(); }); } [Theory] [InlineData("__id")] [InlineData("___id")] public void throws_when_field_name_prefix_with_reserved_underscores(string fieldName) { var exception = test_field_name(fieldName); exception.Message.ShouldStartWith($"A field name: '{fieldName}' must not begin with __, which is reserved by GraphQL introspection."); } [Theory] [InlineData("i#d")] [InlineData("i$d")] [InlineData("id$")] public void throws_when_field_name_doesnot_follow_spec(string fieldName) { var exception = test_field_name(fieldName); exception.Message.ShouldStartWith($"A field name must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but '{fieldName}' does not."); } [Theory] [InlineData("__id")] [InlineData("___id")] [InlineData("i#d")] [InlineData("i$d")] [InlineData("id$")] public void does_not_throw_with_filtering_nameconverter(string fieldName) { GlobalSwitches.NameValidation = (n, t) => { }; // disable "before" checks try { var type = new ObjectGraphType(); type.Field<StringGraphType>(fieldName); var schema = new Schema { Query = type, NameConverter = new TestNameConverter(fieldName, "pass") }; schema.Initialize(); } finally { GlobalSwitches.NameValidation = NameValidator.ValidateDefault; // restore defaults } } [Fact] public void throws_with_bad_namevalidator() { var exception = Should.Throw<ArgumentOutOfRangeException>(() => { var type = new ObjectGraphType(); type.Field<StringGraphType>("hello"); var schema = new Schema { Query = type, NameConverter = new TestNameConverter("hello", "hello$") }; schema.Initialize(); }); exception.Message.ShouldStartWith($"A field name must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but 'hello$' does not."); } private class TestNameConverter : INameConverter { private readonly string _from; private readonly string _to; public TestNameConverter(string from, string to) { _from = from; _to = to; } public string NameForArgument(string argumentName, IComplexGraphType parentGraphType, FieldType field) => argumentName == _from ? _to : argumentName; public string NameForField(string fieldName, IComplexGraphType parentGraphType) => fieldName == _from ? _to : fieldName; } [Theory] [InlineData("")] [InlineData(null)] public void throws_when_field_name_is_null_or_empty(string fieldName) { var type = new ComplexType<TestObject>(); var exception = Should.Throw<ArgumentOutOfRangeException>(() => type.Field<StringGraphType>(fieldName)); exception.Message.ShouldStartWith("A field name can not be null or empty."); } [Theory] [InlineData("")] [InlineData(null)] public void throws_when_field_name_is_null_or_empty_using_field_builder(string fieldName) { var type = new ComplexType<TestObject>(); var exception = Should.Throw<ArgumentOutOfRangeException>(() => type.Field<StringGraphType>().Name(fieldName)); exception.Message.ShouldStartWith("A field name can not be null or empty."); } [Theory] [InlineData("name")] [InlineData("Name")] [InlineData("_name")] [InlineData("test_name")] public void should_not_throw_exception_on_valid_field_name(string fieldName) { var type = new ComplexType<TestObject>(); var field = type.Field<StringGraphType>(fieldName); field.Name.ShouldBe(fieldName); } [Theory] [InlineData("name")] [InlineData("Name")] [InlineData("_name")] [InlineData("test_name")] public void should_not_throw_exception_on_valid_field_name_using_field_builder(string fieldName) { var type = new ComplexType<TestObject>(); type.Field<StringGraphType>().Name(fieldName); type.Fields.Last().Name.ShouldBe(fieldName); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.IO; namespace Amazon.Runtime.Internal.Util { /// <summary> /// A wrapper stream. /// </summary> public class WrapperStream : Stream { /// <summary> /// Base stream. /// </summary> protected Stream BaseStream { get; private set; } /// <summary> /// Initializes WrapperStream with a base stream. /// </summary> /// <param name="baseStream"></param> public WrapperStream(Stream baseStream) { if (baseStream == null) throw new ArgumentNullException("baseStream"); BaseStream = baseStream; } /// <summary> /// Returns the first base non-WrapperStream. /// </summary> /// <returns>First base stream that is non-WrapperStream.</returns> public Stream GetNonWrapperBaseStream() { Stream baseStream = this; do { var partialStream = baseStream as PartialWrapperStream; if (partialStream != null) return partialStream; baseStream = (baseStream as WrapperStream).BaseStream; } while (baseStream is WrapperStream); return baseStream; } /// <summary> /// Returns the first base non-WrapperStream. /// </summary> /// <returns>First base stream that is non-WrapperStream.</returns> public Stream GetSeekableBaseStream() { Stream baseStream = this; do { if (baseStream.CanSeek) return baseStream; baseStream = (baseStream as WrapperStream).BaseStream; } while (baseStream is WrapperStream); if (!baseStream.CanSeek) throw new InvalidOperationException("Unable to find seekable stream"); return baseStream; } /// <summary> /// Returns the first base non-WrapperStream. /// </summary> /// <param name="stream">Potential WrapperStream</param> /// <returns>Base non-WrapperStream.</returns> public static Stream GetNonWrapperBaseStream(Stream stream) { WrapperStream wrapperStream = stream as WrapperStream; if (wrapperStream == null) return stream; return wrapperStream.GetNonWrapperBaseStream(); } public Stream SearchWrappedStream(Func<Stream, bool> condition) { Stream baseStream = this; do { if (condition(baseStream)) return baseStream; if (!(baseStream is WrapperStream)) return null; baseStream = (baseStream as WrapperStream).BaseStream; } while (baseStream != null); return baseStream; } public static Stream SearchWrappedStream(Stream stream, Func<Stream, bool> condition) { WrapperStream wrapperStream = stream as WrapperStream; if (wrapperStream == null) return condition(stream) ? stream : null; return wrapperStream.SearchWrappedStream(condition); } #region Stream overrides /// <summary> /// Gets a value indicating whether the current stream supports reading. /// True if the stream supports reading; otherwise, false. /// </summary> public override bool CanRead { get { return BaseStream.CanRead; } } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// True if the stream supports seeking; otherwise, false. /// </summary> public override bool CanSeek { get { return BaseStream.CanSeek; } } /// <summary> /// Gets a value indicating whether the current stream supports writing. /// True if the stream supports writing; otherwise, false. /// </summary> public override bool CanWrite { get { return BaseStream.CanWrite; } } /// <summary> /// Closes the current stream and releases any resources (such as sockets and /// file handles) associated with the current stream. /// </summary> #if !WIN_RT public override void Close() { BaseStream.Close(); } #else protected override void Dispose(bool disposing) { base.Dispose(disposing); BaseStream.Dispose(); } #endif /// <summary> /// Gets the length in bytes of the stream. /// </summary> public override long Length { get { return BaseStream.Length; } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> public override long Position { get { return BaseStream.Position; } set { BaseStream.Position = value; } } /// <summary> /// Gets or sets a value, in miliseconds, that determines how long the stream /// will attempt to read before timing out. /// </summary> public override int ReadTimeout { get { return BaseStream.ReadTimeout; } set { BaseStream.ReadTimeout = value; } } /// <summary> /// Gets or sets a value, in miliseconds, that determines how long the stream /// will attempt to write before timing out. /// </summary> public override int WriteTimeout { get { return BaseStream.WriteTimeout; } set { BaseStream.WriteTimeout = value; } } /// <summary> /// Clears all buffers for this stream and causes any buffered data to be written /// to the underlying device. /// </summary> public override void Flush() { BaseStream.Flush(); } /// <summary> /// Reads a sequence of bytes from the current stream and advances the position /// within the stream by the number of bytes read. /// </summary> /// <param name="buffer"> /// An array of bytes. When this method returns, the buffer contains the specified /// byte array with the values between offset and (offset + count - 1) replaced /// by the bytes read from the current source. /// </param> /// <param name="offset"> /// The zero-based byte offset in buffer at which to begin storing the data read /// from the current stream. /// </param> /// <param name="count"> /// The maximum number of bytes to be read from the current stream. /// </param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the /// number of bytes requested if that many bytes are not currently available, /// or zero (0) if the end of the stream has been reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { return BaseStream.Read(buffer, offset, count); } /// <summary> /// Sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the origin parameter.</param> /// <param name="origin"> /// A value of type System.IO.SeekOrigin indicating the reference point used /// to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { return BaseStream.Seek(offset, origin); } /// <summary> /// Sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> public override void SetLength(long value) { BaseStream.SetLength(value); } /// <summary> /// Writes a sequence of bytes to the current stream and advances the current /// position within this stream by the number of bytes written. /// </summary> /// <param name="buffer"> /// An array of bytes. This method copies count bytes from buffer to the current stream. /// </param> /// <param name="offset"> /// The zero-based byte offset in buffer at which to begin copying bytes to the /// current stream. /// </param> /// <param name="count">The number of bytes to be written to the current stream.</param> public override void Write(byte[] buffer, int offset, int count) { BaseStream.Write(buffer, offset, count); } #endregion } }
#region File Description //----------------------------------------------------------------------------- // NetRumbleGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.IO; using System.Collections.Generic; using System.Reflection; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; #endregion namespace NetRumble { /// <summary> /// While this used to be an enum in the XNA Framework API, it was removed in version 4.0. /// However, it is still useful as a parameter to specify what kind of particles to draw, /// so it is revitalized here as a global enum. /// </summary> public enum SpriteBlendMode { Additive, AlphaBlend } /// <summary> /// The main type for this game. /// </summary> public class NetRumbleGame : Microsoft.Xna.Framework.Game { #region Graphics Data /// <summary> /// The graphics device manager used to render the game. /// </summary> GraphicsDeviceManager graphics; #endregion #region Game State Management Data /// <summary> /// The manager for all of the user-interface data. /// </summary> ScreenManager screenManager; #endregion #region Initialization Methods /// <summary> /// Constructs a new NetRumbleGame object. /// </summary> public NetRumbleGame() { // initialize the graphics device manager graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = 1280; graphics.PreferredBackBufferHeight = 720; // initialize the content manager Content.RootDirectory = "Content"; // initialize the gamer-services component // this component enables Live sign-in functionality // and updates the Gamer.SignedInGamers collection. Components.Add(new GamerServicesComponent(this)); // initialize the screen manager screenManager = new ScreenManager(this); Components.Add(screenManager); // initialize the audio system AudioManager.Initialize(this, new DirectoryInfo(Content.RootDirectory + @"\audio\wav")); } /// <summary> /// Allows the game to perform any initialization it needs to before starting. /// This is where it can query for any required services and load any /// non-graphic related content. Calling base.Initialize will enumerate through /// any components and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); // Useful to turn on SimulateTrialMode here if you want to test launching the game // from an invite and have it start in trial mode. //#if DEBUG // Guide.SimulateTrialMode = true; //#endif // load the initial screens screenManager.AddScreen(new BackgroundScreen()); screenManager.AddScreen(new MainMenuScreen()); // hookup the invite event-processing function NetworkSession.InviteAccepted += new EventHandler<InviteAcceptedEventArgs>(NetworkSession_InviteAccepted); } /// <summary> /// Begins the asynchronous process of joining a game from an invitation. /// </summary> void NetworkSession_InviteAccepted(object sender, InviteAcceptedEventArgs e) { if (Guide.IsTrialMode) { screenManager.invited = e.Gamer; string message = "Need to unlock full version before you can accept this invite."; MessageBoxScreen messageBox = new MessageBoxScreen(message); screenManager.AddScreen(messageBox); System.Console.WriteLine("Cannot accept invite yet because we're in trial mode"); return; } // We will join the game from a method in this screen. MainMenuScreen mainMenu = null; // Keep the background screen and main menu screen but remove all others // to prepare for joining the game we were invited to. foreach (GameScreen screen in screenManager.GetScreens()) { if (screen is BackgroundScreen) { continue; } else if (screen is MainMenuScreen) { mainMenu = screen as MainMenuScreen; } else { // If there's an active network session, we'll need to end it // before attempting to join a new one. MethodInfo method = screen.GetType().GetMethod("EndSession"); if (method != null) { method.Invoke(screen, null); } // Now exit and remove this screen. screen.ExitScreen(); screenManager.RemoveScreen(screen); } } // Now attempt to join the game to which we were invited! if (mainMenu != null) mainMenu.JoinInvitedGame(); } #endregion #region Drawing Methods /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); base.Draw(gameTime); } #endregion #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (NetRumbleGame game = new NetRumbleGame()) { game.Run(); } } } #endregion } }
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 ZhAsoiafWiki.Plus.Web.Areas.HelpPage.ModelDescriptions; using ZhAsoiafWiki.Plus.Web.Areas.HelpPage.Models; namespace ZhAsoiafWiki.Plus.Web.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 (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; /* * Steps to add a new prioritization policy: * * - Add a new value to the UpdatePrioritizationSchemes enum. * - Specify this new value in the [InterestManagement] section of your * Aurora.ini. The name in the config file must match the enum value name * (although it is not case sensitive). * - Write a new GetPriorityBy*() method in this class. * - Add a new entry to the switch statement in GetUpdatePriority() that calls * your method. */ namespace OpenSim.Region.Framework.Scenes { public enum UpdatePrioritizationSchemes { Time = 0, Distance = 1, SimpleAngularDistance = 2, FrontBack = 3, BestAvatarResponsiveness = 4, OOB = 5 } public class Culler : ICuller { private readonly Dictionary<uint, bool> m_previousCulled = new Dictionary<uint, bool>(); private readonly bool m_useDistanceCulling = true; private int m_cachedXOffset; private int m_cachedYOffset; private int m_lastCached; private float m_sizeToForceDualCulling = 10f; private bool m_useCulling = true; public Culler(IScene scene) { IConfig interestConfig = scene.Config.Configs["InterestManagement"]; if (interestConfig != null) { m_useCulling = interestConfig.GetBoolean("UseCulling", m_useCulling); m_useDistanceCulling = interestConfig.GetBoolean("UseDistanceBasedCulling", m_useDistanceCulling); } } #region ICuller Members public bool UseCulling { get { return m_useCulling; } set { m_useCulling = value; } } public bool ShowEntityToClient(IScenePresence client, IEntity entity, IScene scene) { return ShowEntityToClient(client, entity, scene, Util.EnvironmentTickCount()); } #endregion public void Reset() { m_cachedXOffset = 0; m_cachedYOffset = 0; } public bool ShowEntityToClient(IScenePresence client, IEntity entity, IScene scene, int currentTickCount) { if (!m_useCulling) return true; //If we arn't using culling, return true by default to show all prims if (entity == null || client == null || scene == null) return false; bool cull = false; lock (m_previousCulled) { if (m_previousCulled.TryGetValue(entity.LocalId, out cull)) { Int32 diff = currentTickCount - m_lastCached; Int32 timingDiff = (diff >= 0) ? diff : (diff + Util.EnvironmentTickCountMask + 1); if (timingDiff > 5*1000) //Only recheck every 5 seconds { m_lastCached = Util.EnvironmentTickCount(); m_previousCulled.Clear(); } else return cull; } } if (m_useDistanceCulling && !DistanceCulling(client, entity, scene)) { lock (m_previousCulled) m_previousCulled[entity.LocalId] = false; return false; } if (!ParcelPrivateCulling(client, entity)) { lock (m_previousCulled) m_previousCulled[entity.LocalId] = false; return false; } //No more, guess its fine lock (m_previousCulled) m_previousCulled[entity.LocalId] = true; return true; } private bool ParcelPrivateCulling(IScenePresence client, IEntity entity) { if (entity is IScenePresence) { IScenePresence pEntity = (IScenePresence) entity; if ((client.CurrentParcel != null && client.CurrentParcel.LandData.Private) || (pEntity.CurrentParcel != null && pEntity.CurrentParcel.LandData.Private)) { //We need to check whether this presence is sitting on anything, so that we can check from the object's // position, rather than the offset position of the object that the avatar is sitting on if (pEntity.CurrentParcelUUID != client.CurrentParcelUUID) return false; //Can't see avatar's outside the parcel } } return true; } public bool DistanceCulling(IScenePresence client, IEntity entity, IScene scene) { float DD = client.DrawDistance; if (DD < 32) //Limit to a small distance DD = 32; if (DD > scene.RegionInfo.RegionSizeX && DD > scene.RegionInfo.RegionSizeY) return true; //Its larger than the region, no culling check even necessary Vector3 posToCheckFrom = client.GetAbsolutePosition(); if (client.IsChildAgent) { /*if (m_cachedXOffset == 0 && m_cachedYOffset == 0) //Not found yet { int RegionLocX, RegionLocY; Util.UlongToInts(client.RootAgentHandle, out RegionLocX, out RegionLocY); m_cachedXOffset = scene.RegionInfo.RegionLocX - RegionLocX; m_cachedYOffset = scene.RegionInfo.RegionLocY - RegionLocY; } //We need to add the offset so that we can check from the right place in child regions if (m_cachedXOffset < 0) posToCheckFrom.X = scene.RegionInfo.RegionSizeX - (scene.RegionInfo.RegionSizeX + client.AbsolutePosition.X + m_cachedXOffset); if (m_cachedYOffset < 0) posToCheckFrom.Y = scene.RegionInfo.RegionSizeY - (scene.RegionInfo.RegionSizeY + client.AbsolutePosition.Y + m_cachedYOffset); if (m_cachedXOffset > scene.RegionInfo.RegionSizeX) posToCheckFrom.X = scene.RegionInfo.RegionSizeX - (scene.RegionInfo.RegionSizeX - (client.AbsolutePosition.X + m_cachedXOffset)); if (m_cachedYOffset > scene.RegionInfo.RegionSizeY) posToCheckFrom.Y = scene.RegionInfo.RegionSizeY - (scene.RegionInfo.RegionSizeY - (client.AbsolutePosition.Y + m_cachedYOffset));*/ } Vector3 entityPosToCheckFrom = Vector3.Zero; bool doHeavyCulling = false; if (entity is ISceneEntity) { doHeavyCulling = true; //We need to check whether this object is an attachment, and if so, set it so that we check from the avatar's // position, rather than from the offset of the attachment ISceneEntity sEntity = (ISceneEntity) entity; if (sEntity.RootChild.IsAttachment) { IScenePresence attachedAvatar = scene.GetScenePresence(sEntity.RootChild.AttachedAvatar); if (attachedAvatar != null) entityPosToCheckFrom = attachedAvatar.AbsolutePosition; } else entityPosToCheckFrom = sEntity.RootChild.GetGroupPosition(); } else if (entity is IScenePresence) { //We need to check whether this presence is sitting on anything, so that we can check from the object's // position, rather than the offset position of the object that the avatar is sitting on IScenePresence pEntity = (IScenePresence) entity; if (pEntity.Sitting) { ISceneChildEntity sittingEntity = scene.GetSceneObjectPart(pEntity.SittingOnUUID); if (sittingEntity != null) entityPosToCheckFrom = sittingEntity.GetGroupPosition(); } else entityPosToCheckFrom = pEntity.GetAbsolutePosition(); } //If the distance is greater than the clients draw distance, its out of range if (Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom) > DD*DD) //Use squares to make it faster than having to do the sqrt { if (!doHeavyCulling) return false; //Don't do the hardcore checks ISceneEntity childEntity = (entity as ISceneEntity); if (childEntity != null && HardCullingCheck(childEntity)) { #region Side culling check (X, Y, Z) plane checks if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(childEntity.OOBsize.X, 0, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(childEntity.OOBsize.X, 0, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(0, childEntity.OOBsize.Y, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(0, childEntity.OOBsize.Y, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(0, 0, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(0, 0, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; #endregion #region Corner checks ((x,y),(-x,-y),(x,-y),(-x,y), (y,z),(-y,-z),(y,-z),(-y,z), (x,z),(-x,-z),(x,-z),(-x,z)) if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(childEntity.OOBsize.X, childEntity.OOBsize.Y, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(childEntity.OOBsize.X, childEntity.OOBsize.Y, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(childEntity.OOBsize.X, -childEntity.OOBsize.Y, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(childEntity.OOBsize.X, -childEntity.OOBsize.Y, 0)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(0, childEntity.OOBsize.Y, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(0, childEntity.OOBsize.Y, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(0, childEntity.OOBsize.Y, -childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(0, childEntity.OOBsize.Y, -childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom + new Vector3(-childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; if ( Vector3.DistanceSquared(posToCheckFrom, entityPosToCheckFrom - new Vector3(-childEntity.OOBsize.X, 0, childEntity.OOBsize.Z)) < DD*DD) //Use squares to make it faster than having to do the sqrt return true; #endregion } return false; } return true; } private bool HardCullingCheck(ISceneEntity childEntity) { Vector3 OOBsize = childEntity.OOBsize; if (LengthSquared(OOBsize.X, OOBsize.Y) > m_sizeToForceDualCulling*m_sizeToForceDualCulling || LengthSquared(OOBsize.Y, OOBsize.Z) > m_sizeToForceDualCulling*m_sizeToForceDualCulling || LengthSquared(OOBsize.Z, OOBsize.X) > m_sizeToForceDualCulling*m_sizeToForceDualCulling) return true; return false; } private float LengthSquared(float a, float b) { return (a*a) + (b*b); } } public class Prioritizer : IPrioritizer { private readonly double m_childReprioritizationDistance = 20.0; public UpdatePrioritizationSchemes UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness; public Prioritizer(IScene scene) { IConfig interestConfig = scene.Config.Configs["InterestManagement"]; if (interestConfig != null) { string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "BestAvatarResponsiveness").Trim().ToLower(); m_childReprioritizationDistance = interestConfig.GetDouble("ChildReprioritizationDistance", 20.0); try { UpdatePrioritizationScheme = (UpdatePrioritizationSchemes) Enum.Parse(typeof (UpdatePrioritizationSchemes), update_prioritization_scheme, true); } catch (Exception) { MainConsole.Instance.Warn( "[Prioritizer]: UpdatePrioritizationScheme was not recognized, setting to default prioritizer BestAvatarResponsiveness"); UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness; } } //MainConsole.Instance.Info("[Prioritizer]: Using the " + UpdatePrioritizationScheme + " prioritization scheme"); } #region IPrioritizer Members public double ChildReprioritizationDistance { get { return m_childReprioritizationDistance; } } public double GetUpdatePriority(IScenePresence client, IEntity entity) { double priority = 0; if (entity == null) return double.PositiveInfinity; bool adjustRootPriority = true; try { /*switch (UpdatePrioritizationScheme) { case UpdatePrioritizationSchemes.Time: priority = GetPriorityByTime(); break; case UpdatePrioritizationSchemes.Distance: priority = GetPriorityByDistance(client, entity); break; case UpdatePrioritizationSchemes.SimpleAngularDistance: priority = GetPriorityByDistance(client, entity); //This (afaik) always has been the same in OpenSim as just distance (it is in 0.6.9 anyway) break; case UpdatePrioritizationSchemes.FrontBack: priority = GetPriorityByFrontBack(client, entity); break; case UpdatePrioritizationSchemes.BestAvatarResponsiveness: priority = GetPriorityByBestAvatarResponsiveness(client, entity); break; case UpdatePrioritizationSchemes.OOB:*/ adjustRootPriority = false; //It doesn't need it priority = GetPriorityByOOBDistance(client, entity); /*break; default: throw new InvalidOperationException("UpdatePrioritizationScheme not defined."); }*/ } catch (Exception ex) { if (!(ex is InvalidOperationException)) { MainConsole.Instance.Warn("[PRIORITY]: Error in finding priority of a prim/user:" + ex); } //Set it to max if it errors priority = double.PositiveInfinity; } // Adjust priority so that root prims are sent to the viewer first. This is especially important for // attachments acting as huds, since current viewers fail to display hud child prims if their updates // arrive before the root one. if (adjustRootPriority && entity is ISceneChildEntity) { ISceneChildEntity sop = ((ISceneChildEntity) entity); if (sop.IsRoot) { ISceneEntity grp = sop.ParentEntity; priority -= (grp.BSphereRadiusSQ + 0.5f); } if (sop.IsRoot) { if (priority >= double.MinValue + 0.05) priority -= 0.05; } else { if (priority <= double.MaxValue - 0.05) priority += 0.05; } } return priority; } #endregion private double GetPriorityByOOBDistance(IScenePresence presence, IEntity entity) { // If this is an update for our own avatar give it the highest priority if (presence == entity) return 0.0; // Use the camera position for local agents and avatar position for remote agents Vector3 presencePos = (presence.IsChildAgent) ? presence.AbsolutePosition : presence.CameraPosition; // Use group position for child prims Vector3 entityPos; float distsq; if (entity is SceneObjectGroup) { SceneObjectGroup g = (SceneObjectGroup) entity; entityPos = g.AbsolutePosition + g.OOBoffset*g.GroupRotation; distsq = g.BSphereRadiusSQ - Vector3.DistanceSquared(presencePos, entityPos); } else if (entity is SceneObjectPart) { SceneObjectPart p = (SceneObjectPart) entity; if (p.IsRoot) { SceneObjectGroup g = p.ParentGroup; entityPos = g.AbsolutePosition + g.OOBoffset*g.GroupRotation; distsq = g.BSphereRadiusSQ - Vector3.DistanceSquared(presencePos, entityPos); } else { distsq = -p.clampedAABdistanceToSQ(presencePos) + 1.0f; } } else { entityPos = entity.AbsolutePosition; distsq = - Vector3.DistanceSquared(presencePos, entityPos); } if (distsq > 0.0f) distsq = 0.0f; return distsq; } private double GetPriorityByTime() { return DateTime.UtcNow.ToOADate(); } private double GetPriorityByDistance(IScenePresence presence, IEntity entity) { // If this is an update for our own avatar give it the highest priority if (presence == entity) return 0.0; // Use the camera position for local agents and avatar position for remote agents Vector3 presencePos = (presence.IsChildAgent) ? presence.AbsolutePosition : presence.CameraPosition; // Use group position for child prims Vector3 entityPos = entity.AbsolutePosition; return Vector3.DistanceSquared(presencePos, entityPos); } private double GetPriorityByFrontBack(IScenePresence presence, IEntity entity) { // If this is an update for our own avatar give it the highest priority if (presence == entity) return 0.0; // Use group position for child prims Vector3 entityPos = entity.AbsolutePosition; if (entity is SceneObjectPart) { // Can't use Scene.GetGroupByPrim() here, since the entity may have been delete from the scene // before its scheduled update was triggered //entityPos = m_scene.GetGroupByPrim(entity.LocalId).AbsolutePosition; entityPos = ((SceneObjectPart) entity).ParentGroup.AbsolutePosition; } else { entityPos = entity.AbsolutePosition; } if (!presence.IsChildAgent) { // Root agent. Use distance from camera and a priority decrease for objects behind us Vector3 camPosition = presence.CameraPosition; Vector3 camAtAxis = presence.CameraAtAxis; // Distance double priority = Vector3.DistanceSquared(camPosition, entityPos); // Plane equation float d = -Vector3.Dot(camPosition, camAtAxis); float p = Vector3.Dot(camAtAxis, entityPos) + d; if (p < 0.0f) priority *= 2.0; return priority; } else { // Child agent. Use the normal distance method Vector3 presencePos = presence.AbsolutePosition; return Vector3.DistanceSquared(presencePos, entityPos); } } private double GetPriorityByBestAvatarResponsiveness(IScenePresence presence, IEntity entity) { // If this is an update for our own avatar give it the highest priority if (presence.UUID == entity.UUID) return 0.0; if (entity == null) return double.NaN; if (entity is IScenePresence) return 1.0; // Use group position for child prims Vector3 entityPos = entity.AbsolutePosition; if (!presence.IsChildAgent) { // Root agent. Use distance from camera and a priority decrease for objects behind us Vector3 camPosition = presence.CameraPosition; Vector3 camAtAxis = presence.CameraAtAxis; // Distance double priority = Vector3.DistanceSquared(camPosition, entityPos); // Plane equation float d = -Vector3.Dot(camPosition, camAtAxis); float p = Vector3.Dot(camAtAxis, entityPos) + d; if (p < 0.0f) priority *= 2.0; //Add distance again to really emphasize it priority += Vector3.DistanceSquared(presence.AbsolutePosition, entityPos); if ((Vector3.Distance(presence.AbsolutePosition, entityPos)/2) > presence.DrawDistance) { //Outside of draw distance! priority *= 2; } SceneObjectPart rootPart = null; if (entity is SceneObjectPart) { if (((SceneObjectPart) entity).ParentGroup != null && ((SceneObjectPart) entity).ParentGroup.RootPart != null) rootPart = ((SceneObjectPart) entity).ParentGroup.RootPart; } if (entity is SceneObjectGroup) { if (((SceneObjectGroup) entity).RootPart != null) rootPart = ((SceneObjectGroup) entity).RootPart; } if (rootPart != null) { PhysicsActor physActor = rootPart.PhysActor; // Objects avatars are sitting on should be prioritized more if (presence.ParentID == rootPart.UUID) { //Objects that are physical get more priority. if (physActor != null && physActor.IsPhysical) return 0.0; else return 1.2; } if (physActor == null || physActor.IsPhysical) priority /= 2; //Emphasize physical objs //Factor in the size of objects as well, big ones are MUCH more important than small ones float size = rootPart.ParentGroup.GroupScale().Length(); //Cap size at 200 so that it doesn't completely overwhelm other objects if (size > 200) size = 200; //Do it dynamically as well so that larger prims get smaller quicker priority /= size > 40 ? (size/35) : (size > 20 ? (size/17) : 1); if (rootPart.IsAttachment) { //Attachments are always high! priority = 0.5; } } //Closest first! return priority; } else { // Child agent. Use the normal distance method Vector3 presencePos = presence.AbsolutePosition; return Vector3.DistanceSquared(presencePos, entityPos); } } } }
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; //get all the materials to change them during runtime public Material depthImage; public Material regular; public Material flir; public Material grey; public GameObject plane; public GameObject cube1; public GameObject cube2; public GameObject cube3; public GameObject cube4; private GameObject[] cubes; public GameObject wall1; public GameObject wall2; public GameObject wall3; public GameObject wall4; private GameObject[] walls; // 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); cubes = new GameObject[4]; walls = new GameObject[4]; cubes[0] = cube1; cubes[1] = cube2; cubes[2] = cube3; cubes[3] = cube4; walls[0] = wall1; walls[1] = wall2; walls[2] = wall3; walls[3] = wall4; } // Update is called once per frame // added Input for keys 1-4 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; if (Input.GetKeyDown(KeyCode.Alpha1)) { changeMaterials(regular); } if (Input.GetKeyDown(KeyCode.Alpha2)) { changeMaterials(grey); } if (Input.GetKeyDown(KeyCode.Alpha3)) { changeMaterials(depthImage); } if (Input.GetKeyDown(KeyCode.Alpha4)) { changeMaterials(flir); } } private void changeMaterials(Material newMaterial) { foreach(GameObject wall in walls) { wall.GetComponent<Renderer>().material = newMaterial; } foreach(GameObject cube in cubes) { cube.GetComponent<Renderer>().material = newMaterial; } plane.GetComponent<Renderer>().material = newMaterial; } 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); } } }
using Certify.Models; using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace Certify.UI.Controls { /// <summary> /// Interaction logic for ManagedSites.xaml /// </summary> public partial class ManagedSites { protected ViewModel.AppModel MainViewModel => ViewModel.AppModel.Current; private string _sortOrder { get; set; } = "NameAsc"; public ManagedSites() { InitializeComponent(); DataContext = MainViewModel; SetFilter(); // start listening MainViewModel.PropertyChanged += (obj, args) => { if (args.PropertyName == "ManagedSites" || args.PropertyName == "SelectedItem" && MainViewModel.ManagedSites != null) { SetFilter(); // reset listeners when ManagedSites are reset } }; } private void SetFilter() { CollectionViewSource.GetDefaultView(MainViewModel.ManagedSites).Filter = (item) => { string filter = txtFilter.Text.Trim(); return filter == "" || filter.Split(';').Where(f => f.Trim() != "").Any(f => ((Models.ManagedSite)item).Name.IndexOf(f, StringComparison.OrdinalIgnoreCase) > -1 || (((Models.ManagedSite)item).DomainOptions?.Any(d => d.Domain.IndexOf(f, StringComparison.OrdinalIgnoreCase) > -1) ?? false) || (((Models.ManagedSite)item).Comments ?? "").IndexOf(f, StringComparison.OrdinalIgnoreCase) > -1); }; //sort by name ascending CollectionViewSource.GetDefaultView(MainViewModel.ManagedSites).SortDescriptions.Clear(); if (_sortOrder == "NameAsc") { CollectionViewSource.GetDefaultView(MainViewModel.ManagedSites).SortDescriptions.Add( new System.ComponentModel.SortDescription("Name", System.ComponentModel.ListSortDirection.Ascending) ); } if (_sortOrder == "ExpiryDateAsc") { CollectionViewSource.GetDefaultView(MainViewModel.ManagedSites).SortDescriptions.Add( new System.ComponentModel.SortDescription("DateExpiry", System.ComponentModel.ListSortDirection.Ascending) ); } } private async void ListViewItem_InteractionEvent(object sender, InputEventArgs e) { var item = (ListViewItem)sender; var ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); if (item != null && item.DataContext != null && item.DataContext is ManagedSite) { var site = (ManagedSite)item.DataContext; site = site == MainViewModel.SelectedItem && ctrl ? null : site; if (MainViewModel.SelectedItem != site) { if (await MainViewModel.ConfirmDiscardUnsavedChanges()) { SelectAndFocus(site); } e.Handled = true; } } } private void TxtFilter_TextChanged(object sender, TextChangedEventArgs e) { var defaultView = CollectionViewSource.GetDefaultView(lvManagedSites.ItemsSource); defaultView.Refresh(); if (lvManagedSites.SelectedIndex == -1 && MainViewModel.SelectedItem != null) { // if the data model's selected item has come into view after filter box text // changed, select the item in the list if (defaultView.Filter(MainViewModel.SelectedItem)) { lvManagedSites.SelectedItem = MainViewModel.SelectedItem; } } } private async void TxtFilter_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) ResetFilter(); if (e.Key == Key.Enter || e.Key == Key.Down) { if (lvManagedSites.Items.Count > 0) { // get selected index of filtered list or 0 int index = lvManagedSites.Items.IndexOf(MainViewModel.SelectedItem); var item = lvManagedSites.Items[index == -1 ? 0 : index]; // if navigating away, confirm discard if (item != MainViewModel.SelectedItem && !await MainViewModel.ConfirmDiscardUnsavedChanges()) { return; } // if confirmed, select and focus e.Handled = true; SelectAndFocus(item); } } } private void ResetFilter() { txtFilter.Text = ""; txtFilter.Focus(); if (lvManagedSites.SelectedItem != null) { lvManagedSites.ScrollIntoView(lvManagedSites.SelectedItem); } } private void SelectAndFocus(object obj) { MainViewModel.SelectedItem = obj as ManagedSite; if (lvManagedSites.Items.Count > 0 && lvManagedSites.Items.Contains(MainViewModel.SelectedItem)) { lvManagedSites.UpdateLayout(); // ensure containers exist if (lvManagedSites.ItemContainerGenerator.ContainerFromItem(MainViewModel.SelectedItem) is ListViewItem item) { item.Focus(); item.IsSelected = true; } } } private async void ListViewItem_PreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { ResetFilter(); return; } if (e.Key == Key.Delete && lvManagedSites.SelectedItem != null) { await MainViewModel.DeleteManagedSite(MainViewModel.SelectedItem); if (lvManagedSites.Items.Count > 0) { SelectAndFocus(lvManagedSites.SelectedItem); } return; } object next = MainViewModel.SelectedItem; var item = ((ListViewItem)sender); int index = lvManagedSites.Items.IndexOf(item.DataContext); if (e.Key == Key.Enter) { next = item.DataContext; } var ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); if (e.Key == Key.Space) { next = MainViewModel.SelectedItem != null && ctrl ? null : item.DataContext; } if (e.Key == Key.Up) { next = lvManagedSites.Items[index - 1 > -1 ? index - 1 : 0]; } if (e.Key == Key.Down) { next = lvManagedSites.Items[index + 1 < lvManagedSites.Items.Count ? index + 1 : lvManagedSites.Items.Count - 1]; } if (e.Key == Key.Home) { next = lvManagedSites.Items[0]; } if (e.Key == Key.End) { next = lvManagedSites.Items[lvManagedSites.Items.Count - 1]; } if (e.Key == Key.PageUp) { int pagesize = (int)(lvManagedSites.ActualHeight / item.ActualHeight); next = lvManagedSites.Items[index - pagesize > -1 ? index - pagesize : 0]; } if (e.Key == Key.PageDown) { int pagesize = (int)(lvManagedSites.ActualHeight / item.ActualHeight); next = lvManagedSites.Items[index + pagesize < lvManagedSites.Items.Count ? index + pagesize : lvManagedSites.Items.Count - 1]; } if (next != MainViewModel.SelectedItem) { if (await MainViewModel.ConfirmDiscardUnsavedChanges()) { SelectAndFocus(next); } e.Handled = true; } } private int lastSelectedIndex = -1; private void lvManagedSites_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (MainViewModel.SelectedItem != null && !MainViewModel.ManagedSites.Contains(MainViewModel.SelectedItem)) { if (lvManagedSites.Items.Count == 0) { MainViewModel.SelectedItem = null; txtFilter.Focus(); } else { // selected item was deleted int newIndex = lastSelectedIndex; while (newIndex >= lvManagedSites.Items.Count && newIndex >= -1) { newIndex--; } SelectAndFocus(newIndex == -1 ? null : lvManagedSites.Items[newIndex]); } } lastSelectedIndex = lvManagedSites.SelectedIndex; } private void UserControl_OnLoaded(object sender, RoutedEventArgs e) { var window = Window.GetWindow(this); if (window != null) // null in XAML designer { window.KeyDown += (obj, args) => { if (args.Key == Key.F && Keyboard.Modifiers == ModifierKeys.Control) { txtFilter.Focus(); txtFilter.SelectAll(); } }; } } private void SetListSortOrder_Click(object sender, RoutedEventArgs e) { if (sender is MenuItem) { var menu = sender as MenuItem; _sortOrder = menu.Tag.ToString(); SetFilter(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Windows.Input; using Microsoft.Practices.Prism.Mvvm.Properties; using Microsoft.Practices.Prism.Mvvm; namespace Microsoft.Practices.Prism.Commands { /// <summary> /// The CompositeCommand composes one or more ICommands. /// </summary> public partial class CompositeCommand : ICommand { private readonly List<ICommand> registeredCommands = new List<ICommand>(); private readonly bool monitorCommandActivity; private readonly EventHandler onRegisteredCommandCanExecuteChangedHandler; private List<WeakReference> _canExecuteChangedHandlers; /// <summary> /// Initializes a new instance of <see cref="CompositeCommand"/>. /// </summary> public CompositeCommand() { this.onRegisteredCommandCanExecuteChangedHandler = new EventHandler(this.OnRegisteredCommandCanExecuteChanged); } /// <summary> /// Initializes a new instance of <see cref="CompositeCommand"/>. /// </summary> /// <param name="monitorCommandActivity">Indicates when the command activity is going to be monitored.</param> public CompositeCommand(bool monitorCommandActivity) : this() { this.monitorCommandActivity = monitorCommandActivity; } /// <summary> /// Adds a command to the collection and signs up for the <see cref="ICommand.CanExecuteChanged"/> event of it. /// </summary> /// <remarks> /// If this command is set to monitor command activity, and <paramref name="command"/> /// implements the <see cref="IActiveAwareCommand"/> interface, this method will subscribe to its /// <see cref="IActiveAwareCommand.IsActiveChanged"/> event. /// </remarks> /// <param name="command">The command to register.</param> public virtual void RegisterCommand(ICommand command) { if (command == null) throw new ArgumentNullException("command"); if (command == this) { throw new ArgumentException(Resources.CannotRegisterCompositeCommandInItself); } lock (this.registeredCommands) { if (this.registeredCommands.Contains(command)) { throw new InvalidOperationException(Resources.CannotRegisterSameCommandTwice); } this.registeredCommands.Add(command); } command.CanExecuteChanged += this.onRegisteredCommandCanExecuteChangedHandler; this.OnCanExecuteChanged(); if (this.monitorCommandActivity) { var activeAwareCommand = command as IActiveAware; if (activeAwareCommand != null) { activeAwareCommand.IsActiveChanged += this.Command_IsActiveChanged; } } } /// <summary> /// Removes a command from the collection and removes itself from the <see cref="ICommand.CanExecuteChanged"/> event of it. /// </summary> /// <param name="command">The command to unregister.</param> public virtual void UnregisterCommand(ICommand command) { if (command == null) throw new ArgumentNullException("command"); bool removed; lock (this.registeredCommands) { removed = this.registeredCommands.Remove(command); } if (removed) { command.CanExecuteChanged -= this.onRegisteredCommandCanExecuteChangedHandler; this.OnCanExecuteChanged(); if (this.monitorCommandActivity) { var activeAwareCommand = command as IActiveAware; if (activeAwareCommand != null) { activeAwareCommand.IsActiveChanged -= this.Command_IsActiveChanged; } } } } private void OnRegisteredCommandCanExecuteChanged(object sender, EventArgs e) { this.OnCanExecuteChanged(); } /// <summary> /// Forwards <see cref="ICommand.CanExecute"/> to the registered commands and returns /// <see langword="true" /> if all of the commands return <see langword="true" />. /// </summary> /// <param name="parameter">Data used by the command. /// If the command does not require data to be passed, this object can be set to <see langword="null" />. /// </param> /// <returns><see langword="true" /> if all of the commands return <see langword="true" />; otherwise, <see langword="false" />.</returns> public virtual bool CanExecute(object parameter) { bool hasEnabledCommandsThatShouldBeExecuted = false; ICommand[] commandList; lock (this.registeredCommands) { commandList = this.registeredCommands.ToArray(); } foreach (ICommand command in commandList) { if (this.ShouldExecute(command)) { if (!command.CanExecute(parameter)) { return false; } hasEnabledCommandsThatShouldBeExecuted = true; } } return hasEnabledCommandsThatShouldBeExecuted; } /// <summary> /// Occurs when any of the registered commands raise <see cref="ICommand.CanExecuteChanged"/>. You must keep a hard /// reference to the handler to avoid garbage collection and unexpected results. See remarks for more information. /// </summary> /// <remarks> /// When subscribing to the <see cref="ICommand.CanExecuteChanged"/> event using /// code (not when binding using XAML) will need to keep a hard reference to the event handler. This is to prevent /// garbage collection of the event handler because the command implements the Weak Event pattern so it does not have /// a hard reference to this handler. An example implementation can be seen in the CompositeCommand and CommandBehaviorBase /// classes. In most scenarios, there is no reason to sign up to the CanExecuteChanged event directly, but if you do, you /// are responsible for maintaining the reference. /// </remarks> /// <example> /// The following code holds a reference to the event handler. The myEventHandlerReference value should be stored /// in an instance member to avoid it from being garbage collected. /// <code> /// EventHandler myEventHandlerReference = new EventHandler(this.OnCanExecuteChanged); /// command.CanExecuteChanged += myEventHandlerReference; /// </code> /// </example> public event EventHandler CanExecuteChanged { add { WeakEventHandlerManager.AddWeakReferenceHandler(ref _canExecuteChangedHandlers, value, 2); } remove { WeakEventHandlerManager.RemoveWeakReferenceHandler(_canExecuteChangedHandlers, value); } } /// <summary> /// Forwards <see cref="ICommand.Execute"/> to the registered commands. /// </summary> /// <param name="parameter">Data used by the command. /// If the command does not require data to be passed, this object can be set to <see langword="null" />. /// </param> public virtual void Execute(object parameter) { Queue<ICommand> commands; lock (this.registeredCommands) { commands = new Queue<ICommand>(this.registeredCommands.Where(this.ShouldExecute).ToList()); } while (commands.Count > 0) { ICommand command = commands.Dequeue(); command.Execute(parameter); } } /// <summary> /// Evaluates if a command should execute. /// </summary> /// <param name="command">The command to evaluate.</param> /// <returns>A <see cref="bool"/> value indicating whether the command should be used /// when evaluating <see cref="CompositeCommand.CanExecute"/> and <see cref="CompositeCommand.Execute"/>.</returns> /// <remarks> /// If this command is set to monitor command activity, and <paramref name="command"/> /// implements the <see cref="IActiveAwareCommand"/> interface, /// this method will return <see langword="false" /> if the command's <see cref="IActiveAwareCommand.IsActive"/> /// property is <see langword="false" />; otherwise it always returns <see langword="true" />.</remarks> protected virtual bool ShouldExecute(ICommand command) { var activeAwareCommand = command as IActiveAware; if (this.monitorCommandActivity && activeAwareCommand != null) { return activeAwareCommand.IsActive; } return true; } /// <summary> /// Gets the list of all the registered commands. /// </summary> /// <value>A list of registered commands.</value> /// <remarks>This returns a copy of the commands subscribed to the CompositeCommand.</remarks> public IList<ICommand> RegisteredCommands { get { IList<ICommand> commandList; lock (this.registeredCommands) { commandList = this.registeredCommands.ToList(); } return commandList; } } /// <summary> /// Raises <see cref="ICommand.CanExecuteChanged"/> on the UI thread so every /// command invoker can requery <see cref="ICommand.CanExecute"/> to check if the /// <see cref="CompositeCommand"/> can execute. /// </summary> protected virtual void OnCanExecuteChanged() { WeakEventHandlerManager.CallWeakReferenceHandlers(this, _canExecuteChangedHandlers); } /// <summary> /// Handler for IsActiveChanged events of registered commands. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">EventArgs to pass to the event.</param> private void Command_IsActiveChanged(object sender, EventArgs e) { this.OnCanExecuteChanged(); } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; using System.Linq; namespace Trisoft.ISHRemote.Cmdlets.Folder { /// <summary> /// <para type="synopsis">The Remove-IshFolder cmdlet removes the repository folders that are passed through the pipeline or determined via provided parameters Query and Reference folders are not supported.</para> /// <para type="description">The Remove-IshFolder cmdlet removes the repository folders that are passed through the pipeline or determined via provided parameters Query and Reference folders are not supported.</para> /// </summary> /// <example> /// <code> /// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -IshUserName "username" -IshUserPassword "userpassword" /// Remove-IshFolder -FolderId "674580" /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Remove folder with specified Id</para> /// </example> [Cmdlet(VerbsCommon.Remove, "IshFolder", SupportsShouldProcess = true)] public sealed class RemoveIshFolder : FolderCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFoldersGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">Full path to the folder that needs to be removed. Use the IshSession.FolderPathSeparator.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup"), ValidateNotNullOrEmpty] public string FolderPath { get; set; } /// <summary> /// <para type="description">Identifier of the folder to be removed</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup"), ValidateNotNullOrEmpty] public long FolderId { get; set; } /// <summary> /// <para type="description">Array with the folders to remove. This array can be passed through the pipeline or explicitly passed via the parameter.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshFoldersGroup")] [AllowEmptyCollection] public IshFolder[] IshFolder { get; set; } /// <summary> /// <para type="description">Perform recursive retrieval of the provided incoming folder(s)</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderPathGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshFoldersGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "FolderIdGroup")] public SwitchParameter Recurse { get; set; } protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); base.BeginProcessing(); } /// <summary> /// Process the Remove-IshFolder commandlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> protected override void ProcessRecord() { try { // 1. Validating the input // 2. Doing Remove WriteDebug("Removing"); if (IshFolder != null) { long folderId; // 2a. Remove using IshFolder[] pipeline IshFolder[] ishFolders = IshFolder; int current = 0; foreach (IshFolder ishFolder in ishFolders) { // read "folderRef" from the ishFolder object folderId = ishFolder.IshFolderRef; WriteDebug($"folderId[{folderId}] {++current}/{ishFolders.Length}"); if (!Recurse) { if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Delete(folderId); } } else { DeleteRecursive(ishFolder, 0); } } } else if (FolderId != 0) { // 2b. Remove using provided parameters (not piped IshFolder) long folderId = FolderId; WriteDebug($"folderId[{folderId}]"); if (!Recurse) { if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Delete(folderId); } } else { IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(), Enumerations.ActionMode.Read); string xmlIshFolder = IshSession.Folder25.GetMetadataByIshFolderRef(folderId, requestedMetadata.ToXml()); IshFolders ishFolders = new IshFolders(xmlIshFolder, "ishfolder"); DeleteRecursive(ishFolders.Folders[0], 0); } } else if (FolderPath != null) { // 2c. Retrieve using provided parameter FolderPath // Parse FolderPath input parameter: get basefolderName(1st element of an array) string folderPath = FolderPath; string[] folderPathElements = folderPath.Split( new string[] { IshSession.FolderPathSeparator }, StringSplitOptions.RemoveEmptyEntries); string baseFolderLabel = folderPathElements[0]; // remaining folder path elements string[] folderPathTrisoft = new string[folderPathElements.Length - 1]; Array.Copy(folderPathElements, 1, folderPathTrisoft, 0, folderPathElements.Length - 1); WriteDebug($"FolderPath[{folderPath}]"); string xmlIshFolder = IshSession.Folder25.GetMetadata( BaseFolderLabelToEnum(IshSession, baseFolderLabel), folderPathTrisoft, ""); IshFolders ishFolder = new IshFolders(xmlIshFolder, "ishfolder"); long folderId = ishFolder.Folders[0].IshFolderRef; if (!Recurse) { if (ShouldProcess(Convert.ToString(folderId))) { IshSession.Folder25.Delete(folderId); } } else { WriteParentProgress("Recursive folder remove...", _parentCurrent, 1); DeleteRecursive(ishFolder.Folders[0], 0); } } else { WriteDebug("How did you get here? Probably provided too little parameters."); } WriteVerbose("returned object count[0]"); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } /// <summary> /// Recursive delete of folder, expects folders to be empty /// </summary> /// <param name="ishFolder"></param> /// <param name="currentDepth"></param> private void DeleteRecursive(IshFolder ishFolder, int currentDepth) { string folderName = ishFolder.IshFields.GetFieldValue("FNAME", Enumerations.Level.None, Enumerations.ValueType.Value); WriteVerbose(new string('>', currentDepth) + IshSession.FolderPathSeparator + folderName + IshSession.FolderPathSeparator); WriteDebug($"DeleteRecursive IshFolderRef[{ishFolder.IshFolderRef}] folderName[{folderName}] ({currentDepth}/{int.MaxValue})"); string xmlIshFolders = IshSession.Folder25.GetSubFoldersByIshFolderRef(ishFolder.IshFolderRef); // GetSubFolders contains ishfolder for the parent folder + ishfolder inside for the subfolders IshFolders retrievedFolders = new IshFolders(xmlIshFolders, "ishfolder/ishfolder"); if (retrievedFolders.Ids.Length > 0) { IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(), Enumerations.ActionMode.Read); xmlIshFolders = IshSession.Folder25.RetrieveMetadataByIshFolderRefs(retrievedFolders.Ids, requestedMetadata.ToXml()); retrievedFolders = new IshFolders(xmlIshFolders); // sort them ++currentDepth; IshFolder[] sortedFolders = retrievedFolders.SortedFolders; WriteParentProgress("Recursive folder remove...", _parentCurrent, _parentTotal + sortedFolders.Count()); foreach (IshFolder retrievedIshFolder in sortedFolders) { DeleteRecursive(retrievedIshFolder, currentDepth); } } WriteParentProgress("Recursive folder remove...", ++_parentCurrent, _parentTotal); if (ShouldProcess(Convert.ToString(ishFolder.IshFolderRef))) { IshSession.Folder25.Delete(ishFolder.IshFolderRef); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Compute.Tests { public class VMScaleSetRollingUpgradeTests : VMScaleSetTestsBase { /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources with an SLB probe to use as a health probe /// Create VMScaleSet in rolling upgrade mode /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// Upgrade scale set with an extension /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetRollingUpgrade")] public void TestVMScaleSetRollingUpgrade() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.NotNull(getInstanceViewResponse); ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse); var getVMInstanceViewResponse = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName, vmssName, "0"); Assert.NotNull(getVMInstanceViewResponse); Assert.NotNull(getVMInstanceViewResponse.VmHealth); Assert.Equal("HealthState/healthy", getVMInstanceViewResponse.VmHealth.Status.Code); // Update the VMSS by adding an extension ComputeManagementTestUtilities.WaitSeconds(600); var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.NotNull(getInstanceViewResponse); ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse); //m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources with an SLB probe to use as a health probe /// Create VMScaleSet in rolling upgrade mode /// Perform a rolling OS upgrade /// Validate the rolling upgrade completed /// Perform another rolling OS upgrade /// Cancel the rolling upgrade /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetRollingUpgradeAPIs")] public void TestVMScaleSetRollingUpgradeAPIs() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); imageRef.Version = "latest"; var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling; vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy() { EnableAutomaticOSUpgrade = false }; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); ComputeManagementTestUtilities.WaitSeconds(600); var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartOSUpgrade(rgName, vmssName); var rollingUpgradeStatus = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.GetLatest(rgName, vmssName); Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeStatus.Progress.SuccessfulInstanceCount); var upgradeTask = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.BeginStartOSUpgradeWithHttpMessagesAsync(rgName, vmssName); vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); m_CrpClient.VirtualMachineScaleSetRollingUpgrades.Cancel(rgName, vmssName); rollingUpgradeStatus = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.GetLatest(rgName, vmssName); Assert.True(rollingUpgradeStatus.RunningStatus.Code == RollingUpgradeStatusCode.Cancelled); Assert.True(rollingUpgradeStatus.Progress.PendingInstanceCount >= 0); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources with an SLB probe to use as a health probe /// Create VMScaleSet in rolling upgrade mode /// Perform a rolling OS upgrade /// Validate Upgrade History /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetRollingUpgradeHistory")] public void TestVMScaleSetRollingUpgradeHistory() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); imageRef.Version = "latest"; var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); ComputeManagementTestUtilities.WaitSeconds(600); var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartOSUpgrade(rgName, vmssName); var rollingUpgradeHistory = m_CrpClient.VirtualMachineScaleSets.GetOSUpgradeHistory(rgName, vmssName); Assert.NotNull(rollingUpgradeHistory); Assert.True(rollingUpgradeHistory.Count() == 1); Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeHistory.First().Properties.Progress.SuccessfulInstanceCount); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } /// <summary> /// Testing Automatic OS Upgrade Policy /// </summary> [Fact] [Trait("Name", "TestVMScaleSetAutomaticOSUpgradePolicies")] public void TestVMScaleSetAutomaticOSUpgradePolicies() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); imageRef.Version = "latest"; // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy() { DisableAutomaticRollback = false }; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Set Automatic OS Upgrade inputVMScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade = true; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // with automatic OS upgrade policy as null inputVMScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = null; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); Assert.NotNull(getResponse.UpgradePolicy.AutomaticOSUpgradePolicy); Assert.True(getResponse.UpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback == false); Assert.True(getResponse.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade == true); // Toggle Disable Auto Rollback inputVMScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy() { DisableAutomaticRollback = true, EnableAutomaticOSUpgrade = false }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } // Does the following operations: // Create ResourceGroup // Create StorageAccount // Create VMSS in Automatic Mode // Perform an extension rolling upgrade // Delete ResourceGroup [Fact] [Trait("Name", "TestVMScaleSetExtensionUpgradeAPIs")] public void TestVMScaleSetExtensionUpgradeAPIs() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); string rgName = TestUtilities.GenerateName(TestPrefix); string vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); EnsureClientsInitialized(context); // Windows VM image ImageReference imageRef = GetPlatformVMImage(true); imageRef.Version = "latest"; var extension = GetTestVMSSVMExtension(autoUpdateMinorVersion:false); VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { extension, } }; var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); //m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, extensionProfile, (vmScaleSet) => { vmScaleSet.Overprovision = false; vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Automatic; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); //m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartExtensionUpgrade(rgName, vmssName); //var rollingUpgradeStatus = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.GetLatest(rgName, vmssName); //Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeStatus.Progress.SuccessfulInstanceCount); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); // Cleanup resource group and revert default location to the original location m_ResourcesClient.ResourceGroups.Delete(rgName); } } } } }
/* * 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> /// PaymentsConfigurationCheck /// </summary> [DataContract] public partial class PaymentsConfigurationCheck : IEquatable<PaymentsConfigurationCheck>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PaymentsConfigurationCheck" /> class. /// </summary> /// <param name="acceptCheckOrders">Master flag indicating this merchant accepts paper checks.</param> /// <param name="accountingCode">Optional Quickbooks accounting code.</param> /// <param name="checksPayableTo">This is who the customer makes the check out to.</param> /// <param name="depositToAccount">Optional Quickbooks deposit to account.</param> /// <param name="mailToAddress1">MailTo address line 1.</param> /// <param name="mailToAddress2">MailTo address line 2.</param> /// <param name="mailToCity">MailTo city.</param> /// <param name="mailToCountry">MailTo country.</param> /// <param name="mailToName">MailTo name.</param> /// <param name="mailToPostalCode">MailTo postal code.</param> /// <param name="mailToStore">MailTo store.</param> /// <param name="restrictions">restrictions.</param> public PaymentsConfigurationCheck(bool? acceptCheckOrders = default(bool?), string accountingCode = default(string), string checksPayableTo = default(string), string depositToAccount = default(string), string mailToAddress1 = default(string), string mailToAddress2 = default(string), string mailToCity = default(string), string mailToCountry = default(string), string mailToName = default(string), string mailToPostalCode = default(string), string mailToStore = default(string), PaymentsConfigurationRestrictions restrictions = default(PaymentsConfigurationRestrictions)) { this.AcceptCheckOrders = acceptCheckOrders; this.AccountingCode = accountingCode; this.ChecksPayableTo = checksPayableTo; this.DepositToAccount = depositToAccount; this.MailToAddress1 = mailToAddress1; this.MailToAddress2 = mailToAddress2; this.MailToCity = mailToCity; this.MailToCountry = mailToCountry; this.MailToName = mailToName; this.MailToPostalCode = mailToPostalCode; this.MailToStore = mailToStore; this.Restrictions = restrictions; } /// <summary> /// Master flag indicating this merchant accepts paper checks /// </summary> /// <value>Master flag indicating this merchant accepts paper checks</value> [DataMember(Name="accept_check_orders", EmitDefaultValue=false)] public bool? AcceptCheckOrders { get; set; } /// <summary> /// Optional Quickbooks accounting code /// </summary> /// <value>Optional Quickbooks accounting code</value> [DataMember(Name="accounting_code", EmitDefaultValue=false)] public string AccountingCode { get; set; } /// <summary> /// This is who the customer makes the check out to /// </summary> /// <value>This is who the customer makes the check out to</value> [DataMember(Name="checks_payable_to", EmitDefaultValue=false)] public string ChecksPayableTo { get; set; } /// <summary> /// Optional Quickbooks deposit to account /// </summary> /// <value>Optional Quickbooks deposit to account</value> [DataMember(Name="deposit_to_account", EmitDefaultValue=false)] public string DepositToAccount { get; set; } /// <summary> /// MailTo address line 1 /// </summary> /// <value>MailTo address line 1</value> [DataMember(Name="mail_to_address1", EmitDefaultValue=false)] public string MailToAddress1 { get; set; } /// <summary> /// MailTo address line 2 /// </summary> /// <value>MailTo address line 2</value> [DataMember(Name="mail_to_address2", EmitDefaultValue=false)] public string MailToAddress2 { get; set; } /// <summary> /// MailTo city /// </summary> /// <value>MailTo city</value> [DataMember(Name="mail_to_city", EmitDefaultValue=false)] public string MailToCity { get; set; } /// <summary> /// MailTo country /// </summary> /// <value>MailTo country</value> [DataMember(Name="mail_to_country", EmitDefaultValue=false)] public string MailToCountry { get; set; } /// <summary> /// MailTo name /// </summary> /// <value>MailTo name</value> [DataMember(Name="mail_to_name", EmitDefaultValue=false)] public string MailToName { get; set; } /// <summary> /// MailTo postal code /// </summary> /// <value>MailTo postal code</value> [DataMember(Name="mail_to_postal_code", EmitDefaultValue=false)] public string MailToPostalCode { get; set; } /// <summary> /// MailTo store /// </summary> /// <value>MailTo store</value> [DataMember(Name="mail_to_store", EmitDefaultValue=false)] public string MailToStore { get; set; } /// <summary> /// Gets or Sets Restrictions /// </summary> [DataMember(Name="restrictions", EmitDefaultValue=false)] public PaymentsConfigurationRestrictions Restrictions { 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 PaymentsConfigurationCheck {\n"); sb.Append(" AcceptCheckOrders: ").Append(AcceptCheckOrders).Append("\n"); sb.Append(" AccountingCode: ").Append(AccountingCode).Append("\n"); sb.Append(" ChecksPayableTo: ").Append(ChecksPayableTo).Append("\n"); sb.Append(" DepositToAccount: ").Append(DepositToAccount).Append("\n"); sb.Append(" MailToAddress1: ").Append(MailToAddress1).Append("\n"); sb.Append(" MailToAddress2: ").Append(MailToAddress2).Append("\n"); sb.Append(" MailToCity: ").Append(MailToCity).Append("\n"); sb.Append(" MailToCountry: ").Append(MailToCountry).Append("\n"); sb.Append(" MailToName: ").Append(MailToName).Append("\n"); sb.Append(" MailToPostalCode: ").Append(MailToPostalCode).Append("\n"); sb.Append(" MailToStore: ").Append(MailToStore).Append("\n"); sb.Append(" Restrictions: ").Append(Restrictions).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 PaymentsConfigurationCheck); } /// <summary> /// Returns true if PaymentsConfigurationCheck instances are equal /// </summary> /// <param name="input">Instance of PaymentsConfigurationCheck to be compared</param> /// <returns>Boolean</returns> public bool Equals(PaymentsConfigurationCheck input) { if (input == null) return false; return ( this.AcceptCheckOrders == input.AcceptCheckOrders || (this.AcceptCheckOrders != null && this.AcceptCheckOrders.Equals(input.AcceptCheckOrders)) ) && ( this.AccountingCode == input.AccountingCode || (this.AccountingCode != null && this.AccountingCode.Equals(input.AccountingCode)) ) && ( this.ChecksPayableTo == input.ChecksPayableTo || (this.ChecksPayableTo != null && this.ChecksPayableTo.Equals(input.ChecksPayableTo)) ) && ( this.DepositToAccount == input.DepositToAccount || (this.DepositToAccount != null && this.DepositToAccount.Equals(input.DepositToAccount)) ) && ( this.MailToAddress1 == input.MailToAddress1 || (this.MailToAddress1 != null && this.MailToAddress1.Equals(input.MailToAddress1)) ) && ( this.MailToAddress2 == input.MailToAddress2 || (this.MailToAddress2 != null && this.MailToAddress2.Equals(input.MailToAddress2)) ) && ( this.MailToCity == input.MailToCity || (this.MailToCity != null && this.MailToCity.Equals(input.MailToCity)) ) && ( this.MailToCountry == input.MailToCountry || (this.MailToCountry != null && this.MailToCountry.Equals(input.MailToCountry)) ) && ( this.MailToName == input.MailToName || (this.MailToName != null && this.MailToName.Equals(input.MailToName)) ) && ( this.MailToPostalCode == input.MailToPostalCode || (this.MailToPostalCode != null && this.MailToPostalCode.Equals(input.MailToPostalCode)) ) && ( this.MailToStore == input.MailToStore || (this.MailToStore != null && this.MailToStore.Equals(input.MailToStore)) ) && ( this.Restrictions == input.Restrictions || (this.Restrictions != null && this.Restrictions.Equals(input.Restrictions)) ); } /// <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.AcceptCheckOrders != null) hashCode = hashCode * 59 + this.AcceptCheckOrders.GetHashCode(); if (this.AccountingCode != null) hashCode = hashCode * 59 + this.AccountingCode.GetHashCode(); if (this.ChecksPayableTo != null) hashCode = hashCode * 59 + this.ChecksPayableTo.GetHashCode(); if (this.DepositToAccount != null) hashCode = hashCode * 59 + this.DepositToAccount.GetHashCode(); if (this.MailToAddress1 != null) hashCode = hashCode * 59 + this.MailToAddress1.GetHashCode(); if (this.MailToAddress2 != null) hashCode = hashCode * 59 + this.MailToAddress2.GetHashCode(); if (this.MailToCity != null) hashCode = hashCode * 59 + this.MailToCity.GetHashCode(); if (this.MailToCountry != null) hashCode = hashCode * 59 + this.MailToCountry.GetHashCode(); if (this.MailToName != null) hashCode = hashCode * 59 + this.MailToName.GetHashCode(); if (this.MailToPostalCode != null) hashCode = hashCode * 59 + this.MailToPostalCode.GetHashCode(); if (this.MailToStore != null) hashCode = hashCode * 59 + this.MailToStore.GetHashCode(); if (this.Restrictions != null) hashCode = hashCode * 59 + this.Restrictions.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; } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.EqualityComparer.Equals(T,T) /// </summary> public class GenericEqualityComparerEquals { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main(string[] args) { GenericEqualityComparerEquals testObj = new GenericEqualityComparerEquals(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.EqualityComparer.Equals(T,T)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Verify EqualityCompare.Equals(T,T) when Type is int..."; const string c_TEST_ID = "P001"; MyEqualityComparer<int> myEC = new MyEqualityComparer<int>(); int x = TestLibrary.Generator.GetInt32(-55); int y = x; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!myEC.Equals(x, y)) { string errorDesc = "result should be true when two int both is 1"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Verify the EqualityComparer.Equals(T,T) when T is reference type... "; const string c_TEST_ID = "P002"; String str1 = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH); String str2 = str1; MyEqualityComparer<String> myEC = new MyEqualityComparer<String>(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!myEC.Equals(str1, str2)) { string errorDesc = "result should be true when two String object is the same reference"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Verify EqualityCompare.Equals(T,T) when Type is user-defined class... "; const string c_TEST_ID = "P003"; MyEqualityComparer<MyClass> myEC = new MyEqualityComparer<MyClass>(); MyClass myClass1 = new MyClass(); MyClass myClass2 = myClass1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!myEC.Equals(myClass1, myClass2)) { string errorDesc = "result should be true when two MyClass object is the same reference"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Verify EqualityCompare.Equals(T,T) when two parameters are null reference... "; const string c_TEST_ID = "P004"; MyEqualityComparer<String> myEC = new MyEqualityComparer<String>(); String str1 = null; String str2 = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!myEC.Equals(str2, str1)) { string errorDesc = "result should be true when two DateTime object is null reference"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Verify EqualityCompare.Equals(T,T) when a parameters is a null reference and another is not... "; const string c_TEST_ID = "P005"; MyEqualityComparer<String> myEC = new MyEqualityComparer<String>(); String str1 = null; String str2 = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (myEC.Equals(str1, str2)) { string errorDesc = "result should be false when a String is null and another is not"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyEqualityComparer<T> : EqualityComparer<T> { public override bool Equals(T x, T y) { if (x != null) { if (y != null) return x.Equals(y); return false; } if (y != null) return false; return true; } public override int GetHashCode(T obj) { throw new Exception("The method or operation is not implemented."); } } public class MyClass { } #endregion }
using System; using System.Collections.Generic; using MbUnit.Framework; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Query.Generator.Tests.WithEagerFetch; using NHibernate.SqlCommand; using NHibernate.Transform; using Query; namespace NHibernate.Query.Generator.Tests { [TestFixture] public class TestApplicationRepositoryFind { private Configuration cfg; private ISessionFactory sf; private ISession session; private Application app1; private Application app2; private Application app3; private Operation app3op1 = new Operation(); private Operation app3op2 = new Operation(); [TestFixtureSetUp] public void TestFixtureSetup() { cfg = new Configuration() .SetProperty("show_sql", "true") .SetProperty("dialect", "NHibernate.Dialect.SQLiteDialect") .SetProperty("connection.driver_class", "NHibernate.Driver.SQLite20Driver") .SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider") .SetProperty("connection.connection_string", "Data Source=test.db3;Version=3;New=True;") // .SetProperty("hibernate.connection.connection_string", "Data Source=:memory:;Version=3;New=True;") .SetProperty("connection.release_mode", "on_close") .SetProperty("max_fetch_deptch", "2") .AddClass(typeof(WithEagerFetch.Application)) .AddClass(typeof(WithEagerFetch.Action)); sf = cfg.BuildSessionFactory(); } [SetUp] public void SetUpEachTest() { new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Execute(false, true, false, false); app1 = new Application(); app1.Name = "Mega App"; app1.Description = "Fabulous"; app1.Obsolete = false; app2 = new Application(); app2.Name = "Super Mega App"; app2.Description = "Fabulous"; app2.Obsolete = false; app3 = new Application(); app3.Name = "Ultra Super Mega App"; app3.Description = "Amazing"; app3.Obsolete = false; app3op1.Application = app3; app3op1.Name = "EatCheese"; app3op1.Description = "Allows the user eat cheese"; app3.Operations.Add(app3op1); app3op2.Application = app3; app3op2.Name = "MakeTea"; app3op2.Description = "Allows the user make tea"; app3.Operations.Add(app3op2); session = sf.OpenSession(); ITransaction tx = session.BeginTransaction(); session.Save(app1); session.Save(app2); session.Save(app3); session.Save(app3op1); session.Save(app3op2); UserSetting app3us1 = new UserSetting(app3, "country", "usa"); UserSetting app3us2 = new UserSetting(app3, "lang", "english"); GlobalSetting app3gs1 = new GlobalSetting(app3, "title", "Ultra Super Mega App"); GlobalSetting app3gs2 = new GlobalSetting(app3, "security", "active directory"); app3.Settings.UserSettings.Add(app3us1); app3.Settings.UserSettings.Add(app3us2); app3.Settings.GlobalSettings.Add(app3gs1); app3.Settings.GlobalSettings.Add(app3gs2); session.Save(app3us1); session.Save(app3us2); session.Save(app3gs1); session.Save(app3gs2); session.Update(app3); tx.Commit(); session.Close(); } [TearDown] public void TearDownEachTest() { if (session.IsOpen) session.Close(); } [Test] public void ShouldFetchJoinWithoutCriteria() { session = sf.OpenSession(); DetachedCriteria where = Where.Application.Operations.With(JoinType.LeftOuterJoin, FetchMode.Join); IList<Application> applications = where.GetExecutableCriteria(session).SetResultTransformer(new DistinctRootEntityResultTransformer()). List<Application>(); session.Close(); Assert.IsNotNull(applications); Assert.AreEqual(3, applications.Count); Assert.IsTrue(applications.Contains(app1)); Assert.IsTrue(applications.Contains(app2)); Assert.IsTrue(applications.Contains(app3)); Assert.AreEqual(2, applications[2].Operations.Count); Assert.IsTrue(applications[2].Operations.Contains(app3op1)); Assert.IsTrue(applications[2].Operations.Contains(app3op2)); } [Test] [Ignore("NHibernate's behaviro was changed? Need to check why this is failing")] public void ShouldFetchJoinWithCriteria() { session = sf.OpenSession(); DetachedCriteria where = Where.Application.Operations .With(JoinType.LeftOuterJoin, FetchMode.Join).Name == "EatCheese"; IList<Application> applications = where.GetExecutableCriteria(session).SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Application>(); session.Close(); Assert.IsNotNull(applications); Assert.AreEqual(1, applications.Count); Assert.AreEqual(app3, applications[0]); Assert.AreEqual(1, applications[0].Operations.Count); Assert.IsTrue(applications[0].Operations.Contains(app3op1)); } [Test] [Ignore("NHibernate's behaviro was changed? Need to check why this is failing")] public void ShouldFetchJoinWithCriteriaOnRootAndJoin() { session = sf.OpenSession(); DetachedCriteria where = Where.Application.Id == app3.Id & Where.Application.Operations .With(JoinType.LeftOuterJoin, FetchMode.Join).Name == "EatCheese"; IList<Application> applications = where.GetExecutableCriteria(session).SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Application>(); session.Close(); Assert.IsNotNull(applications); Assert.AreEqual(1, applications.Count); Assert.AreEqual(app3, applications[0]); Assert.AreEqual(1, applications[0].Operations.Count); Assert.IsTrue(applications[0].Operations.Contains(app3op1)); } [Test] public void ShouldFetchJoinComponentCollectionsOnRootAndJoin() { session = sf.OpenSession(); DetachedCriteria where = Where.Application.Id == app3.Id && Where.Application.Settings.GlobalSettings.With(JoinType.LeftOuterJoin, FetchMode.Join); IList<Application> applications = where.GetExecutableCriteria(session).SetResultTransformer(new DistinctRootEntityResultTransformer()) .List<Application>(); session.Close(); Assert.IsNotNull(applications); Assert.AreEqual(1, applications.Count); Assert.AreEqual(app3, applications[0]); Assert.AreEqual(2, applications[0].Settings.GlobalSettings.Count); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Threading; using System.Web; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using umbraco.BusinessLogic; using System.Collections.Generic; using umbraco.BusinessLogic.Utils; using umbraco.businesslogic; using umbraco.cms.businesslogic.cache; using System.Web.Caching; using Umbraco.Core.IO; using umbraco.interfaces; namespace umbraco.presentation { /// <summary> /// Summary description for requestModule. /// </summary> [Obsolete("This class is not used anymore and will be removed from the codebase in future versions.")] public class requestModule : IHttpModule { protected static Timer publishingTimer; protected static Timer pingTimer; private HttpApplication mApp; private IContainer components = null; private readonly IList<IApplicationStartupHandler> startupHandlers = new List<IApplicationStartupHandler>(); /// <summary>True if the module is currently handling an error.</summary> private static object handlingError = false; /// <summary>List of errors that occurred since the last error was being handled.</summary> private List<Exception> unhandledErrors = new List<Exception>(); public const string ORIGINAL_URL_CXT_KEY = "umbOriginalUrl"; private static string LOG_SCRUBBER_TASK_NAME = "ScrubLogs"; private static CacheItemRemovedCallback OnCacheRemove = null; protected void ApplicationStart(HttpApplication HttpApp) { //starting the application. Application doesn't support HttpContext in integrated mode (standard mode on IIS7) //So everything is moved to beginRequest. } protected void Application_PostResolveRequestCache(object sender, EventArgs e) { // process rewrite here so forms authentication can Authorize based on url before the original url is discarded this.UmbracoRewrite(sender, e); } protected void Application_AuthorizeRequest(object sender, EventArgs e) { // nothing needs to be done here } protected void Application_PreRequestHandlerExecute(object sender, EventArgs e) { HttpContext context = mApp.Context; //httpContext.RewritePath( (string) httpContext.Items[ORIGINAL_URL_CXT_KEY] + "?" + httpContext.Request.QueryString ); } /// <summary> /// Handles the BeginRequest event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Application_BeginRequest(Object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; //first time init, starts timers, and sets httpContext InitializeApplication(app); // grab the original url before anything modifies it HttpContext httpContext = mApp.Context; httpContext.Items[ORIGINAL_URL_CXT_KEY] = rewrite404Url(httpContext.Request.Url.AbsolutePath, httpContext.Request.Url.Query, false); // create the Umbraco context UmbracoContext.Current = new UmbracoContext(httpContext); // rewrite will happen after authorization } protected string rewrite404Url(string url, string querystring, bool returnQuery) { // adding endswith and contains checks to ensure support for custom 404 messages (only 404 parse directory and aspx requests) if (querystring.StartsWith("?404") && (!querystring.Contains(".") || querystring.EndsWith(".aspx") || querystring.Contains(".aspx&"))) { Uri u = new Uri(querystring.Substring(5, querystring.Length - 5)); string path = u.AbsolutePath; if (returnQuery) { return u.Query; } else { return path; } } if (returnQuery) { return querystring; } else { return url; } } /// <summary> /// Performs path rewriting. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void UmbracoRewrite(Object sender, EventArgs e) { HttpContext context = mApp.Context; string path = rewrite404Url(context.Request.Path.ToLower(), context.Request.Url.Query, false); string query = String.Empty; if (GlobalSettings.UseDirectoryUrls) { // zb-00017 #29930 : do not change url casing when rewriting string requestPath = context.Request.Path; // not lowercased int asmxPos = path.IndexOf(".asmx/"); if (asmxPos >= 0) context.RewritePath(path.Substring(0, asmxPos + 5), requestPath.Substring(asmxPos + 5), context.Request.QueryString.ToString()); } if (path.IndexOf(".aspx") > -1 || path.IndexOf('.') == -1) { // validate configuration if (mApp.Application["umbracoNeedConfiguration"] == null) mApp.Application["umbracoNeedConfiguration"] = !GlobalSettings.Configured; if (!GlobalSettings.IsReservedPathOrUrl(path)) { // redirect if Umbraco needs configuration Nullable<bool> needsConfiguration = (Nullable<bool>)mApp.Application["umbracoNeedConfiguration"]; if (needsConfiguration.HasValue && needsConfiguration.Value) { string url = SystemDirectories.Install; string meh = IOHelper.ResolveUrl(url); string installUrl = string.Format("{0}/default.aspx?redir=true&url={1}", IOHelper.ResolveUrl( SystemDirectories.Install ), context.Request.Path.ToLower()); context.Response.Redirect(installUrl, true); } // show splash? else if (UmbracoSettings.EnableSplashWhileLoading && content.Instance.isInitializing) context.RewritePath(string.Format("{0}/splashes/booting.aspx", SystemDirectories.Config)); // rewrite page path else { string receivedQuery = rewrite404Url(context.Request.Path.ToLower(), context.Request.Url.Query, true); if (receivedQuery.Length > 0) { // Clean umbPage from querystring, caused by .NET 2.0 default Auth Controls if (receivedQuery.IndexOf("umbPage") > 0) { int ampPos = receivedQuery.IndexOf('&'); // query contains no ampersand? if (ampPos < 0) { // no ampersand means no original query string query = String.Empty; // ampersand would occur past then end the of received query ampPos = receivedQuery.Length; } else { // original query string past ampersand query = receivedQuery.Substring(ampPos + 1, receivedQuery.Length - ampPos - 1); } // get umbPage out of query string (9 = "&umbPage".Length() + 1) path = receivedQuery.Substring(9, ampPos - 9); //this will fail if there are < 9 characters before the &umbPage query string } else { // strip off question mark query = receivedQuery.Substring(1); } } // Add questionmark to query string if it's not empty if (!String.IsNullOrEmpty(query)) query = "?" + query; // save original URL context.Items["UmbPage"] = path; context.Items["VirtualUrl"] = String.Format("{0}{1}", path, query); // rewrite to the new URL context.RewritePath(string.Format("{0}/default.aspx{2}", SystemDirectories.Root, path, query)); } } } } /// <summary> /// Handles the Error event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Application_Error(Object sender, EventArgs e) { // return immediately if an error is already been handled, to avoid infinite recursion if ((bool)handlingError) { lock (unhandledErrors) { unhandledErrors.Add(mApp.Server.GetLastError()); } return; } // make sure only one thread at a time can handle an error lock (handlingError) { Debug.Assert(!(bool)handlingError, "Two errors are being handled at the same time."); handlingError = true; // make sure handlingError always gets set to false try { if (GlobalSettings.Configured) { // log the error // zb-00017 #29930 : could have been cleared, though: take care, .GetLastError() may return null Exception ex = mApp.Server.GetLastError(); if (ex != null) ex = ex.InnerException; string error; if (mApp.Context.Request != null) error = string.Format("At {0} (Referred by: {1}): {2}", mApp.Context.Request.RawUrl, mApp.Context.Request.UrlReferrer, ex); else error = "No Context available -> " + ex; // Hide error if getting the user throws an error (e.g. corrupt / blank db) User staticUser = null; try { User.GetCurrent(); } catch { } LogHelper.Debug<requestModule>(error); Trace.TraceError(error); lock (unhandledErrors) { if (unhandledErrors.Count > 0) Trace.TraceError("New errors occurred while an error was being handled. The error handler Application_Error possibly raised another error, but was protected against an infinite loop."); foreach (Exception unhandledError in unhandledErrors) Trace.TraceError(unhandledError.StackTrace); } } } finally { // clear unhandled errors lock (unhandledErrors) { unhandledErrors.Clear(); } // flag we're done with the error handling handlingError = false; } } } #region IHttpModule Members ///<summary> ///Initializes a module and prepares it to handle requests. ///</summary> /// ///<param name="httpContext">An <see cref="T:System.Web.HttpApplication"></see> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param> public void Init(HttpApplication context) { InitializeComponent(); ApplicationStart(context); context.BeginRequest += new EventHandler(Application_BeginRequest); context.AuthorizeRequest += new EventHandler(Application_AuthorizeRequest); // Alex Norcliffe - 2010 02 - Changed this behaviour as it disables OutputCaching due to Rewrite happening too early in the chain // context.PostAuthorizeRequest += new EventHandler(Application_PostAuthorizeRequest); context.PostResolveRequestCache += new EventHandler(Application_PostResolveRequestCache); context.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandlerExecute); // Alex Norcliffe - 2010 06 - Added a check at the end of the page lifecycle to see if we should persist Xml cache to disk // (a replacement for all those parallel Async methods launching ThreadPool threads) context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute); context.Error += new EventHandler(Application_Error); mApp = context; } void context_PostRequestHandlerExecute(object sender, EventArgs e) { if (content.Instance.IsXmlQueuedForPersistenceToFile) { content.Instance.PersistXmlToFile(); } } private void InitializeComponent() { components = new Container(); } ///<summary> ///Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"></see>. ///</summary> /// public void Dispose() { } //this makes sure that times and other stuff is started on the first request, instead of depending on // application_start, which was inteded for being a httpContext-agnostic state. private static bool s_InitializedAlready = false; private static Object s_lock = new Object(); // Initialize only on the first request public void InitializeApplication(HttpApplication HttpApp) { if (s_InitializedAlready) return; lock (s_lock) { if (s_InitializedAlready) return; // Perform first-request initialization here ... try { LogHelper.Info<requestModule>(string.Format("Application started at {0}", DateTime.Now)); if (UmbracoSettings.AutoCleanLogs) { AddTask(LOG_SCRUBBER_TASK_NAME, GetLogScrubbingInterval()); } } catch { } // Trigger startup handlers ApplicationStartupHandler.RegisterHandlers(); // Check for configured key, checking for currentversion to ensure that a request with // no httpcontext don't set the whole app in configure mode if (UmbracoVersion.Current != null && !GlobalSettings.Configured) { HttpApp.Application["umbracoNeedConfiguration"] = true; } /* This section is needed on start-up because timer objects * might initialize before these are initialized without a traditional * request, and therefore lacks information on application paths */ /* Initialize SECTION END */ // add current default url HttpApp.Application["umbracoUrl"] = string.Format("{0}:{1}{2}", HttpApp.Context.Request.ServerVariables["SERVER_NAME"], HttpApp.Context.Request.ServerVariables["SERVER_PORT"], IOHelper.ResolveUrl( SystemDirectories.Umbraco )); // Start ping / keepalive timer pingTimer = new Timer(new TimerCallback(keepAliveService.PingUmbraco), HttpApp.Context, 60000, 300000); // Start publishingservice publishingTimer = new Timer(new TimerCallback(publishingService.CheckPublishing), HttpApp.Context, 30000, 60000); //Find Applications and event handlers and hook-up the events //BusinessLogic.Application.RegisterIApplications(); //define the base settings for the dependency loader to use the global path settings //if (!CompositeDependencyHandler.HandlerFileName.StartsWith(GlobalSettings_Path)) // CompositeDependencyHandler.HandlerFileName = GlobalSettings_Path + "/" + CompositeDependencyHandler.HandlerFileName; // Backwards compatibility - set the path and URL type for ClientDependency 1.5.1 [LK] ClientDependency.Core.CompositeFiles.Providers.XmlFileMapper.FileMapVirtualFolder = "~/App_Data/TEMP/ClientDependency"; ClientDependency.Core.CompositeFiles.Providers.BaseCompositeFileProcessingProvider.UrlTypeDefault = ClientDependency.Core.CompositeFiles.Providers.CompositeUrlType.Base64QueryStrings; // init done... s_InitializedAlready = true; } } #endregion #region Inteval tasks private static int GetLogScrubbingInterval() { int interval = 24 * 60 * 60; //24 hours try { if (UmbracoSettings.CleaningMiliseconds > -1) interval = UmbracoSettings.CleaningMiliseconds; } catch (Exception) { LogHelper.Info<requestModule>("Unable to locate a log scrubbing interval. Defaulting to 24 hours"); } return interval; } private static int GetLogScrubbingMaximumAge() { int maximumAge = 24 * 60 * 60; try { if (UmbracoSettings.MaxLogAge > -1) maximumAge = UmbracoSettings.MaxLogAge; } catch (Exception) { LogHelper.Info<requestModule>("Unable to locate a log scrubbing maximum age. Defaulting to 24 hours"); } return maximumAge; } private void AddTask(string name, int seconds) { OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved); HttpRuntime.Cache.Insert(name, seconds, null, DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove); } public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) { if (k.Equals(LOG_SCRUBBER_TASK_NAME)) { ScrubLogs(); } AddTask(k, Convert.ToInt32(v)); } private static void ScrubLogs() { Log.CleanLogs(GetLogScrubbingMaximumAge()); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { internal abstract partial class HttpHeaders : IHeaderDictionary { protected long _bits; protected long? _contentLength; protected bool _isReadOnly; protected Dictionary<string, StringValues>? MaybeUnknown; protected Dictionary<string, StringValues> Unknown => MaybeUnknown ??= new Dictionary<string, StringValues>(StringComparer.OrdinalIgnoreCase); public long? ContentLength { get { return _contentLength; } set { if (_isReadOnly) { ThrowHeadersReadOnlyException(); } if (value.HasValue && value.Value < 0) { ThrowInvalidContentLengthException(value.Value); } _contentLength = value; } } public abstract StringValues HeaderConnection { get; set; } StringValues IHeaderDictionary.this[string key] { get { TryGetValueFast(key, out var value); return value; } set { if (_isReadOnly) { ThrowHeadersReadOnlyException(); } if (string.IsNullOrEmpty(key)) { ThrowInvalidEmptyHeaderName(); } if (value.Count == 0) { RemoveFast(key); } else { SetValueFast(key, value); } } } StringValues IDictionary<string, StringValues>.this[string key] { get { // Unlike the IHeaderDictionary version, this getter will throw a KeyNotFoundException. if (!TryGetValueFast(key, out var value)) { ThrowKeyNotFoundException(); } return value; } set { ((IHeaderDictionary)this)[key] = value; } } protected static void ThrowHeadersReadOnlyException() { throw new InvalidOperationException(CoreStrings.HeadersAreReadOnly); } protected static void ThrowArgumentException() { throw new ArgumentException(); } protected static void ThrowKeyNotFoundException() { throw new KeyNotFoundException(); } protected static void ThrowDuplicateKeyException() { throw new ArgumentException(CoreStrings.KeyAlreadyExists); } public int Count => GetCountFast(); bool ICollection<KeyValuePair<string, StringValues>>.IsReadOnly => _isReadOnly; ICollection<string> IDictionary<string, StringValues>.Keys => ((IDictionary<string, StringValues>)this).Select(pair => pair.Key).ToList(); ICollection<StringValues> IDictionary<string, StringValues>.Values => ((IDictionary<string, StringValues>)this).Select(pair => pair.Value).ToList(); public void SetReadOnly() { _isReadOnly = true; } // Inline to allow ClearFast to devirtualize in caller [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { _isReadOnly = false; ClearFast(); } protected static string GetInternedHeaderName(string name) { // Some headers can be very long lived; for example those on a WebSocket connection // so we exchange these for the preallocated strings predefined in HeaderNames if (_internedHeaderNames.TryGetValue(name, out var internedName)) { return internedName; } return name; } [MethodImpl(MethodImplOptions.NoInlining)] protected static StringValues AppendValue(StringValues existing, string append) { return StringValues.Concat(existing, append); } [MethodImpl(MethodImplOptions.NoInlining)] protected bool TryGetUnknown(string key, ref StringValues value) => MaybeUnknown?.TryGetValue(key, out value) ?? false; [MethodImpl(MethodImplOptions.NoInlining)] protected bool RemoveUnknown(string key) => MaybeUnknown?.Remove(key) ?? false; protected virtual int GetCountFast() { throw new NotImplementedException(); } protected virtual bool TryGetValueFast(string key, out StringValues value) { throw new NotImplementedException(); } protected virtual void SetValueFast(string key, StringValues value) { throw new NotImplementedException(); } protected virtual bool AddValueFast(string key, StringValues value) { throw new NotImplementedException(); } protected virtual bool RemoveFast(string key) { throw new NotImplementedException(); } protected virtual void ClearFast() { throw new NotImplementedException(); } protected virtual bool CopyToFast(KeyValuePair<string, StringValues>[] array, int arrayIndex) { throw new NotImplementedException(); } protected virtual IEnumerator<KeyValuePair<string, StringValues>> GetEnumeratorFast() { throw new NotImplementedException(); } void ICollection<KeyValuePair<string, StringValues>>.Add(KeyValuePair<string, StringValues> item) { ((IDictionary<string, StringValues>)this).Add(item.Key, item.Value); } void IDictionary<string, StringValues>.Add(string key, StringValues value) { if (_isReadOnly) { ThrowHeadersReadOnlyException(); } if (string.IsNullOrEmpty(key)) { ThrowInvalidEmptyHeaderName(); } if (value.Count > 0 && !AddValueFast(key, value)) { ThrowDuplicateKeyException(); } } void ICollection<KeyValuePair<string, StringValues>>.Clear() { if (_isReadOnly) { ThrowHeadersReadOnlyException(); } ClearFast(); } bool ICollection<KeyValuePair<string, StringValues>>.Contains(KeyValuePair<string, StringValues> item) { return TryGetValueFast(item.Key, out var value) && value.Equals(item.Value); } bool IDictionary<string, StringValues>.ContainsKey(string key) { return TryGetValueFast(key, out _); } void ICollection<KeyValuePair<string, StringValues>>.CopyTo(KeyValuePair<string, StringValues>[] array, int arrayIndex) { if (!CopyToFast(array, arrayIndex)) { ThrowArgumentException(); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorFast(); } IEnumerator<KeyValuePair<string, StringValues>> IEnumerable<KeyValuePair<string, StringValues>>.GetEnumerator() { return GetEnumeratorFast(); } bool ICollection<KeyValuePair<string, StringValues>>.Remove(KeyValuePair<string, StringValues> item) { return TryGetValueFast(item.Key, out var value) && value.Equals(item.Value) && RemoveFast(item.Key); } bool IDictionary<string, StringValues>.Remove(string key) { if (_isReadOnly) { ThrowHeadersReadOnlyException(); } return RemoveFast(key); } bool IDictionary<string, StringValues>.TryGetValue(string key, out StringValues value) { return TryGetValueFast(key, out value); } public static void ValidateHeaderValueCharacters(string headerName, StringValues headerValues, Func<string, Encoding?> encodingSelector) { var requireAscii = ReferenceEquals(encodingSelector, KestrelServerOptions.DefaultHeaderEncodingSelector) || encodingSelector(headerName) == null; var count = headerValues.Count; for (var i = 0; i < count; i++) { ValidateHeaderValueCharacters(headerValues[i] ?? string.Empty, requireAscii); } } public static void ValidateHeaderValueCharacters(string headerCharacters, bool requireAscii) { if (headerCharacters != null) { var invalid = requireAscii ? HttpCharacters.IndexOfInvalidFieldValueChar(headerCharacters) : HttpCharacters.IndexOfInvalidFieldValueCharExtended(headerCharacters); if (invalid >= 0) { ThrowInvalidHeaderCharacter(headerCharacters[invalid]); } } } public static void ValidateHeaderNameCharacters(string headerCharacters) { var invalid = HttpCharacters.IndexOfInvalidTokenChar(headerCharacters); if (invalid >= 0) { ThrowInvalidHeaderCharacter(headerCharacters[invalid]); } } #pragma warning disable CA1802 // Use literals where appropriate. Using a static field for reference equality private static readonly string KeepAlive = "keep-alive"; #pragma warning restore CA1802 private static readonly StringValues ConnectionValueKeepAlive = KeepAlive; private static readonly StringValues ConnectionValueClose = "close"; private static readonly StringValues ConnectionValueUpgrade = HeaderNames.Upgrade; public static ConnectionOptions ParseConnection(HttpHeaders headers) { // Keep-alive const ulong lowerCaseKeep = 0x0000_0020_0020_0020; // Don't lowercase hyphen const ulong keepAliveStart = 0x002d_0070_0065_0065; // 4 chars "eep-" const ulong keepAliveMiddle = 0x0076_0069_006c_0061; // 4 chars "aliv" const ushort keepAliveEnd = 0x0065; // 1 char "e" // Upgrade const ulong upgradeStart = 0x0061_0072_0067_0070; // 4 chars "pgra" const uint upgradeEnd = 0x0065_0064; // 2 chars "de" // Close const ulong closeEnd = 0x0065_0073_006f_006c; // 4 chars "lose" var connection = headers.HeaderConnection; var connectionCount = connection.Count; if (connectionCount == 0) { return ConnectionOptions.None; } var connectionOptions = ConnectionOptions.None; if (connectionCount == 1) { // "keep-alive" is the only value that will be repeated over // many requests on the same connection; on the first request // we will have switched it for the readonly static value; // so we can ptentially short-circuit parsing and use ReferenceEquals. if (ReferenceEquals(connection.ToString(), KeepAlive)) { return ConnectionOptions.KeepAlive; } } for (var i = 0; i < connectionCount; i++) { var value = connection[i].AsSpan(); while (value.Length > 0) { int offset; char c = '\0'; // Skip any spaces and empty values. for (offset = 0; offset < value.Length; offset++) { c = value[offset]; if (c != ' ' && c != ',') { break; } } // Skip last read char. offset++; if ((uint)offset > (uint)value.Length) { // Consumed enitre string, move to next. break; } // Remove leading spaces or empty values. value = value.Slice(offset); c = ToLowerCase(c); var byteValue = MemoryMarshal.AsBytes(value); offset = 0; var potentialConnectionOptions = ConnectionOptions.None; if (c == 'k' && byteValue.Length >= (2 * sizeof(ulong) + sizeof(ushort))) { if (ReadLowerCaseUInt64(byteValue, lowerCaseKeep) == keepAliveStart) { offset += sizeof(ulong) / 2; byteValue = byteValue.Slice(sizeof(ulong)); if (ReadLowerCaseUInt64(byteValue) == keepAliveMiddle) { offset += sizeof(ulong) / 2; byteValue = byteValue.Slice(sizeof(ulong)); if (ReadLowerCaseUInt16(byteValue) == keepAliveEnd) { offset += sizeof(ushort) / 2; potentialConnectionOptions = ConnectionOptions.KeepAlive; } } } } else if (c == 'u' && byteValue.Length >= (sizeof(ulong) + sizeof(uint))) { if (ReadLowerCaseUInt64(byteValue) == upgradeStart) { offset += sizeof(ulong) / 2; byteValue = byteValue.Slice(sizeof(ulong)); if (ReadLowerCaseUInt32(byteValue) == upgradeEnd) { offset += sizeof(uint) / 2; potentialConnectionOptions = ConnectionOptions.Upgrade; } } } else if (c == 'c' && byteValue.Length >= sizeof(ulong)) { if (ReadLowerCaseUInt64(byteValue) == closeEnd) { offset += sizeof(ulong) / 2; potentialConnectionOptions = ConnectionOptions.Close; } } if ((uint)offset >= (uint)value.Length) { // Consumed enitre string, move to next string. connectionOptions |= potentialConnectionOptions; break; } else { value = value.Slice(offset); } for (offset = 0; offset < value.Length; offset++) { c = value[offset]; if (c == ',') { break; } else if (c != ' ') { // Value contains extra chars; this is not the matched one. potentialConnectionOptions = ConnectionOptions.None; } } if ((uint)offset >= (uint)value.Length) { // Consumed enitre string, move to next string. connectionOptions |= potentialConnectionOptions; break; } else if (c == ',') { // Consumed value corretly. connectionOptions |= potentialConnectionOptions; // Skip comma. offset++; if ((uint)offset >= (uint)value.Length) { // Consumed enitre string, move to next string. break; } else { // Move to next value. value = value.Slice(offset); } } } } // If Connection is a single value, switch it for the interned value // in case the connection is long lived if (connectionOptions == ConnectionOptions.Upgrade) { headers.HeaderConnection = ConnectionValueUpgrade; } else if (connectionOptions == ConnectionOptions.KeepAlive) { headers.HeaderConnection = ConnectionValueKeepAlive; } else if (connectionOptions == ConnectionOptions.Close) { headers.HeaderConnection = ConnectionValueClose; } return connectionOptions; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong ReadLowerCaseUInt64(ReadOnlySpan<byte> value, ulong lowerCaseMask = 0x0020_0020_0020_0020) { ulong result = MemoryMarshal.Read<ulong>(value); if (!BitConverter.IsLittleEndian) { result = (result & 0xffff_0000_0000_0000) >> 48 | (result & 0x0000_ffff_0000_0000) >> 16 | (result & 0x0000_0000_ffff_0000) << 16 | (result & 0x0000_0000_0000_ffff) << 48; } return result | lowerCaseMask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ReadLowerCaseUInt32(ReadOnlySpan<byte> value) { uint result = MemoryMarshal.Read<uint>(value); if (!BitConverter.IsLittleEndian) { result = (result & 0xffff_0000) >> 16 | (result & 0x0000_ffff) << 16; } return result | 0x0020_0020; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ushort ReadLowerCaseUInt16(ReadOnlySpan<byte> value) => (ushort)(MemoryMarshal.Read<ushort>(value) | 0x0020); private static char ToLowerCase(char value) => (char)(value | (char)0x0020); public static TransferCoding GetFinalTransferCoding(StringValues transferEncoding) { const ulong chunkedStart = 0x006b_006e_0075_0068; // 4 chars "hunk" const uint chunkedEnd = 0x0064_0065; // 2 chars "ed" var transferEncodingOptions = TransferCoding.None; var transferEncodingCount = transferEncoding.Count; for (var i = 0; i < transferEncodingCount; i++) { var values = transferEncoding[i].AsSpan(); while (values.Length > 0) { int offset; char c = '\0'; // Skip any spaces and empty values. for (offset = 0; offset < values.Length; offset++) { c = values[offset]; if (c != ' ' && c != ',') { break; } } // Skip last read char. offset++; if ((uint)offset > (uint)values.Length) { // Consumed entire string, move to next. break; } // Remove leading spaces or empty values. values = values.Slice(offset); offset = 0; var byteValue = MemoryMarshal.AsBytes(values); if (ToLowerCase(c) == 'c' && TryReadLowerCaseUInt64(byteValue, out var result64) && result64 == chunkedStart) { offset += sizeof(ulong) / 2; byteValue = byteValue.Slice(sizeof(ulong)); if (TryReadLowerCaseUInt32(byteValue, out var result32) && result32 == chunkedEnd) { offset += sizeof(uint) / 2; transferEncodingOptions = TransferCoding.Chunked; } } if ((uint)offset >= (uint)values.Length) { // Consumed entire string, move to next string. break; } else { values = values.Slice(offset); } for (offset = 0; offset < values.Length; offset++) { c = values[offset]; if (c == ',') { break; } else if (c != ' ') { // Value contains extra chars; Chunked is not the matched one. transferEncodingOptions = TransferCoding.Other; } } if ((uint)offset >= (uint)values.Length) { // Consumed entire string, move to next string. break; } else if (c == ',') { // Consumed value, move to next value. offset++; if ((uint)offset >= (uint)values.Length) { // Consumed entire string, move to next string. break; } else { values = values.Slice(offset); continue; } } } } return transferEncodingOptions; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryReadLowerCaseUInt64(ReadOnlySpan<byte> byteValue, out ulong value) { if (MemoryMarshal.TryRead(byteValue, out ulong result)) { if (!BitConverter.IsLittleEndian) { result = (result & 0xffff_0000_0000_0000) >> 48 | (result & 0x0000_ffff_0000_0000) >> 16 | (result & 0x0000_0000_ffff_0000) << 16 | (result & 0x0000_0000_0000_ffff) << 48; } value = result | 0x0020_0020_0020_0020; return true; } value = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryReadLowerCaseUInt32(ReadOnlySpan<byte> byteValue, out uint value) { if (MemoryMarshal.TryRead(byteValue, out uint result)) { if (!BitConverter.IsLittleEndian) { result = (result & 0xffff_0000) >> 16 | (result & 0x0000_ffff) << 16; } value = result | 0x0020_0020; return true; } value = 0; return false; } private static void ThrowInvalidContentLengthException(long value) { throw new ArgumentOutOfRangeException(CoreStrings.FormatInvalidContentLength_InvalidNumber(value)); } private static void ThrowInvalidHeaderCharacter(char ch) { throw new InvalidOperationException(CoreStrings.FormatInvalidAsciiOrControlChar(string.Format(CultureInfo.InvariantCulture, "0x{0:X4}", (ushort)ch))); } private static void ThrowInvalidEmptyHeaderName() { throw new InvalidOperationException(CoreStrings.InvalidEmptyHeaderName); } } }
/* Copyright (c) 2010 by Genstein This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Trizbort { partial class DisambiguateRoomsDialog { /// <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(DisambiguateRoomsDialog)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.m_transcriptContextTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.m_roomNamesListBox = new System.Windows.Forms.ListBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.m_roomDescriptionTextBox = new System.Windows.Forms.TextBox(); this.m_thisRoomButton = new System.Windows.Forms.Button(); this.m_newRoomButton = new System.Windows.Forms.Button(); this.m_dontCareAnyMoreButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label1.Location = new System.Drawing.Point(13, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(481, 57); this.label1.TabIndex = 0; this.label1.Text = "Trizbort isn\'t sure which room the transcript is referring to.\r\n\r\nEither several " + "rooms have the same name but different descriptions, or the room description has" + " changed during play.\r\n"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(16, 92); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(132, 13); this.label2.TabIndex = 1; this.label2.Text = "When the transcript says:"; // // m_transcriptContextTextBox // this.m_transcriptContextTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.m_transcriptContextTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_transcriptContextTextBox.Location = new System.Drawing.Point(43, 108); this.m_transcriptContextTextBox.Multiline = true; this.m_transcriptContextTextBox.Name = "m_transcriptContextTextBox"; this.m_transcriptContextTextBox.ReadOnly = true; this.m_transcriptContextTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.m_transcriptContextTextBox.Size = new System.Drawing.Size(451, 88); this.m_transcriptContextTextBox.TabIndex = 2; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(16, 208); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(132, 13); this.label3.TabIndex = 3; this.label3.Text = "Which room does it mean?"; // // m_roomNamesListBox // this.m_roomNamesListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.m_roomNamesListBox.FormattingEnabled = true; this.m_roomNamesListBox.Location = new System.Drawing.Point(43, 248); this.m_roomNamesListBox.Name = "m_roomNamesListBox"; this.m_roomNamesListBox.Size = new System.Drawing.Size(161, 95); this.m_roomNamesListBox.TabIndex = 5; this.m_roomNamesListBox.SelectedIndexChanged += new System.EventHandler(this.RoomNamesListBox_SelectedIndexChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(43, 229); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(34, 13); this.label4.TabIndex = 4; this.label4.Text = "&Room"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(207, 229); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(60, 13); this.label5.TabIndex = 6; this.label5.Text = "&Description"; // // m_roomDescriptionTextBox // this.m_roomDescriptionTextBox.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.m_roomDescriptionTextBox.BackColor = System.Drawing.SystemColors.Window; this.m_roomDescriptionTextBox.Location = new System.Drawing.Point(210, 248); this.m_roomDescriptionTextBox.Multiline = true; this.m_roomDescriptionTextBox.Name = "m_roomDescriptionTextBox"; this.m_roomDescriptionTextBox.ReadOnly = true; this.m_roomDescriptionTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.m_roomDescriptionTextBox.Size = new System.Drawing.Size(284, 95); this.m_roomDescriptionTextBox.TabIndex = 7; // // m_thisRoomButton // this.m_thisRoomButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_thisRoomButton.DialogResult = System.Windows.Forms.DialogResult.Yes; this.m_thisRoomButton.Location = new System.Drawing.Point(65, 362); this.m_thisRoomButton.Name = "m_thisRoomButton"; this.m_thisRoomButton.Size = new System.Drawing.Size(139, 24); this.m_thisRoomButton.TabIndex = 8; this.m_thisRoomButton.Text = "&This Room"; this.m_thisRoomButton.UseVisualStyleBackColor = true; // // m_newRoomButton // this.m_newRoomButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_newRoomButton.DialogResult = System.Windows.Forms.DialogResult.No; this.m_newRoomButton.Location = new System.Drawing.Point(210, 362); this.m_newRoomButton.Name = "m_newRoomButton"; this.m_newRoomButton.Size = new System.Drawing.Size(139, 24); this.m_newRoomButton.TabIndex = 9; this.m_newRoomButton.Text = "A &New Room"; this.m_newRoomButton.UseVisualStyleBackColor = true; // // m_dontCareAnyMoreButton // this.m_dontCareAnyMoreButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.m_dontCareAnyMoreButton.DialogResult = System.Windows.Forms.DialogResult.Abort; this.m_dontCareAnyMoreButton.Location = new System.Drawing.Point(355, 362); this.m_dontCareAnyMoreButton.Name = "m_dontCareAnyMoreButton"; this.m_dontCareAnyMoreButton.Size = new System.Drawing.Size(139, 24); this.m_dontCareAnyMoreButton.TabIndex = 10; this.m_dontCareAnyMoreButton.Text = "I &Dont Care Any More"; this.m_dontCareAnyMoreButton.UseVisualStyleBackColor = true; // // DisambiguateRoomsDialog // this.AcceptButton = this.m_thisRoomButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(506, 398); this.Controls.Add(this.m_dontCareAnyMoreButton); this.Controls.Add(this.m_newRoomButton); this.Controls.Add(this.m_thisRoomButton); this.Controls.Add(this.m_roomDescriptionTextBox); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.m_roomNamesListBox); this.Controls.Add(this.label3); this.Controls.Add(this.m_transcriptContextTextBox); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(514, 425); this.Name = "DisambiguateRoomsDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Disambiguate Rooms"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox m_transcriptContextTextBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.ListBox m_roomNamesListBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox m_roomDescriptionTextBox; private System.Windows.Forms.Button m_thisRoomButton; private System.Windows.Forms.Button m_newRoomButton; private System.Windows.Forms.Button m_dontCareAnyMoreButton; } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Text { public static class __Encoding { public static IObservable<System.Byte[]> Convert(IObservable<System.Text.Encoding> srcEncoding, IObservable<System.Text.Encoding> dstEncoding, IObservable<System.Byte[]> bytes) { return Observable.Zip(srcEncoding, dstEncoding, bytes, (srcEncodingLambda, dstEncodingLambda, bytesLambda) => System.Text.Encoding.Convert(srcEncodingLambda, dstEncodingLambda, bytesLambda)); } public static IObservable<System.Byte[]> Convert(IObservable<System.Text.Encoding> srcEncoding, IObservable<System.Text.Encoding> dstEncoding, IObservable<System.Byte[]> bytes, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(srcEncoding, dstEncoding, bytes, index, count, (srcEncodingLambda, dstEncodingLambda, bytesLambda, indexLambda, countLambda) => System.Text.Encoding.Convert(srcEncodingLambda, dstEncodingLambda, bytesLambda, indexLambda, countLambda)); } public static IObservable<System.Reactive.Unit> RegisterProvider( IObservable<System.Text.EncodingProvider> provider) { return Observable.Do(provider, (providerLambda) => System.Text.Encoding.RegisterProvider(providerLambda)) .ToUnit(); } public static IObservable<System.Text.Encoding> GetEncoding(IObservable<System.Int32> codepage) { return Observable.Select(codepage, (codepageLambda) => System.Text.Encoding.GetEncoding(codepageLambda)); } public static IObservable<System.Text.Encoding> GetEncoding(IObservable<System.Int32> codepage, IObservable<System.Text.EncoderFallback> encoderFallback, IObservable<System.Text.DecoderFallback> decoderFallback) { return Observable.Zip(codepage, encoderFallback, decoderFallback, (codepageLambda, encoderFallbackLambda, decoderFallbackLambda) => System.Text.Encoding.GetEncoding(codepageLambda, encoderFallbackLambda, decoderFallbackLambda)); } public static IObservable<System.Text.Encoding> GetEncoding(IObservable<System.String> name) { return Observable.Select(name, (nameLambda) => System.Text.Encoding.GetEncoding(nameLambda)); } public static IObservable<System.Text.Encoding> GetEncoding(IObservable<System.String> name, IObservable<System.Text.EncoderFallback> encoderFallback, IObservable<System.Text.DecoderFallback> decoderFallback) { return Observable.Zip(name, encoderFallback, decoderFallback, (nameLambda, encoderFallbackLambda, decoderFallbackLambda) => System.Text.Encoding.GetEncoding(nameLambda, encoderFallbackLambda, decoderFallbackLambda)); } public static IObservable<System.Text.EncodingInfo[]> GetEncodings() { return ObservableExt.Factory(() => System.Text.Encoding.GetEncodings()); } public static IObservable<System.Byte[]> GetPreamble(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.GetPreamble()); } public static IObservable<System.Object> Clone(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.Clone()); } public static IObservable<System.Int32> GetByteCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Char[]> chars) { return Observable.Zip(EncodingValue, chars, (EncodingValueLambda, charsLambda) => EncodingValueLambda.GetByteCount(charsLambda)); } public static IObservable<System.Int32> GetByteCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.String> s) { return Observable.Zip(EncodingValue, s, (EncodingValueLambda, sLambda) => EncodingValueLambda.GetByteCount(sLambda)); } public static IObservable<System.Int32> GetByteCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Char[]> chars, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(EncodingValue, chars, index, count, (EncodingValueLambda, charsLambda, indexLambda, countLambda) => EncodingValueLambda.GetByteCount(charsLambda, indexLambda, countLambda)); } public static IObservable<System.Byte[]> GetBytes(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Char[]> chars) { return Observable.Zip(EncodingValue, chars, (EncodingValueLambda, charsLambda) => EncodingValueLambda.GetBytes(charsLambda)); } public static IObservable<System.Byte[]> GetBytes(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Char[]> chars, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(EncodingValue, chars, index, count, (EncodingValueLambda, charsLambda, indexLambda, countLambda) => EncodingValueLambda.GetBytes(charsLambda, indexLambda, countLambda)); } public static IObservable<System.Int32> GetBytes(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Char[]> chars, IObservable<System.Int32> charIndex, IObservable<System.Int32> charCount, IObservable<System.Byte[]> bytes, IObservable<System.Int32> byteIndex) { return Observable.Zip(EncodingValue, chars, charIndex, charCount, bytes, byteIndex, (EncodingValueLambda, charsLambda, charIndexLambda, charCountLambda, bytesLambda, byteIndexLambda) => EncodingValueLambda.GetBytes(charsLambda, charIndexLambda, charCountLambda, bytesLambda, byteIndexLambda)); } public static IObservable<System.Byte[]> GetBytes(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.String> s) { return Observable.Zip(EncodingValue, s, (EncodingValueLambda, sLambda) => EncodingValueLambda.GetBytes(sLambda)); } public static IObservable<System.Int32> GetBytes(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.String> s, IObservable<System.Int32> charIndex, IObservable<System.Int32> charCount, IObservable<System.Byte[]> bytes, IObservable<System.Int32> byteIndex) { return Observable.Zip(EncodingValue, s, charIndex, charCount, bytes, byteIndex, (EncodingValueLambda, sLambda, charIndexLambda, charCountLambda, bytesLambda, byteIndexLambda) => EncodingValueLambda.GetBytes(sLambda, charIndexLambda, charCountLambda, bytesLambda, byteIndexLambda)); } public static IObservable<System.Int32> GetCharCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes) { return Observable.Zip(EncodingValue, bytes, (EncodingValueLambda, bytesLambda) => EncodingValueLambda.GetCharCount(bytesLambda)); } public static IObservable<System.Int32> GetCharCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(EncodingValue, bytes, index, count, (EncodingValueLambda, bytesLambda, indexLambda, countLambda) => EncodingValueLambda.GetCharCount(bytesLambda, indexLambda, countLambda)); } public static IObservable<System.Char[]> GetChars(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes) { return Observable.Zip(EncodingValue, bytes, (EncodingValueLambda, bytesLambda) => EncodingValueLambda.GetChars(bytesLambda)); } public static IObservable<System.Char[]> GetChars(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(EncodingValue, bytes, index, count, (EncodingValueLambda, bytesLambda, indexLambda, countLambda) => EncodingValueLambda.GetChars(bytesLambda, indexLambda, countLambda)); } public static IObservable<System.Int32> GetChars(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes, IObservable<System.Int32> byteIndex, IObservable<System.Int32> byteCount, IObservable<System.Char[]> chars, IObservable<System.Int32> charIndex) { return Observable.Zip(EncodingValue, bytes, byteIndex, byteCount, chars, charIndex, (EncodingValueLambda, bytesLambda, byteIndexLambda, byteCountLambda, charsLambda, charIndexLambda) => EncodingValueLambda.GetChars(bytesLambda, byteIndexLambda, byteCountLambda, charsLambda, charIndexLambda)); } public static IObservable<System.Boolean> IsAlwaysNormalized( this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsAlwaysNormalized()); } public static IObservable<System.Boolean> IsAlwaysNormalized( this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Text.NormalizationForm> form) { return Observable.Zip(EncodingValue, form, (EncodingValueLambda, formLambda) => EncodingValueLambda.IsAlwaysNormalized(formLambda)); } public static IObservable<System.Text.Decoder> GetDecoder(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.GetDecoder()); } public static IObservable<System.Text.Encoder> GetEncoder(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.GetEncoder()); } public static IObservable<System.Int32> GetMaxByteCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Int32> charCount) { return Observable.Zip(EncodingValue, charCount, (EncodingValueLambda, charCountLambda) => EncodingValueLambda.GetMaxByteCount(charCountLambda)); } public static IObservable<System.Int32> GetMaxCharCount(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Int32> byteCount) { return Observable.Zip(EncodingValue, byteCount, (EncodingValueLambda, byteCountLambda) => EncodingValueLambda.GetMaxCharCount(byteCountLambda)); } public static IObservable<System.String> GetString(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes) { return Observable.Zip(EncodingValue, bytes, (EncodingValueLambda, bytesLambda) => EncodingValueLambda.GetString(bytesLambda)); } public static IObservable<System.String> GetString(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Byte[]> bytes, IObservable<System.Int32> index, IObservable<System.Int32> count) { return Observable.Zip(EncodingValue, bytes, index, count, (EncodingValueLambda, bytesLambda, indexLambda, countLambda) => EncodingValueLambda.GetString(bytesLambda, indexLambda, countLambda)); } public static IObservable<System.Boolean> Equals(this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Object> value) { return Observable.Zip(EncodingValue, value, (EncodingValueLambda, valueLambda) => EncodingValueLambda.Equals(valueLambda)); } public static IObservable<System.Int32> GetHashCode(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.GetHashCode()); } public static IObservable<System.String> get_BodyName(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.BodyName); } public static IObservable<System.String> get_EncodingName(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.EncodingName); } public static IObservable<System.String> get_HeaderName(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.HeaderName); } public static IObservable<System.String> get_WebName(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.WebName); } public static IObservable<System.Int32> get_WindowsCodePage(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.WindowsCodePage); } public static IObservable<System.Boolean> get_IsBrowserDisplay( this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsBrowserDisplay); } public static IObservable<System.Boolean> get_IsBrowserSave(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsBrowserSave); } public static IObservable<System.Boolean> get_IsMailNewsDisplay( this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsMailNewsDisplay); } public static IObservable<System.Boolean> get_IsMailNewsSave( this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsMailNewsSave); } public static IObservable<System.Boolean> get_IsSingleByte(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsSingleByte); } public static IObservable<System.Text.EncoderFallback> get_EncoderFallback( this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.EncoderFallback); } public static IObservable<System.Text.DecoderFallback> get_DecoderFallback( this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.DecoderFallback); } public static IObservable<System.Boolean> get_IsReadOnly(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.IsReadOnly); } public static IObservable<System.Text.Encoding> get_ASCII() { return ObservableExt.Factory(() => System.Text.Encoding.ASCII); } public static IObservable<System.Int32> get_CodePage(this IObservable<System.Text.Encoding> EncodingValue) { return Observable.Select(EncodingValue, (EncodingValueLambda) => EncodingValueLambda.CodePage); } public static IObservable<System.Text.Encoding> get_Default() { return ObservableExt.Factory(() => System.Text.Encoding.Default); } public static IObservable<System.Text.Encoding> get_Unicode() { return ObservableExt.Factory(() => System.Text.Encoding.Unicode); } public static IObservable<System.Text.Encoding> get_BigEndianUnicode() { return ObservableExt.Factory(() => System.Text.Encoding.BigEndianUnicode); } public static IObservable<System.Text.Encoding> get_UTF7() { return ObservableExt.Factory(() => System.Text.Encoding.UTF7); } public static IObservable<System.Text.Encoding> get_UTF8() { return ObservableExt.Factory(() => System.Text.Encoding.UTF8); } public static IObservable<System.Text.Encoding> get_UTF32() { return ObservableExt.Factory(() => System.Text.Encoding.UTF32); } public static IObservable<System.Reactive.Unit> set_EncoderFallback( this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Text.EncoderFallback> value) { return ObservableExt.ZipExecute(EncodingValue, value, (EncodingValueLambda, valueLambda) => EncodingValueLambda.EncoderFallback = valueLambda); } public static IObservable<System.Reactive.Unit> set_DecoderFallback( this IObservable<System.Text.Encoding> EncodingValue, IObservable<System.Text.DecoderFallback> value) { return ObservableExt.ZipExecute(EncodingValue, value, (EncodingValueLambda, valueLambda) => EncodingValueLambda.DecoderFallback = valueLambda); } } }
using AutoMapper; using AutoMapper.QueryableExtensions; using Microsoft.EntityFrameworkCore; using MvcTemplate.Components; using MvcTemplate.Data; using MvcTemplate.Objects; using MvcTemplate.Resources; using MvcTemplate.Tests; using NSubstitute; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace MvcTemplate.Services.Tests { public class RoleServiceTests : IDisposable { private RoleService service; private DbContext context; private Role role; public RoleServiceTests() { context = TestingContext.Create(); service = Substitute.ForPartsOf<RoleService>(new UnitOfWork(TestingContext.Create())); role = SetUpData(); } public void Dispose() { service.Dispose(); context.Dispose(); } [Fact] public void GetViews_ReturnsRoleViews() { RoleView[] actual = service.GetViews().ToArray(); RoleView[] expected = context .Set<Role>() .ProjectTo<RoleView>() .OrderByDescending(view => view.Id) .ToArray(); for (Int32 i = 0; i < expected.Length || i < actual.Length; i++) { Assert.Equal(expected[i].Permissions.SelectedIds, actual[i].Permissions.SelectedIds); Assert.Equal(expected[i].CreationDate, actual[i].CreationDate); Assert.Equal(expected[i].Title, actual[i].Title); Assert.Equal(expected[i].Id, actual[i].Id); } } [Fact] public void GetView_NoRole_ReturnsNull() { Assert.Null(service.GetView(0)); } [Fact] public void GetView_ReturnsViewById() { RoleView expected = Mapper.Map<RoleView>(role); RoleView actual = service.GetView(role.Id)!; Assert.Equal(expected.CreationDate, actual.CreationDate); Assert.NotEmpty(actual.Permissions.SelectedIds); Assert.Equal(expected.Title, actual.Title); Assert.Equal(expected.Id, actual.Id); } [Fact] public void GetView_SetsSelectedIds() { IEnumerable<Int64> expected = role.Permissions.Select(rolePermission => rolePermission.PermissionId).OrderBy(id => id); IEnumerable<Int64> actual = service.GetView(role.Id)!.Permissions.SelectedIds.OrderBy(id => id); Assert.Equal(expected, actual); } [Fact] public void GetView_SeedsPermissions() { RoleView view = service.GetView(role.Id)!; service.Received().Seed(view.Permissions); } [Fact] public void Seed_FirstDepth() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); service.Seed(view.Permissions); List<MvcTreeNode> expected = CreatePermissions().Nodes; List<MvcTreeNode> actual = view.Permissions.Nodes; for (Int32 i = 0; i < expected.Count || i < actual.Count; i++) { Assert.Equal(expected[i].Id, actual[i].Id); Assert.Equal(expected[i].Title, actual[i].Title); Assert.Equal(expected[i].Children.Count, actual[i].Children.Count); } } [Fact] public void Seed_SecondDepth() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); service.Seed(view.Permissions); List<MvcTreeNode> expected = CreatePermissions().Nodes.SelectMany(node => node.Children).ToList(); List<MvcTreeNode> actual = view.Permissions.Nodes.SelectMany(node => node.Children).ToList(); for (Int32 i = 0; i < expected.Count || i < actual.Count; i++) { Assert.Equal(expected[i].Id, actual[i].Id); Assert.Equal(expected[i].Title, actual[i].Title); Assert.Equal(expected[i].Children.Count, actual[i].Children.Count); } } [Fact] public void Seed_ThirdDepth() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); service.Seed(view.Permissions); List<MvcTreeNode> expected = CreatePermissions().Nodes.SelectMany(node => node.Children).SelectMany(node => node.Children).OrderBy(node => node.Id).ToList(); List<MvcTreeNode> actual = view.Permissions.Nodes.SelectMany(node => node.Children).SelectMany(node => node.Children).OrderBy(node => node.Id).ToList(); for (Int32 i = 0; i < expected.Count || i < actual.Count; i++) { Assert.Equal(expected[i].Id, actual[i].Id); Assert.Equal(expected[i].Title, actual[i].Title); Assert.Equal(expected[i].Children.Count, actual[i].Children.Count); } } [Fact] public void Seed_BranchesWithoutId() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); service.Seed(view.Permissions); IEnumerable<MvcTreeNode> nodes = view.Permissions.Nodes; IEnumerable<MvcTreeNode> branches = GetBranchNodes(nodes); Assert.Empty(branches.Where(branch => branch.Id != null)); } [Fact] public void Seed_LeafsWithId() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); service.Seed(view.Permissions); IEnumerable<MvcTreeNode> nodes = view.Permissions.Nodes; IEnumerable<MvcTreeNode> leafs = GetLeafNodes(nodes); Assert.Empty(leafs.Where(leaf => leaf.Id == null)); } [Fact] public void Create_Role() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); service.Create(view); Role actual = Assert.Single(context.Set<Role>(), model => model.Id != role.Id); RoleView expected = view; Assert.Equal(expected.CreationDate, actual.CreationDate); Assert.Equal(expected.Title, actual.Title); } [Fact] public void Create_RolePermissions() { RoleView view = ObjectsFactory.CreateRoleView(role.Id + 1); view.Permissions = CreatePermissions(); service.Create(view); IEnumerable<Int64> expected = view.Permissions.SelectedIds.OrderBy(permissionId => permissionId); IEnumerable<Int64> actual = context .Set<RolePermission>() .Where(rolePermission => rolePermission.RoleId != role.Id) .Select(rolePermission => rolePermission.PermissionId) .OrderBy(permissionId => permissionId); Assert.Equal(expected, actual); } [Fact] public void Edit_Role() { RoleView view = ObjectsFactory.CreateRoleView(role.Id); view.Title = role.Title += "Test"; service.Edit(view); Role actual = Assert.Single(context.Set<Role>().AsNoTracking()); Role expected = role; Assert.Equal(expected.CreationDate, actual.CreationDate); Assert.Equal(expected.Title, actual.Title); Assert.Equal(expected.Id, actual.Id); } [Fact] public void Edit_RolePermissions() { Permission permission = ObjectsFactory.CreatePermission(0); context.Add(permission); context.SaveChanges(); RoleView view = ObjectsFactory.CreateRoleView(role.Id); view.Permissions = CreatePermissions(); view.Permissions.SelectedIds.Remove(view.Permissions.SelectedIds.First()); view.Permissions.SelectedIds.Add(permission.Id); service.Edit(view); IEnumerable<Int64> actual = context.Set<RolePermission>().AsNoTracking().Select(rolePermission => rolePermission.PermissionId).OrderBy(permissionId => permissionId); IEnumerable<Int64> expected = view.Permissions.SelectedIds.OrderBy(permissionId => permissionId); Assert.Equal(expected, actual); } [Fact] public void Delete_NullsAccountRoles() { Account account = ObjectsFactory.CreateAccount(0); account.RoleId = role.Id; account.Role = null; context.Add(account); context.SaveChanges(); service.Delete(role.Id); Assert.Contains(context.Set<Account>().AsNoTracking(), model => model.Id == account.Id && model.RoleId == null); } [Fact] public void Delete_Role() { service.Delete(role.Id); Assert.Empty(context.Set<Role>()); } private Role SetUpData() { Role role = ObjectsFactory.CreateRole(0); foreach (String controller in new[] { "TestController1", "TestController2" }) foreach (String action in new[] { "Action1", "Action2" }) role.Permissions.Add(new RolePermission { Permission = new Permission { Area = controller == "TestController1" ? "TestingArea" : "", Controller = controller, Action = action } }); context.Drop().Add(role); context.SaveChanges(); return role; } private MvcTree CreatePermissions() { MvcTree expectedTree = new(); MvcTreeNode root = new(Resource.ForString("All")); expectedTree.Nodes.Add(root); expectedTree.SelectedIds = new HashSet<Int64>(role.Permissions.Select(rolePermission => rolePermission.PermissionId)); IEnumerable<PermissionView> permissions = role .Permissions .Select(rolePermission => rolePermission.Permission) .Select(permission => new PermissionView { Id = permission.Id, Area = Resource.ForArea(permission.Area), Action = Resource.ForAction(permission.Action), Controller = Resource.ForController($"{permission.Area}/{permission.Controller}") }); foreach (IGrouping<String?, PermissionView> area in permissions.GroupBy(permission => permission.Area).OrderBy(permission => permission.Key ?? permission.FirstOrDefault()?.Controller)) { List<MvcTreeNode> nodes = new(); foreach (IGrouping<String, PermissionView> controller in area.GroupBy(permission => permission.Controller)) { MvcTreeNode node = new(controller.Key); foreach (PermissionView permission in controller) node.Children.Add(new MvcTreeNode(permission.Id, permission.Action)); nodes.Add(node); } if (area.Key == null) root.Children.AddRange(nodes); else root.Children.Add(new MvcTreeNode(area.Key) { Children = nodes }); } return expectedTree; } private IEnumerable<MvcTreeNode> GetLeafNodes(IEnumerable<MvcTreeNode> nodes) { List<MvcTreeNode> leafs = new(); foreach (MvcTreeNode node in nodes.Where(node => node.Children.Count > 0)) if (node.Children.Count > 0) leafs.AddRange(GetLeafNodes(node.Children)); else leafs.Add(node); return leafs; } private IEnumerable<MvcTreeNode> GetBranchNodes(IEnumerable<MvcTreeNode> nodes) { List<MvcTreeNode> branches = nodes.Where(node => node.Children.Count > 0).ToList(); foreach (MvcTreeNode branch in branches.ToArray()) branches.AddRange(GetBranchNodes(branch.Children)); return branches; } } }
#region Copyright (c) all rights reserved. // <copyright file="SqlDataTargetFacts.cs"> // THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // </copyright> #endregion namespace Ditto.DataLoad.Tests { using System; using System.Collections.Generic; using System.Data; using System.Linq; using Ditto.Core; using Ditto.Core.Tests; using NSubstitute; using Xunit; /// <summary> /// <c>SqlDataTarget</c> Facts. /// </summary> [CLSCompliant(false)] public class SqlDataTargetFacts : DbDataFixture { /// <summary> /// The target table name. /// </summary> private const string TargetTableName = "TEST TABLE NAME"; /// <summary> /// The bulk copy factory. /// </summary> private IBulkCopyFactory bulkCopyFactory; /// <summary> /// The watermark service. /// </summary> private IHighWatermarkService watermarkService; /// <summary> /// The target. /// </summary> private SqlDataTarget nonWatermarkTarget; /// <summary> /// The target. /// </summary> private SqlDataTarget watermarkedTarget; /// <summary> /// Initializes a new instance of the <see cref="SqlDataTargetFacts"/> class. /// </summary> public SqlDataTargetFacts() { this.bulkCopyFactory = Substitute.For<IBulkCopyFactory>(); this.watermarkService = Substitute.For<IHighWatermarkService>(); this.nonWatermarkTarget = new SqlDataTarget(this.ConnectionFactory, this.bulkCopyFactory, this.watermarkService, TargetTableName, string.Empty, true); this.watermarkedTarget = new SqlDataTarget(this.ConnectionFactory, this.bulkCopyFactory, this.watermarkService, TargetTableName, "WATERMARK COLUMN", true); } /// <summary> /// Enumerates the database nulls. /// </summary> /// <returns>A sequence of nulls that come from the database.</returns> public static IEnumerable<object[]> EnumerateDatabaseNulls() { yield return new object[] { null }; yield return new object[] { DBNull.Value }; } /// <summary> /// Exists the should return true when table exists. /// </summary> /// <param name="commandResponse">The command response.</param> /// <param name="exists">If set to <c>true</c> [exists].</param> [Theory] [InlineData(0, false)] [InlineData(1, true)] public void ExistsShouldCheckForTableExisting(int commandResponse, bool exists) { this.Command.ExecuteScalar().ReturnsForAnyArgs(commandResponse); Assert.Equal(exists, this.nonWatermarkTarget.Exists); } /// <summary> /// Should return null when updating non watermarked watermark. /// </summary> [Fact] public void ShouldReturnNullWhenUpdatingNonWatermarkedWatermark() { Assert.Null(this.nonWatermarkTarget.UpdateHighWatermark()); } /// <summary> /// Should return null when updating watermark with no data in the table. /// </summary> /// <param name="commandResponse">The command response.</param> [Theory] [MemberData(nameof(EnumerateDatabaseNulls))] public void ShouldReturnNullWhenUpdatingWatermarkWithNoData(object commandResponse) { this.Command.ExecuteScalar().ReturnsForAnyArgs(commandResponse); Assert.Null(this.watermarkedTarget.UpdateHighWatermark()); } /// <summary> /// Should update watermark with correct date. /// </summary> [Fact] public void ShouldUpdateWatermarkWithCorrectDate() { var watermark = new DateTime(2015, 06, 02, 14, 15, 16); this.Command.ExecuteScalar().ReturnsForAnyArgs(watermark); this.watermarkService.UpdateHighWatermark( Arg.Any<string>(), Arg.Do<Watermark>(w => Assert.Equal(watermark, w.WatermarkValue))); this.watermarkedTarget.UpdateHighWatermark(); } /// <summary> /// Should truncate when initialize batch called. /// </summary> [Fact] public void ShouldTruncateWhenInitializeBatchCalled() { this.nonWatermarkTarget.InitializeBatch(); this.Command.Received().ExecuteNonQuery(); Assert.Contains("truncate", this.Command.CommandText, StringComparison.OrdinalIgnoreCase); } /// <summary> /// BulkCopy should have correct target table name. /// </summary> [Fact] public void BulkCopyShouldHaveCorrectTargetTableName() { using (var bulkCopy = this.nonWatermarkTarget.CreateBulkCopy()) { Assert.Equal(TargetTableName, bulkCopy.DestinationTableName); } } /// <summary> /// Column property should return correct column count. /// </summary> [Fact] public void ColumnsPropertyShouldReturnCorrectColumnCount() { using (var schema = FakeSchemaFactory.CreateDefaultTableSchema()) { this.Reader.GetSchemaTable().ReturnsForAnyArgs(schema); Assert.Equal(schema.Rows.Count, this.nonWatermarkTarget.Columns.Count()); } } /// <summary> /// Creating the table causes SQL to be executed. /// </summary> /// <remarks>NB: This is a behavior test and not very good.</remarks> [Fact] public void CreatingTableCausesSqlToBeExecuted() { using (var schema = FakeSchemaFactory.CreateDefaultTableSchema()) { this.nonWatermarkTarget.CreateTable(schema); Assert.Contains(TargetTableName, this.Command.CommandText, StringComparison.OrdinalIgnoreCase); } } /// <summary> /// Should throw when null connection factory passed. /// </summary> [Fact] public void ShouldThrowWhenNullConnectionFactoryPassed() { Assert.Throws<ArgumentNullException>( () => new SqlDataTarget(null, this.bulkCopyFactory, this.watermarkService, string.Empty, string.Empty, false)); } /// <summary> /// Should throw when null bulk copy factory passed. /// </summary> [Fact] public void ShouldThrowWhenNullBulkCopyFactoryPassed() { Assert.Throws<ArgumentNullException>( () => new SqlDataTarget(this.ConnectionFactory, null, this.watermarkService, string.Empty, string.Empty, false)); } /// <summary> /// Should throw when null watermark service passed. /// </summary> [Fact] public void ShouldThrowWhenNullWatermarkServicePassed() { Assert.Throws<ArgumentNullException>( () => new SqlDataTarget(this.ConnectionFactory, this.bulkCopyFactory, null, string.Empty, string.Empty, false)); } /// <summary> /// Should throw when null table name passed. /// </summary> [Fact] public void ShouldThrowWhenNullTableNamePassed() { Assert.Throws<ArgumentNullException>( () => new SqlDataTarget(this.ConnectionFactory, this.bulkCopyFactory, this.watermarkService, null, string.Empty, false)); } } }
#region License and Terms // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // The MIT License (MIT) // // Copyright(c) Microsoft Corporation // // 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 namespace MoreLinq { using System; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// A <see cref="ILookup{TKey, TElement}"/> implementation that preserves insertion order /// </summary> /// <typeparam name="TKey">The type of the keys in the <see cref="Lookup{TKey, TElement}"/></typeparam> /// <typeparam name="TElement">The type of the elements in the <see cref="IEnumerable{T}"/> sequences that make up the values in the <see cref="Lookup{TKey, TElement}"/></typeparam> /// <remarks> /// This implementation preserves insertion order of keys and elements within each <see cref="IEnumerable{T}"/> /// Copied over from CoreFX on 2015-10-27 /// https://github.com/dotnet/corefx/blob/6f1c2a86fb8fa1bdaee7c6e70a684d27842d804c/src/System.Linq/src/System/Linq/Enumerable.cs#L3230-L3403 /// Modified to remove internal interfaces /// </remarks> internal class Lookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>, ILookup<TKey, TElement> { private IEqualityComparer<TKey> _comparer; private Grouping<TKey, TElement>[] _groupings; private Grouping<TKey, TElement> _lastGrouping; private int _count; internal static Lookup<TKey, TElement> Create<TSource>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) { if (source == null) throw new ArgumentNullException(nameof(source)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); if (elementSelector == null) throw new ArgumentNullException(nameof(elementSelector)); Lookup<TKey, TElement> lookup = new Lookup<TKey, TElement>(comparer); foreach (TSource item in source) { lookup.GetGrouping(keySelector(item), true).Add(elementSelector(item)); } return lookup; } internal static Lookup<TKey, TElement> CreateForJoin(IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer) { Lookup<TKey, TElement> lookup = new Lookup<TKey, TElement>(comparer); foreach (TElement item in source) { TKey key = keySelector(item); if (key != null) lookup.GetGrouping(key, true).Add(item); } return lookup; } private Lookup(IEqualityComparer<TKey> comparer) { if (comparer == null) comparer = EqualityComparer<TKey>.Default; _comparer = comparer; _groupings = new Grouping<TKey, TElement>[7]; } public int Count { get { return _count; } } public IEnumerable<TElement> this[TKey key] { get { Grouping<TKey, TElement> grouping = GetGrouping(key, false); if (grouping != null) return grouping; return Enumerable.Empty<TElement>(); } } public bool Contains(TKey key) { return _count > 0 && GetGrouping(key, false) != null; } public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator() { Grouping<TKey, TElement> g = _lastGrouping; if (g != null) { do { g = g.next; yield return g; } while (g != _lastGrouping); } } public IEnumerable<TResult> ApplyResultSelector<TResult>(Func<TKey, IEnumerable<TElement>, TResult> resultSelector) { Grouping<TKey, TElement> g = _lastGrouping; if (g != null) { do { g = g.next; if (g.count != g.elements.Length) { Array.Resize<TElement>(ref g.elements, g.count); } yield return resultSelector(g.key, g.elements); } while (g != _lastGrouping); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } internal int InternalGetHashCode(TKey key) { // Handle comparer implementations that throw when passed null return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF; } internal Grouping<TKey, TElement> GetGrouping(TKey key, bool create) { int hashCode = InternalGetHashCode(key); for (Grouping<TKey, TElement> g = _groupings[hashCode % _groupings.Length]; g != null; g = g.hashNext) if (g.hashCode == hashCode && _comparer.Equals(g.key, key)) return g; if (create) { if (_count == _groupings.Length) Resize(); int index = hashCode % _groupings.Length; Grouping<TKey, TElement> g = new Grouping<TKey, TElement>(); g.key = key; g.hashCode = hashCode; g.elements = new TElement[1]; g.hashNext = _groupings[index]; _groupings[index] = g; if (_lastGrouping == null) { g.next = g; } else { g.next = _lastGrouping.next; _lastGrouping.next = g; } _lastGrouping = g; _count++; return g; } return null; } private void Resize() { int newSize = checked(_count * 2 + 1); Grouping<TKey, TElement>[] newGroupings = new Grouping<TKey, TElement>[newSize]; Grouping<TKey, TElement> g = _lastGrouping; do { g = g.next; int index = g.hashCode % newSize; g.hashNext = newGroupings[index]; newGroupings[index] = g; } while (g != _lastGrouping); _groupings = newGroupings; } } internal class Grouping<TKey, TElement> : IGrouping<TKey, TElement>, IList<TElement> { internal TKey key; internal int hashCode; internal TElement[] elements; internal int count; internal Grouping<TKey, TElement> hashNext; internal Grouping<TKey, TElement> next; internal Grouping() { } internal void Add(TElement element) { if (elements.Length == count) Array.Resize(ref elements, checked(count * 2)); elements[count] = element; count++; } public IEnumerator<TElement> GetEnumerator() { for (int i = 0; i < count; i++) yield return elements[i]; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // DDB195907: implement IGrouping<>.Key implicitly // so that WPF binding works on this property. public TKey Key { get { return key; } } int ICollection<TElement>.Count { get { return count; } } bool ICollection<TElement>.IsReadOnly { get { return true; } } void ICollection<TElement>.Add(TElement item) { throw new NotSupportedException("Lookup is immutable"); } void ICollection<TElement>.Clear() { throw new NotSupportedException("Lookup is immutable"); } bool ICollection<TElement>.Contains(TElement item) { return Array.IndexOf(elements, item, 0, count) >= 0; } void ICollection<TElement>.CopyTo(TElement[] array, int arrayIndex) { Array.Copy(elements, 0, array, arrayIndex, count); } bool ICollection<TElement>.Remove(TElement item) { throw new NotSupportedException("Lookup is immutable"); } int IList<TElement>.IndexOf(TElement item) { return Array.IndexOf(elements, item, 0, count); } void IList<TElement>.Insert(int index, TElement item) { throw new NotSupportedException("Lookup is immutable"); } void IList<TElement>.RemoveAt(int index) { throw new NotSupportedException("Lookup is immutable"); } TElement IList<TElement>.this[int index] { get { if (index < 0 || index >= count) throw new ArgumentOutOfRangeException(nameof(index)); return elements[index]; } set { throw new NotSupportedException("Lookup is immutable"); } } } }
// 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 Fixtures.AcceptanceTestsBodyString { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// EnumModel operations. /// </summary> public partial class EnumModel : IServiceOperations<AutoRestSwaggerBATService>, IEnumModel { /// <summary> /// Initializes a new instance of the EnumModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EnumModel(AutoRestSwaggerBATService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestSwaggerBATService /// </summary> public AutoRestSwaggerBATService Client { get; private set; } /// <summary> /// Get enum value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color'. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Colors?>> GetNotExpandableWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNotExpandable", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Colors?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Colors?>(_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> /// Sends value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color' /// </summary> /// <param name='stringBody'> /// Possible values include: 'red color', 'green-color', 'blue_color' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutNotExpandableWithHttpMessagesAsync(Colors stringBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("stringBody", stringBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutNotExpandable", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(stringBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get enum value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color'. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Colors?>> GetReferencedWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetReferenced", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/Referenced").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Colors?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Colors?>(_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> /// Sends value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color' /// </summary> /// <param name='enumStringBody'> /// Possible values include: 'red color', 'green-color', 'blue_color' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutReferencedWithHttpMessagesAsync(Colors enumStringBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("enumStringBody", enumStringBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutReferenced", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/Referenced").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(enumStringBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get value 'green-color' from the constant. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<RefColorConstant>> GetReferencedConstantWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetReferencedConstant", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/ReferencedConstant").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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; // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<RefColorConstant>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RefColorConstant>(_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> /// Sends value 'green-color' from a constant /// </summary> /// <param name='field1'> /// Sample string. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutReferencedConstantWithHttpMessagesAsync(string field1 = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { RefColorConstant enumStringBody = new RefColorConstant(); if (field1 != null) { enumStringBody.Field1 = field1; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("enumStringBody", enumStringBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutReferencedConstant", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/ReferencedConstant").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (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(enumStringBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(enumStringBody, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gckv = Google.Cloud.Kms.V1; namespace Google.Cloud.Kms.V1 { public partial class ListKeyRingsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListCryptoKeysRequest { /// <summary> /// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public KeyRingName ParentAsKeyRingName { get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListCryptoKeyVersionsRequest { /// <summary> /// <see cref="CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public CryptoKeyName ParentAsCryptoKeyName { get => string.IsNullOrEmpty(Parent) ? null : CryptoKeyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListImportJobsRequest { /// <summary> /// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public KeyRingName ParentAsKeyRingName { get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetKeyRingRequest { /// <summary> /// <see cref="gckv::KeyRingName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::KeyRingName KeyRingName { get => string.IsNullOrEmpty(Name) ? null : gckv::KeyRingName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetCryptoKeyRequest { /// <summary> /// <see cref="gckv::CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyName CryptoKeyName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetCryptoKeyVersionRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetPublicKeyRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetImportJobRequest { /// <summary> /// <see cref="gckv::ImportJobName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::ImportJobName ImportJobName { get => string.IsNullOrEmpty(Name) ? null : gckv::ImportJobName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateKeyRingRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CreateCryptoKeyRequest { /// <summary> /// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public KeyRingName ParentAsKeyRingName { get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class CreateCryptoKeyVersionRequest { /// <summary> /// <see cref="CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public CryptoKeyName ParentAsCryptoKeyName { get => string.IsNullOrEmpty(Parent) ? null : CryptoKeyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ImportCryptoKeyVersionRequest { /// <summary> /// <see cref="CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public CryptoKeyName ParentAsCryptoKeyName { get => string.IsNullOrEmpty(Parent) ? null : CryptoKeyName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="CryptoKeyVersionName"/>-typed view over the <see cref="CryptoKeyVersion"/> resource name /// property. /// </summary> public CryptoKeyVersionName CryptoKeyVersionAsCryptoKeyVersionName { get => string.IsNullOrEmpty(CryptoKeyVersion) ? null : CryptoKeyVersionName.Parse(CryptoKeyVersion, allowUnparsed: true); set => CryptoKeyVersion = value?.ToString() ?? ""; } } public partial class CreateImportJobRequest { /// <summary> /// <see cref="KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public KeyRingName ParentAsKeyRingName { get => string.IsNullOrEmpty(Parent) ? null : KeyRingName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class UpdateCryptoKeyPrimaryVersionRequest { /// <summary> /// <see cref="gckv::CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyName CryptoKeyName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DestroyCryptoKeyVersionRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class RestoreCryptoKeyVersionRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class EncryptRequest { /// <summary> /// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gax::IResourceName ResourceName { get => string.IsNullOrEmpty(Name) ? null : gax::UnparsedResourceName.Parse(Name); set => Name = value?.ToString() ?? ""; } } public partial class DecryptRequest { /// <summary> /// <see cref="gckv::CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyName CryptoKeyName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class AsymmetricSignRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class AsymmetricDecryptRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class MacSignRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class MacVerifyRequest { /// <summary> /// <see cref="gckv::CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gckv::CryptoKeyVersionName CryptoKeyVersionName { get => string.IsNullOrEmpty(Name) ? null : gckv::CryptoKeyVersionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #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.Reflection; using System.Linq; namespace PlayFab.Json.Utilities { internal static class TypeExtensions { private static PlayFab.Json.Utilities.BindingFlags DefaultFlags = PlayFab.Json.Utilities.BindingFlags.Public | PlayFab.Json.Utilities.BindingFlags.Static | PlayFab.Json.Utilities.BindingFlags.Instance; public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetGetMethod(false); } public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo getMethod = propertyInfo.GetMethod; if (getMethod != null && (getMethod.IsPublic || nonPublic)) return getMethod; return null; } public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetSetMethod(false); } public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo setMethod = propertyInfo.SetMethod; if (setMethod != null && (setMethod.IsPublic || nonPublic)) return setMethod; return null; } public static bool IsSubclassOf(this Type type, Type c) { return type.GetTypeInfo().IsSubclassOf(c); } public static bool IsAssignableFrom(this Type type, Type c) { return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo()); } public static MethodInfo Method(this Delegate d) { return d.GetMethodInfo(); } public static MemberTypes MemberType(this MemberInfo memberInfo) { if (memberInfo is PropertyInfo) return MemberTypes.Property; else if (memberInfo is FieldInfo) return MemberTypes.Field; else if (memberInfo is EventInfo) return MemberTypes.Event; else if (memberInfo is MethodInfo) return MemberTypes.Method; else return MemberTypes.Other; } public static bool ContainsGenericParameters(this Type type) { return type.GetTypeInfo().ContainsGenericParameters; } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.GetTypeInfo().IsGenericTypeDefinition; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsClass(this Type type) { return type.GetTypeInfo().IsClass; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static MethodInfo GetBaseDefinition(this MethodInfo method) { return method.GetRuntimeBaseDefinition(); } public static bool IsDefined(this Type type, Type attributeType, bool inherit) { return type.GetTypeInfo().CustomAttributes.Any(a => a.AttributeType == attributeType); } public static MethodInfo GetMethod(this Type type, string name) { return type.GetMethod(name, DefaultFlags); } public static MethodInfo GetMethod(this Type type, string name, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetDeclaredMethod(name); } public static MethodInfo GetMethod(this Type type, IList<Type> parameterTypes) { return type.GetMethod(null, parameterTypes); } public static MethodInfo GetMethod(this Type type, string name, IList<Type> parameterTypes) { return type.GetMethod(name, DefaultFlags, null, parameterTypes, null); } public static MethodInfo GetMethod(this Type type, string name, PlayFab.Json.Utilities.BindingFlags bindingFlags, object placeHolder1, IList<Type> parameterTypes, object placeHolder2) { return type.GetTypeInfo().DeclaredMethods.Where(m => { if (name != null && m.Name != name) return false; if (!TestAccessibility(m, bindingFlags)) return false; return m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes); }).SingleOrDefault(); } public static PropertyInfo GetProperty(this Type type, string name, PlayFab.Json.Utilities.BindingFlags bindingFlags, object placeholder1, Type propertyType, IList<Type> indexParameters, object placeholder2) { return type.GetTypeInfo().DeclaredProperties.Where(p => { if (name != null && name != p.Name) return false; if (propertyType != null && propertyType != p.PropertyType) return false; if (indexParameters != null) { if (!p.GetIndexParameters().Select(ip => ip.ParameterType).SequenceEqual(indexParameters)) return false; } return true; }).SingleOrDefault(); } public static IEnumerable<MemberInfo> GetMember(this Type type, string name, MemberTypes memberType, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetMembersRecursive().Where(m => { if (name != null && name != m.Name) return false; if (m.MemberType() != memberType) return false; if (!TestAccessibility(m, bindingFlags)) return false; return true; }); } public static IEnumerable<ConstructorInfo> GetConstructors(this Type type) { return type.GetConstructors(DefaultFlags); } public static IEnumerable<ConstructorInfo> GetConstructors(this Type type, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetConstructors(bindingFlags, null); } private static IEnumerable<ConstructorInfo> GetConstructors(this Type type, PlayFab.Json.Utilities.BindingFlags bindingFlags, IList<Type> parameterTypes) { return type.GetTypeInfo().DeclaredConstructors.Where(c => { if (!TestAccessibility(c, bindingFlags)) return false; if (parameterTypes != null && !c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)) return false; return true; }); } public static ConstructorInfo GetConstructor(this Type type, IList<Type> parameterTypes) { return type.GetConstructor(DefaultFlags, null, parameterTypes, null); } public static ConstructorInfo GetConstructor(this Type type, PlayFab.Json.Utilities.BindingFlags bindingFlags, object placeholder1, IList<Type> parameterTypes, object placeholder2) { return type.GetConstructors(bindingFlags, parameterTypes).SingleOrDefault(); } public static MemberInfo[] GetMember(this Type type, string member) { return type.GetMember(member, DefaultFlags); } public static MemberInfo[] GetMember(this Type type, string member, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetMembersRecursive().Where(m => m.Name == member && TestAccessibility(m, bindingFlags)).ToArray(); } public static MemberInfo GetField(this Type type, string member) { return type.GetField(member, DefaultFlags); } public static MemberInfo GetField(this Type type, string member, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetDeclaredField(member); } public static IEnumerable<PropertyInfo> GetProperties(this Type type, PlayFab.Json.Utilities.BindingFlags bindingFlags) { IList<PropertyInfo> properties = (bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.DeclaredOnly)) ? type.GetTypeInfo().DeclaredProperties.ToList() : type.GetTypeInfo().GetPropertiesRecursive(); return properties.Where(p => TestAccessibility(p, bindingFlags)); } private static IList<MemberInfo> GetMembersRecursive(this TypeInfo type) { TypeInfo t = type; IList<MemberInfo> members = new List<MemberInfo>(); while (t != null) { foreach (var member in t.DeclaredMembers) { if (!members.Any(p => p.Name == member.Name)) members.Add(member); } t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; } return members; } private static IList<PropertyInfo> GetPropertiesRecursive(this TypeInfo type) { TypeInfo t = type; IList<PropertyInfo> properties = new List<PropertyInfo>(); while (t != null) { foreach (var member in t.DeclaredProperties) { if (!properties.Any(p => p.Name == member.Name)) properties.Add(member); } t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; } return properties; } private static IList<FieldInfo> GetFieldsRecursive(this TypeInfo type) { TypeInfo t = type; IList<FieldInfo> fields = new List<FieldInfo>(); while (t != null) { foreach (var member in t.DeclaredFields) { if (!fields.Any(p => p.Name == member.Name)) fields.Add(member); } t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; } return fields; } public static IEnumerable<MethodInfo> GetMethods(this Type type, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().DeclaredMethods; } public static PropertyInfo GetProperty(this Type type, string name) { return type.GetProperty(name, DefaultFlags); } public static PropertyInfo GetProperty(this Type type, string name, PlayFab.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetDeclaredProperty(name); } public static IEnumerable<FieldInfo> GetFields(this Type type) { return type.GetFields(DefaultFlags); } public static IEnumerable<FieldInfo> GetFields(this Type type, PlayFab.Json.Utilities.BindingFlags bindingFlags) { IList<FieldInfo> fields = (bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.DeclaredOnly)) ? type.GetTypeInfo().DeclaredFields.ToList() : type.GetTypeInfo().GetFieldsRecursive(); return fields.Where(f => TestAccessibility(f, bindingFlags)).ToList(); } private static bool TestAccessibility(PropertyInfo member, PlayFab.Json.Utilities.BindingFlags bindingFlags) { if (member.GetMethod != null && TestAccessibility(member.GetMethod, bindingFlags)) return true; if (member.SetMethod != null && TestAccessibility(member.SetMethod, bindingFlags)) return true; return false; } private static bool TestAccessibility(MemberInfo member, PlayFab.Json.Utilities.BindingFlags bindingFlags) { if (member is FieldInfo) { return TestAccessibility((FieldInfo)member, bindingFlags); } else if (member is MethodBase) { return TestAccessibility((MethodBase)member, bindingFlags); } else if (member is PropertyInfo) { return TestAccessibility((PropertyInfo)member, bindingFlags); } throw new Exception("Unexpected member type."); } private static bool TestAccessibility(FieldInfo member, PlayFab.Json.Utilities.BindingFlags bindingFlags) { bool visibility = (member.IsPublic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.Public)) || (!member.IsPublic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.NonPublic)); bool instance = (member.IsStatic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.Static)) || (!member.IsStatic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.Instance)); return visibility && instance; } private static bool TestAccessibility(MethodBase member, PlayFab.Json.Utilities.BindingFlags bindingFlags) { bool visibility = (member.IsPublic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.Public)) || (!member.IsPublic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.NonPublic)); bool instance = (member.IsStatic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.Static)) || (!member.IsStatic && bindingFlags.HasFlag(PlayFab.Json.Utilities.BindingFlags.Instance)); return visibility && instance; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } public static IEnumerable<Type> GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces; } public static IEnumerable<MethodInfo> GetMethods(this Type type) { return type.GetTypeInfo().DeclaredMethods; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsVisible(this Type type) { return type.GetTypeInfo().IsVisible; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) { Type current = type; while (current != null) { if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) { match = current; return true; } current = current.BaseType(); } foreach (Type i in type.GetInterfaces()) { if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) { match = type; return true; } } match = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName) { Type match; return type.AssignableToTypeName(fullTypeName, out match); } public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) { var methods = type.GetMethods().Where(method => method.Name == name); foreach (var method in methods) { if (method.HasParameters(parameterTypes)) return method; } return null; } public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes) { var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); if (methodParameters.Length != parameterTypes.Length) return false; for (int i = 0; i < methodParameters.Length; i++) if (methodParameters[i].ToString() != parameterTypes[i].ToString()) return false; return true; } public static IEnumerable<Type> GetAllInterfaces(this Type target) { foreach (var i in target.GetInterfaces()) { yield return i; foreach (var ci in i.GetInterfaces()) { yield return ci; } } } public static IEnumerable<MethodInfo> GetAllMethods(this Type target) { var allTypes = target.GetAllInterfaces().ToList(); allTypes.Add(target); return from type in allTypes from method in type.GetMethods() select method; } } } #endif
using System.Threading; using System.Collections; namespace Signum.Utilities; public static class Statics { static readonly Dictionary<string, IThreadVariable> threadVariables = new Dictionary<string, IThreadVariable>(); public static ThreadVariable<T> ThreadVariable<T>(string name, bool avoidExportImport = false) { var variable = new ThreadVariable<T>(name) { AvoidExportImport = avoidExportImport }; threadVariables.AddOrThrow(name, variable, "Thread variable {0} already defined"); return variable; } public static Dictionary<string, object?> ExportThreadContext(bool force = false) { return threadVariables.Where(t => !t.Value.IsClean && (!t.Value.AvoidExportImport || force)).ToDictionaryEx(kvp => kvp.Key, kvp => kvp.Value.UntypedValue); } public static IDisposable ImportThreadContext(Dictionary<string, object> context) { foreach (var kvp in threadVariables) { var val = context.TryGetC(kvp.Key); if (val != null) kvp.Value.UntypedValue = val; else kvp.Value.Clean(); } return new Disposable(() => { foreach (var v in threadVariables.Values) { v.Clean(); } }); } public static void CleanThreadContextAndAssert() { string errors = threadVariables.Values.Where(v => !v.IsClean).ToString(v => "{0} contains the non-default value {1}".FormatWith(v.Name, v.UntypedValue), "\r\n"); foreach (var v in threadVariables.Values) { v.Clean(); } if (errors.HasText()) throw new InvalidOperationException("The thread variable \r\n" + errors); } static readonly Dictionary<string, IUntypedVariable> sessionVariables = new Dictionary<string, IUntypedVariable>(); public static SessionVariable<T> SessionVariable<T>(string name) { var variable = SessionFactory.CreateVariable<T>(name); sessionVariables.AddOrThrow(name, variable, "Session variable {0} already defined"); return variable; } static ISessionFactory sessionFactory = new ScopeSessionFactory(new SingletonSessionFactory()); public static ISessionFactory SessionFactory { get { if (sessionFactory == null) throw new InvalidOperationException("Statics.SessionFactory not determined. (Tip: add a StaticSessionFactory, ScopeSessionFactory or AspNetSessionFactory)"); return sessionFactory; } set { sessionFactory = value; } } } public interface IUntypedVariable { string Name { get; } object? UntypedValue { get; set; } bool IsClean {get;} void Clean(); } public abstract class Variable<T> : IUntypedVariable { public string Name { get; private set; } public Variable(string name) { this.Name = name; } public abstract T Value { get; set; } public object? UntypedValue { get { return Value; } set { Value = (T)value!; } } public bool IsClean { get { if (Value == null) return true; if (Value.Equals(default(T)!)) return true; if (Value is IEnumerable col) { foreach (var item in col) { return false; } return true; } return false; } } public abstract void Clean(); } public interface IThreadVariable: IUntypedVariable { bool AvoidExportImport { get; } } public class ThreadVariable<T> : Variable<T>, IThreadVariable { readonly AsyncLocal<T> store = new AsyncLocal<T>(); internal ThreadVariable(string name) : base(name) { } public override T Value { get { return store.Value!; } set { store.Value = value; } } public bool AvoidExportImport { get; set; } public override void Clean() { Value = default!; } } public abstract class SessionVariable<T>: Variable<T> { public abstract Func<T>? ValueFactory { get; set; } protected internal SessionVariable(string name) : base(name) { } public T GetDefaulValue() { if (ValueFactory == null) return default!; Value = ValueFactory(); return Value; } } public interface ISessionFactory { SessionVariable<T> CreateVariable<T>(string name); } public class VoidSessionFactory : ISessionFactory { public SessionVariable<T> CreateVariable<T>(string name) { return new VoidVariable<T>(name); } class VoidVariable<T> : SessionVariable<T> { public override Func<T>? ValueFactory { get; set; } public VoidVariable(string name) : base(name) { } public override T Value { get { return default!; } set { throw new InvalidOperationException("No session found to set '{0}'".FormatWith(this.Name)); } } public override void Clean() { } } } public class SingletonSessionFactory : ISessionFactory { public static Dictionary<string, object?> singletonSession = new Dictionary<string, object?>(); public static Dictionary<string, object?> SingletonSession { get { return singletonSession; } set { singletonSession = value; } } public SessionVariable<T> CreateVariable<T>(string name) { return new SingletonVariable<T>(name); } class SingletonVariable<T> : SessionVariable<T> { public override Func<T>? ValueFactory { get; set; } public SingletonVariable(string name) : base(name) { } public override T Value { get { if (singletonSession.TryGetValue(Name, out object? result)) return (T)result!; return GetDefaulValue(); } set { singletonSession[Name] = value; } } public override void Clean() { singletonSession.Remove(Name); } } } public class ScopeSessionFactory : ISessionFactory { public ISessionFactory Factory; static readonly ThreadVariable<Dictionary<string, object?>> overridenSession = Statics.ThreadVariable<Dictionary<string, object?>>("overridenSession"); public static bool IsOverriden { get { return overridenSession.Value != null; } } public ScopeSessionFactory(ISessionFactory factory) { this.Factory = factory; } public static IDisposable OverrideSession() { return OverrideSession(new Dictionary<string, object?>()); } public static IDisposable OverrideSession(Dictionary<string, object?> sessionDictionary) { if (!(Statics.SessionFactory is ScopeSessionFactory)) throw new InvalidOperationException("Impossible to OverrideSession because Statics.SessionFactory is not a ScopeSessionFactory"); var old = overridenSession.Value; overridenSession.Value = sessionDictionary; return new Disposable(() => overridenSession.Value = old); } public SessionVariable<T> CreateVariable<T>(string name) { return new OverrideableVariable<T>(Factory.CreateVariable<T>(name)); } class OverrideableVariable<T> : SessionVariable<T> { readonly SessionVariable<T> variable; public OverrideableVariable(SessionVariable<T> variable) : base(variable.Name) { this.variable = variable; } public override Func<T>? ValueFactory { get { return variable.ValueFactory; } set { variable.ValueFactory = value; } } public override T Value { get { var dic = overridenSession.Value; if (dic != null) { if (dic.TryGetValue(Name, out object? result)) return (T)result!; return GetDefaulValue(); } else return variable.Value; } set { var dic = overridenSession.Value; if (dic != null) dic[Name] = value; else variable.Value = value; } } public override void Clean() { var dic = overridenSession.Value; if (dic != null) dic.Remove(Name); else variable.Clean(); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.Syndication.SyndicationFeedFormatter.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Syndication { abstract public partial class SyndicationFeedFormatter { #region Methods and constructors public abstract bool CanRead(System.Xml.XmlReader reader); protected internal static SyndicationCategory CreateCategory(SyndicationItem item) { return default(SyndicationCategory); } protected internal static SyndicationCategory CreateCategory(SyndicationFeed feed) { return default(SyndicationCategory); } protected abstract SyndicationFeed CreateFeedInstance(); protected internal static SyndicationItem CreateItem(SyndicationFeed feed) { return default(SyndicationItem); } protected internal static SyndicationLink CreateLink(SyndicationItem item) { return default(SyndicationLink); } protected internal static SyndicationLink CreateLink(SyndicationFeed feed) { return default(SyndicationLink); } protected internal static SyndicationPerson CreatePerson(SyndicationItem item) { return default(SyndicationPerson); } protected internal static SyndicationPerson CreatePerson(SyndicationFeed feed) { return default(SyndicationPerson); } protected internal static void LoadElementExtensions(System.Xml.XmlReader reader, SyndicationItem item, int maxExtensionSize) { } protected internal static void LoadElementExtensions(System.Xml.XmlReader reader, SyndicationCategory category, int maxExtensionSize) { } protected internal static void LoadElementExtensions(System.Xml.XmlReader reader, SyndicationLink link, int maxExtensionSize) { } protected internal static void LoadElementExtensions(System.Xml.XmlReader reader, SyndicationFeed feed, int maxExtensionSize) { } protected internal static void LoadElementExtensions(System.Xml.XmlReader reader, SyndicationPerson person, int maxExtensionSize) { } public abstract void ReadFrom(System.Xml.XmlReader reader); protected internal virtual new void SetFeed(SyndicationFeed feed) { } protected SyndicationFeedFormatter(SyndicationFeed feedToWrite) { } protected SyndicationFeedFormatter() { } protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version) { return default(bool); } protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version) { return default(bool); } protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version) { return default(bool); } protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version) { return default(bool); } protected internal static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version) { return default(bool); } protected internal static bool TryParseContent(System.Xml.XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content) { Contract.Requires(item != null); content = default(SyndicationContent); return default(bool); } protected internal static bool TryParseElement(System.Xml.XmlReader reader, SyndicationPerson person, string version) { return default(bool); } protected internal static bool TryParseElement(System.Xml.XmlReader reader, SyndicationLink link, string version) { return default(bool); } protected internal static bool TryParseElement(System.Xml.XmlReader reader, SyndicationFeed feed, string version) { return default(bool); } protected internal static bool TryParseElement(System.Xml.XmlReader reader, SyndicationItem item, string version) { return default(bool); } protected internal static bool TryParseElement(System.Xml.XmlReader reader, SyndicationCategory category, string version) { return default(bool); } protected internal static void WriteAttributeExtensions(System.Xml.XmlWriter writer, SyndicationLink link, string version) { } protected internal static void WriteAttributeExtensions(System.Xml.XmlWriter writer, SyndicationItem item, string version) { } protected internal static void WriteAttributeExtensions(System.Xml.XmlWriter writer, SyndicationFeed feed, string version) { } protected internal static void WriteAttributeExtensions(System.Xml.XmlWriter writer, SyndicationPerson person, string version) { } protected internal static void WriteAttributeExtensions(System.Xml.XmlWriter writer, SyndicationCategory category, string version) { } protected internal static void WriteElementExtensions(System.Xml.XmlWriter writer, SyndicationLink link, string version) { } protected internal static void WriteElementExtensions(System.Xml.XmlWriter writer, SyndicationPerson person, string version) { } protected internal static void WriteElementExtensions(System.Xml.XmlWriter writer, SyndicationItem item, string version) { } protected internal static void WriteElementExtensions(System.Xml.XmlWriter writer, SyndicationCategory category, string version) { } protected internal static void WriteElementExtensions(System.Xml.XmlWriter writer, SyndicationFeed feed, string version) { } public abstract void WriteTo(System.Xml.XmlWriter writer); #endregion #region Properties and indexers public SyndicationFeed Feed { get { return default(SyndicationFeed); } } public abstract string Version { get; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// // // Notes about EastAsianLunisolarCalendar // //////////////////////////////////////////////////////////////////////////// [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class EastAsianLunisolarCalendar : Calendar { internal const int LeapMonth = 0; internal const int Jan1Month = 1; internal const int Jan1Date = 2; internal const int nDaysPerMonth = 3; // # of days so far in the solar year internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // Return the type of the East Asian Lunisolar calendars. // public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.LunisolarCalendar; } } // Return the year number in the 60-year cycle. // public virtual int GetSexagenaryYear (DateTime time) { CheckTicksRange(time.Ticks); int year = 0, month = 0, day = 0; TimeToLunar(time, ref year, ref month, ref day); return ((year - 4) % 60) + 1; } // Return the celestial year from the 60-year cycle. // The returned value is from 1 ~ 10. // public int GetCelestialStem(int sexagenaryYear) { if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) { throw new ArgumentOutOfRangeException( "sexagenaryYear", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60)); } Contract.EndContractBlock(); return ((sexagenaryYear - 1) % 10) + 1; } // Return the Terrestial Branch from the the 60-year cycle. // The returned value is from 1 ~ 12. // public int GetTerrestrialBranch(int sexagenaryYear) { if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) { throw new ArgumentOutOfRangeException( "sexagenaryYear", Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60)); } Contract.EndContractBlock(); return ((sexagenaryYear - 1) % 12) + 1; } internal abstract int GetYearInfo(int LunarYear, int Index); internal abstract int GetYear(int year, DateTime time); internal abstract int GetGregorianYear(int year, int era); internal abstract int MinCalendarYear {get;} internal abstract int MaxCalendarYear {get;} internal abstract EraInfo[] CalEraInfo{get;} internal abstract DateTime MinDate {get;} internal abstract DateTime MaxDate {get;} internal const int MaxCalendarMonth = 13; internal const int MaxCalendarDay = 30; internal int MinEraCalendarYear (int era) { EraInfo[] mEraInfo = CalEraInfo; //ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null if (mEraInfo == null) { return MinCalendarYear; } if (era == Calendar.CurrentEra) { era = CurrentEraValue; } //era has to be in the supported range otherwise we will throw exception in CheckEraRange() if (era == GetEra(MinDate)) { return (GetYear(MinCalendarYear, MinDate)); } for (int i = 0; i < mEraInfo.Length; i++) { if (era == mEraInfo[i].era) { return (mEraInfo[i].minEraYear); } } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal int MaxEraCalendarYear (int era) { EraInfo[] mEraInfo = CalEraInfo; //ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null if (mEraInfo == null) { return MaxCalendarYear; } if (era == Calendar.CurrentEra) { era = CurrentEraValue; } //era has to be in the supported range otherwise we will throw exception in CheckEraRange() if (era == GetEra(MaxDate)) { return (GetYear(MaxCalendarYear, MaxDate)); } for (int i = 0; i < mEraInfo.Length; i++) { if (era == mEraInfo[i].era) { return (mEraInfo[i].maxEraYear); } } throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Construct an instance of EastAsianLunisolar calendar. internal EastAsianLunisolarCalendar() { } internal void CheckTicksRange(long ticks) { if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"), MinSupportedDateTime, MaxSupportedDateTime)); } Contract.EndContractBlock(); } internal void CheckEraRange (int era) { if (era == Calendar.CurrentEra) { era = CurrentEraValue; } if ((era <GetEra(MinDate)) || (era > GetEra(MaxDate))) { throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } internal int CheckYearRange(int year, int era) { CheckEraRange(era); year = GetGregorianYear(year, era); if ((year < MinCalendarYear) || (year > MaxCalendarYear)) { throw new ArgumentOutOfRangeException( "year", Environment.GetResourceString("ArgumentOutOfRange_Range", MinEraCalendarYear(era), MaxEraCalendarYear(era))); } return year; } internal int CheckYearMonthRange(int year, int month, int era) { year = CheckYearRange(year, era); if (month == 13) { //Reject if there is no leap month this year if (GetYearInfo(year , LeapMonth) == 0) throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } if (month < 1 || month > 13) { throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); } return year; } internal int InternalGetDaysInMonth(int year, int month) { int nDays; int mask; // mask for extracting bits mask = 0x8000; // convert the lunar day into a lunar month/date mask >>= (month-1); if ((GetYearInfo(year, nDaysPerMonth) & mask)== 0) nDays = 29; else nDays = 30; return nDays; } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { year = CheckYearMonthRange(year, month, era); return InternalGetDaysInMonth(year, month); } static int GregorianIsLeapYear(int y) { return ((((y)%4)!=0)?0:((((y)%100)!=0)?1:((((y)%400)!=0)?0:1))); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = CheckYearMonthRange(year, month, era); int daysInMonth = InternalGetDaysInMonth(year, month); if (day < 1 || day > daysInMonth) { BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day); throw new ArgumentOutOfRangeException( "day", Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month)); } int gy=0; int gm=0; int gd=0; if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd)) { return new DateTime(gy, gm, gd, hour, minute, second, millisecond); } else { throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay")); } } // // GregorianToLunar calculates lunar calendar info for the given gregorian year, month, date. // The input date should be validated before calling this method. // internal void GregorianToLunar(int nSYear, int nSMonth, int nSDate, ref int nLYear, ref int nLMonth, ref int nLDate) { // unsigned int nLYear, nLMonth, nLDate; // lunar ymd int nSolarDay; // day # in solar year int nLunarDay; // day # in lunar year int fLeap; // is it a solar leap year? int LDpM; // lunar days/month bitfield int mask; // mask for extracting bits int nDays; // # days this lunar month int nJan1Month, nJan1Date; // calc the solar day of year fLeap = GregorianIsLeapYear(nSYear); nSolarDay = (fLeap==1) ? DaysToMonth366[nSMonth-1]: DaysToMonth365[nSMonth-1] ; nSolarDay += nSDate; // init lunar year info nLunarDay = nSolarDay; nLYear = nSYear; if (nLYear == (MaxCalendarYear + 1)) { nLYear--; nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365); nJan1Month = GetYearInfo(nLYear, Jan1Month); nJan1Date = GetYearInfo(nLYear,Jan1Date); } else { nJan1Month = GetYearInfo(nLYear, Jan1Month); nJan1Date = GetYearInfo(nLYear,Jan1Date); // check if this solar date is actually part of the previous // lunar year if ((nSMonth < nJan1Month) || (nSMonth == nJan1Month && nSDate < nJan1Date)) { // the corresponding lunar day is actually part of the previous // lunar year nLYear--; // add a solar year to the lunar day # nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365); // update the new start of year nJan1Month = GetYearInfo(nLYear, Jan1Month); nJan1Date = GetYearInfo(nLYear, Jan1Date); } } // convert solar day into lunar day. // subtract off the beginning part of the solar year which is not // part of the lunar year. since this part is always in Jan or Feb, // we don't need to handle Leap Year (LY only affects March // and later). nLunarDay -= DaysToMonth365[nJan1Month-1]; nLunarDay -= (nJan1Date - 1); // convert the lunar day into a lunar month/date mask = 0x8000; LDpM = GetYearInfo(nLYear, nDaysPerMonth); nDays = ((LDpM & mask) != 0) ? 30 : 29; nLMonth = 1; while (nLunarDay > nDays) { nLunarDay -= nDays; nLMonth++; mask >>= 1; nDays = ((LDpM & mask) != 0) ? 30 : 29; } nLDate = nLunarDay; } /* //Convert from Lunar to Gregorian //Highly inefficient, but it works based on the forward conversion */ internal bool LunarToGregorian(int nLYear, int nLMonth, int nLDate, ref int nSolarYear, ref int nSolarMonth, ref int nSolarDay) { int numLunarDays; if (nLDate < 1 || nLDate > 30) return false; numLunarDays = nLDate-1; //Add previous months days to form the total num of days from the first of the month. for (int i = 1; i < nLMonth; i++) { numLunarDays += InternalGetDaysInMonth(nLYear, i); } //Get Gregorian First of year int nJan1Month = GetYearInfo(nLYear, Jan1Month); int nJan1Date = GetYearInfo(nLYear, Jan1Date); // calc the solar day of year of 1 Lunar day int fLeap = GregorianIsLeapYear(nLYear); int[] days = (fLeap==1)? DaysToMonth366: DaysToMonth365; nSolarDay = nJan1Date; if (nJan1Month > 1) nSolarDay += days [nJan1Month-1]; // Add the actual lunar day to get the solar day we want nSolarDay = nSolarDay + numLunarDays;// - 1; if ( nSolarDay > (fLeap + 365)) { nSolarYear = nLYear + 1; nSolarDay -= (fLeap + 365); } else { nSolarYear = nLYear; } for (nSolarMonth = 1; nSolarMonth < 12; nSolarMonth++) { if (days[nSolarMonth] >= nSolarDay) break; } nSolarDay -= days[nSolarMonth-1]; return true; } internal DateTime LunarToTime(DateTime time, int year, int month, int day) { int gy=0; int gm=0; int gd=0; LunarToGregorian(year, month, day, ref gy, ref gm, ref gd); return (GregorianCalendar.GetDefaultInstance().ToDateTime(gy,gm,gd,time.Hour,time.Minute,time.Second,time.Millisecond)); } internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day) { int gy=0; int gm=0; int gd=0; Calendar Greg = GregorianCalendar.GetDefaultInstance(); gy = Greg.GetYear(time); gm = Greg.GetMonth(time); gd = Greg.GetDayOfMonth(time); GregorianToLunar(gy, gm, gd, ref year, ref month, ref day); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( "months", Environment.GetResourceString("ArgumentOutOfRange_Range", -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y=0; int m=0; int d=0; TimeToLunar(time, ref y, ref m, ref d); int i = m + months; if (i > 0) { int monthsInYear = InternalIsLeapYear(y)?13:12; while (i-monthsInYear > 0) { i -= monthsInYear; y++; monthsInYear = InternalIsLeapYear(y)?13:12; } m = i; } else { int monthsInYear; while (i <= 0) { monthsInYear = InternalIsLeapYear(y-1)?13:12; i += monthsInYear; y--; } m = i; } int days = InternalGetDaysInMonth(y, m); if (d > days) { d = days; } DateTime dt = LunarToTime(time, y, m, d); CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return (dt); } public override DateTime AddYears(DateTime time, int years) { CheckTicksRange(time.Ticks); int y=0; int m=0; int d=0; TimeToLunar(time, ref y, ref m, ref d); y += years; if (m==13 && !InternalIsLeapYear(y)) { m = 12; d = InternalGetDaysInMonth(y, m); } int DaysInMonths = InternalGetDaysInMonth(y, m); if (d > DaysInMonths) { d = DaysInMonths; } DateTime dt = LunarToTime(time, y, m, d); CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return (dt); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and [354|355 |383|384]. // public override int GetDayOfYear(DateTime time) { CheckTicksRange(time.Ticks); int y=0; int m=0; int d=0; TimeToLunar(time, ref y, ref m, ref d); for (int i=1; i<m ;i++) { d = d + InternalGetDaysInMonth(y, i); } return d; } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 29 or 30. // public override int GetDayOfMonth(DateTime time) { CheckTicksRange(time.Ticks); int y=0; int m=0; int d=0; TimeToLunar(time, ref y, ref m, ref d); return d; } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { year = CheckYearRange(year, era); int Days = 0; int monthsInYear = InternalIsLeapYear(year) ? 13 : 12; while (monthsInYear != 0) Days += InternalGetDaysInMonth(year, monthsInYear--); return Days; } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 13. // public override int GetMonth(DateTime time) { CheckTicksRange(time.Ticks); int y=0; int m=0; int d=0; TimeToLunar(time, ref y, ref m, ref d); return m; } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and MaxCalendarYear. // public override int GetYear(DateTime time) { CheckTicksRange(time.Ticks); int y=0; int m=0; int d=0; TimeToLunar(time, ref y, ref m, ref d); return GetYear(y, time); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((int)(time.Ticks / Calendar.TicksPerDay + 1) % 7)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { year = CheckYearRange(year, era); return (InternalIsLeapYear(year)?13:12); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { year = CheckYearMonthRange(year, month, era); int daysInMonth = InternalGetDaysInMonth(year, month); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( "day", Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month)); } int m = GetYearInfo(year, LeapMonth); return ((m!=0) && (month == (m+1))); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { year = CheckYearMonthRange(year, month, era); int m = GetYearInfo(year, LeapMonth); return ((m!=0) && (month == (m+1))); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this this year is not a leap year. // public override int GetLeapMonth(int year, int era) { year = CheckYearRange(year, era); int month = GetYearInfo(year, LeapMonth); if (month>0) { return (month+1); } return 0; } internal bool InternalIsLeapYear(int year) { return (GetYearInfo(year, LeapMonth)!=0); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { year = CheckYearRange(year, era); return InternalIsLeapYear(year); } private const int DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(BaseCalendarID, GetYear(new DateTime(DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX, 1, 1))); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( "value", Environment.GetResourceString("ArgumentOutOfRange_Range", 99, MaxCalendarYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); year = base.ToFourDigitYear(year); CheckYearRange(year, CurrentEra); return (year); } } }
/* * 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. */ // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Tests.Cache.Query { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Queries tests. /// </summary> public class CacheQueriesTest { /** Grid count. */ private const int GridCnt = 2; /** Cache name. */ private const string CacheName = "cache"; /** Path to XML configuration. */ private const string CfgPath = "Config\\cache-query.xml"; /** Maximum amount of items in cache. */ private const int MaxItemCnt = 100; /// <summary> /// Fixture setup. /// </summary> [TestFixtureSetUp] public void StartGrids() { for (int i = 0; i < GridCnt; i++) { Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { BinaryConfiguration = new BinaryConfiguration { NameMapper = GetNameMapper() }, SpringConfigUrl = CfgPath, IgniteInstanceName = "grid-" + i }); } } /// <summary> /// Gets the name mapper. /// </summary> protected virtual IBinaryNameMapper GetNameMapper() { return new BinaryBasicNameMapper {IsSimpleName = false}; } /// <summary> /// Fixture teardown. /// </summary> [TestFixtureTearDown] public void StopGrids() { Ignition.StopAll(true); } /// <summary> /// /// </summary> [SetUp] public void BeforeTest() { Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// /// </summary> [TearDown] public void AfterTest() { var cache = Cache(); for (int i = 0; i < GridCnt; i++) { cache.Clear(); Assert.IsTrue(cache.IsEmpty()); } TestUtils.AssertHandleRegistryIsEmpty(300, Enumerable.Range(0, GridCnt).Select(x => Ignition.GetIgnite("grid-" + x)).ToArray()); Console.WriteLine("Test finished: " + TestContext.CurrentContext.Test.Name); } /// <summary> /// Gets the ignite. /// </summary> private static IIgnite GetIgnite() { return Ignition.GetIgnite("grid-0"); } /// <summary> /// /// </summary> /// <returns></returns> private static ICache<int, QueryPerson> Cache() { return GetIgnite().GetCache<int, QueryPerson>(CacheName); } /// <summary> /// Test arguments validation for SQL queries. /// </summary> [Test] public void TestValidationSql() { // 1. No sql. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlQuery(typeof(QueryPerson), null)); }); // 2. No type. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlQuery((string)null, "age >= 50")); }); } /// <summary> /// Test arguments validation for SQL fields queries. /// </summary> [Test] public void TestValidationSqlFields() { // 1. No sql. Assert.Throws<ArgumentException>(() => { Cache().Query(new SqlFieldsQuery(null)); }); } /// <summary> /// Test arguments validation for TEXT queries. /// </summary> [Test] public void TestValidationText() { // 1. No text. Assert.Throws<ArgumentException>(() => { Cache().Query(new TextQuery(typeof(QueryPerson), null)); }); // 2. No type. Assert.Throws<ArgumentException>(() => { Cache().Query(new TextQuery((string)null, "Ivanov")); }); } /// <summary> /// Cursor tests. /// </summary> [Test] [SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")] public void TestCursor() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(1, new QueryPerson("Petrov", 40)); Cache().Put(1, new QueryPerson("Sidorov", 50)); SqlQuery qry = new SqlQuery(typeof(QueryPerson), "age >= 20"); // 1. Test GetAll(). using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { cursor.GetAll(); Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); }); Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); }); } // 2. Test GetEnumerator. using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { cursor.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { cursor.GetAll(); }); Assert.Throws<InvalidOperationException>(() => { cursor.GetEnumerator(); }); } } /// <summary> /// Test enumerator. /// </summary> [Test] [SuppressMessage("ReSharper", "UnusedVariable")] public void TestEnumerator() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); Cache().Put(4, new QueryPerson("Unknown", 60)); // 1. Empty result set. using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age = 100"))) { IEnumerator<ICacheEntry<int, QueryPerson>> e = cursor.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { ICacheEntry<int, QueryPerson> entry = e.Current; }); Assert.IsFalse(e.MoveNext()); Assert.Throws<InvalidOperationException>(() => { ICacheEntry<int, QueryPerson> entry = e.Current; }); Assert.Throws<NotSupportedException>(() => e.Reset()); e.Dispose(); } SqlQuery qry = new SqlQuery(typeof (QueryPerson), "age < 60"); Assert.AreEqual(QueryBase.DefaultPageSize, qry.PageSize); // 2. Page size is bigger than result set. qry.PageSize = 4; CheckEnumeratorQuery(qry); // 3. Page size equal to result set. qry.PageSize = 3; CheckEnumeratorQuery(qry); // 4. Page size if less than result set. qry.PageSize = 2; CheckEnumeratorQuery(qry); } /// <summary> /// Test SQL query arguments passing. /// </summary> [Test] public void TestSqlQueryArguments() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); // 1. Empty result set. using ( IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(new SqlQuery(typeof(QueryPerson), "age < ?", 50))) { foreach (ICacheEntry<int, QueryPerson> entry in cursor.GetAll()) Assert.IsTrue(entry.Key == 1 || entry.Key == 2); } } /// <summary> /// Test SQL fields query arguments passing. /// </summary> [Test] public void TestSqlFieldsQueryArguments() { Cache().Put(1, new QueryPerson("Ivanov", 30)); Cache().Put(2, new QueryPerson("Petrov", 40)); Cache().Put(3, new QueryPerson("Sidorov", 50)); // 1. Empty result set. using (var cursor = Cache().Query(new SqlFieldsQuery("SELECT age FROM QueryPerson WHERE age < ?", 50))) { foreach (var entry in cursor.GetAll()) Assert.IsTrue((int) entry[0] < 50); } } /// <summary> /// Check query result for enumerator test. /// </summary> /// <param name="qry">QUery.</param> private void CheckEnumeratorQuery(SqlQuery qry) { using (IQueryCursor<ICacheEntry<int, QueryPerson>> cursor = Cache().Query(qry)) { bool first = false; bool second = false; bool third = false; foreach (var entry in cursor) { if (entry.Key == 1) { first = true; Assert.AreEqual("Ivanov", entry.Value.Name); Assert.AreEqual(30, entry.Value.Age); } else if (entry.Key == 2) { second = true; Assert.AreEqual("Petrov", entry.Value.Name); Assert.AreEqual(40, entry.Value.Age); } else if (entry.Key == 3) { third = true; Assert.AreEqual("Sidorov", entry.Value.Name); Assert.AreEqual(50, entry.Value.Age); } else Assert.Fail("Unexpected value: " + entry); } Assert.IsTrue(first && second && third); } } /// <summary> /// Check SQL query. /// </summary> [Test] public void TestSqlQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary, [Values(true, false)] bool distrJoin) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, MaxItemCnt, x => x < 50); // 2. Validate results. var qry = new SqlQuery(typeof(QueryPerson), "age < 50", loc) { EnableDistributedJoins = distrJoin, #pragma warning disable 618 ReplicatedOnly = false, #pragma warning restore 618 Timeout = TimeSpan.FromSeconds(3) }; Assert.AreEqual(string.Format("SqlQuery [Sql=age < 50, Arguments=[], Local={0}, " + "PageSize=1024, EnableDistributedJoins={1}, Timeout={2}, " + "ReplicatedOnly=False]", loc, distrJoin, qry.Timeout), qry.ToString()); ValidateQueryResults(cache, qry, exp, keepBinary); } /// <summary> /// Check SQL fields query. /// </summary> [Test] public void TestSqlFieldsQuery([Values(true, false)] bool loc, [Values(true, false)] bool distrJoin, [Values(true, false)] bool enforceJoinOrder, [Values(true, false)] bool lazy) { int cnt = MaxItemCnt; var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, cnt, x => x < 50); // 2. Validate results. var qry = new SqlFieldsQuery("SELECT name, age FROM QueryPerson WHERE age < 50") { EnableDistributedJoins = distrJoin, EnforceJoinOrder = enforceJoinOrder, Colocated = !distrJoin, #pragma warning disable 618 ReplicatedOnly = false, #pragma warning restore 618 Local = loc, Timeout = TimeSpan.FromSeconds(2), Lazy = lazy }; using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); foreach (var entry in cursor.GetAll()) { Assert.AreEqual(2, entry.Count); Assert.AreEqual(entry[0].ToString(), entry[1].ToString()); exp0.Remove((int)entry[1]); } Assert.AreEqual(0, exp0.Count); Assert.AreEqual(new[] {"NAME", "AGE"}, cursor.FieldNames); } // Test old API as well. #pragma warning disable 618 using (var cursor = cache.QueryFields(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); foreach (var entry in cursor) { Assert.AreEqual(entry[0].ToString(), entry[1].ToString()); exp0.Remove((int)entry[1]); } Assert.AreEqual(0, exp0.Count); } #pragma warning restore 618 } /// <summary> /// Tests that query configuration propagates from Spring XML correctly. /// </summary> [Test] public void TestQueryConfiguration() { var qe = Cache().GetConfiguration().QueryEntities.Single(); Assert.AreEqual(typeof(QueryPerson).FullName, qe.ValueTypeName); var age = qe.Fields.First(); Assert.AreEqual("age", age.Name); Assert.AreEqual(typeof(int), age.FieldType); Assert.IsFalse(age.IsKeyField); var name = qe.Fields.Last(); Assert.AreEqual("name", name.Name); Assert.AreEqual(typeof(string), name.FieldType); Assert.IsFalse(name.IsKeyField); var textIdx = qe.Indexes.First(); Assert.AreEqual(QueryIndexType.FullText, textIdx.IndexType); Assert.AreEqual("name", textIdx.Fields.Single().Name); Assert.AreEqual(QueryIndex.DefaultInlineSize, textIdx.InlineSize); var sqlIdx = qe.Indexes.Last(); Assert.AreEqual(QueryIndexType.Sorted, sqlIdx.IndexType); Assert.AreEqual("age", sqlIdx.Fields.Single().Name); Assert.AreEqual(2345, sqlIdx.InlineSize); } /// <summary> /// Check text query. /// </summary> [Test] public void TestTextQuery([Values(true, false)] bool loc, [Values(true, false)] bool keepBinary) { var cache = Cache(); // 1. Populate cache with data, calculating expected count in parallel. var exp = PopulateCache(cache, loc, MaxItemCnt, x => x.ToString().StartsWith("1")); // 2. Validate results. var qry = new TextQuery(typeof(QueryPerson), "1*", loc); ValidateQueryResults(cache, qry, exp, keepBinary); } /// <summary> /// Check scan query. /// </summary> [Test] public void TestScanQuery([Values(true, false)] bool loc) { CheckScanQuery<QueryPerson>(loc, false); } /// <summary> /// Check scan query in binary mode. /// </summary> [Test] public void TestScanQueryBinary([Values(true, false)] bool loc) { CheckScanQuery<IBinaryObject>(loc, true); } /// <summary> /// Check scan query with partitions. /// </summary> [Test] public void TestScanQueryPartitions([Values(true, false)] bool loc) { CheckScanQueryPartitions<QueryPerson>(loc, false); } /// <summary> /// Check scan query with partitions in binary mode. /// </summary> [Test] public void TestScanQueryPartitionsBinary([Values(true, false)] bool loc) { CheckScanQueryPartitions<IBinaryObject>(loc, true); } /// <summary> /// Tests that query attempt on non-indexed cache causes an exception. /// </summary> [Test] public void TestIndexingDisabledError() { var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>("nonindexed_cache"); // Text query. var err = Assert.Throws<IgniteException>(() => cache.Query(new TextQuery(typeof(QueryPerson), "1*"))); Assert.AreEqual("Indexing is disabled for cache: nonindexed_cache. " + "Use setIndexedTypes or setTypeMetadata methods on CacheConfiguration to enable.", err.Message); // SQL query. err = Assert.Throws<IgniteException>(() => cache.Query(new SqlQuery(typeof(QueryPerson), "age < 50"))); Assert.AreEqual("Failed to find SQL table for type: QueryPerson", err.Message); } /// <summary> /// Check scan query. /// </summary> /// <param name="loc">Local query flag.</param> /// <param name="keepBinary">Keep binary flag.</param> private static void CheckScanQuery<TV>(bool loc, bool keepBinary) { var cache = Cache(); int cnt = MaxItemCnt; // No predicate var exp = PopulateCache(cache, loc, cnt, x => true); var qry = new ScanQuery<int, TV>(); ValidateQueryResults(cache, qry, exp, keepBinary); // Serializable exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()); ValidateQueryResults(cache, qry, exp, keepBinary); // Binarizable exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new BinarizableScanQueryFilter<TV>()); ValidateQueryResults(cache, qry, exp, keepBinary); // Invalid exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new InvalidScanQueryFilter<TV>()); Assert.Throws<BinaryObjectException>(() => ValidateQueryResults(cache, qry, exp, keepBinary)); // Exception exp = PopulateCache(cache, loc, cnt, x => x < 50); qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV> {ThrowErr = true}); var ex = Assert.Throws<IgniteException>(() => ValidateQueryResults(cache, qry, exp, keepBinary)); Assert.AreEqual(ScanQueryFilter<TV>.ErrMessage, ex.Message); } /// <summary> /// Checks scan query with partitions. /// </summary> /// <param name="loc">Local query flag.</param> /// <param name="keepBinary">Keep binary flag.</param> private void CheckScanQueryPartitions<TV>(bool loc, bool keepBinary) { StopGrids(); StartGrids(); var cache = Cache(); int cnt = MaxItemCnt; var aff = cache.Ignite.GetAffinity(CacheName); var exp = PopulateCache(cache, loc, cnt, x => true); // populate outside the loop (slow) for (var part = 0; part < aff.Partitions; part++) { //var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys var exp0 = new HashSet<int>(); foreach (var x in exp) if (aff.GetPartition(x) == part) exp0.Add(x); var qry = new ScanQuery<int, TV> { Partition = part }; ValidateQueryResults(cache, qry, exp0, keepBinary); } // Partitions with predicate exp = PopulateCache(cache, loc, cnt, x => x < 50); // populate outside the loop (slow) for (var part = 0; part < aff.Partitions; part++) { //var exp0 = new HashSet<int>(exp.Where(x => aff.Partition(x) == part)); // filter expected keys var exp0 = new HashSet<int>(); foreach (var x in exp) if (aff.GetPartition(x) == part) exp0.Add(x); var qry = new ScanQuery<int, TV>(new ScanQueryFilter<TV>()) { Partition = part }; ValidateQueryResults(cache, qry, exp0, keepBinary); } } /// <summary> /// Tests custom schema name. /// </summary> [Test] public void TestCustomSchema() { var doubles = GetIgnite().GetOrCreateCache<int, double>(new CacheConfiguration("doubles", new QueryEntity(typeof(int), typeof(double)))); var strings = GetIgnite().GetOrCreateCache<int, string>(new CacheConfiguration("strings", new QueryEntity(typeof(int), typeof(string)))); doubles[1] = 36.6; strings[1] = "foo"; // Default schema. var res = doubles.Query(new SqlFieldsQuery( "select S._val from double as D join \"strings\".string as S on S._key = D._key")) .Select(x => (string) x[0]) .Single(); Assert.AreEqual("foo", res); // Custom schema. res = doubles.Query(new SqlFieldsQuery( "select S._val from \"doubles\".double as D join string as S on S._key = D._key") { Schema = strings.Name }) .Select(x => (string)x[0]) .Single(); Assert.AreEqual("foo", res); } /// <summary> /// Tests the distributed joins flag. /// </summary> [Test] public void TestDistributedJoins() { var cache = GetIgnite().GetOrCreateCache<int, QueryPerson>( new CacheConfiguration("replicatedCache") { QueryEntities = new[] { new QueryEntity(typeof(int), typeof(QueryPerson)) { Fields = new[] {new QueryField("age", "int")} } } }); const int count = 100; cache.PutAll(Enumerable.Range(0, count).ToDictionary(x => x, x => new QueryPerson("Name" + x, x))); // Test non-distributed join: returns partial results var sql = "select T0.Age from QueryPerson as T0 " + "inner join QueryPerson as T1 on ((? - T1.Age - 1) = T0._key)"; var res = cache.Query(new SqlFieldsQuery(sql, count)).GetAll().Distinct().Count(); Assert.Greater(res, 0); Assert.Less(res, count); // Test distributed join: returns complete results res = cache.Query(new SqlFieldsQuery(sql, count) {EnableDistributedJoins = true}) .GetAll().Distinct().Count(); Assert.AreEqual(count, res); } /// <summary> /// Tests the get configuration. /// </summary> [Test] public void TestGetConfiguration() { var entity = Cache().GetConfiguration().QueryEntities.Single(); var ageField = entity.Fields.Single(x => x.Name == "age"); Assert.AreEqual(typeof(int), ageField.FieldType); Assert.IsFalse(ageField.NotNull); Assert.IsFalse(ageField.IsKeyField); var nameField = entity.Fields.Single(x => x.Name == "name"); Assert.AreEqual(typeof(string), nameField.FieldType); Assert.IsTrue(nameField.NotNull); Assert.IsFalse(nameField.IsKeyField); } /// <summary> /// Tests custom key and value field names. /// </summary> [Test] public void TestCustomKeyValueFieldNames() { // Check select * with default config - does not include _key, _val. var cache = Cache(); cache[1] = new QueryPerson("Joe", 48); var row = cache.Query(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0]; Assert.AreEqual(2, row.Count); Assert.AreEqual(48, row[0]); Assert.AreEqual("Joe", row[1]); // Check select * with custom names - fields are included. cache = GetIgnite().GetOrCreateCache<int, QueryPerson>( new CacheConfiguration("customKeyVal") { QueryEntities = new[] { new QueryEntity(typeof(int), typeof(QueryPerson)) { Fields = new[] { new QueryField("age", "int"), new QueryField("FullKey", "int"), new QueryField("FullVal", "QueryPerson") }, KeyFieldName = "FullKey", ValueFieldName = "FullVal" } } }); cache[1] = new QueryPerson("John", 33); row = cache.Query(new SqlFieldsQuery("select * from QueryPerson")).GetAll()[0]; Assert.AreEqual(3, row.Count); Assert.AreEqual(33, row[0]); Assert.AreEqual(1, row[1]); var person = (QueryPerson) row[2]; Assert.AreEqual("John", person.Name); // Check explicit select. row = cache.Query(new SqlFieldsQuery("select FullKey from QueryPerson")).GetAll()[0]; Assert.AreEqual(1, row[0]); } /// <summary> /// Tests query timeouts. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestSqlQueryTimeout() { var cache = Cache(); PopulateCache(cache, false, 30000, x => true); var sqlQry = new SqlQuery(typeof(QueryPerson), "WHERE age < 2000") { Timeout = TimeSpan.FromMilliseconds(1) }; // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var ex = Assert.Throws<CacheException>(() => cache.Query(sqlQry).ToArray()); Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing.")); } /// <summary> /// Tests fields query timeouts. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestSqlFieldsQueryTimeout() { var cache = Cache(); PopulateCache(cache, false, 20000, x => true); var fieldsQry = new SqlFieldsQuery("SELECT * FROM QueryPerson WHERE age < 5000 AND name like '%0%'") { Timeout = TimeSpan.FromMilliseconds(3) }; // ReSharper disable once ReturnValueOfPureMethodIsNotUsed var ex = Assert.Throws<CacheException>(() => cache.Query(fieldsQry).ToArray()); Assert.IsTrue(ex.ToString().Contains("QueryCancelledException: The query was cancelled while executing.")); } /// <summary> /// Tests the FieldNames property. /// </summary> [Test] public void TestFieldNames() { var cache = Cache(); PopulateCache(cache, false, 5, x => true); // Get before iteration. var qry = new SqlFieldsQuery("SELECT * FROM QueryPerson"); var cur = cache.Query(qry); var names = cur.FieldNames; Assert.AreEqual(new[] {"AGE", "NAME" }, names); cur.Dispose(); Assert.AreSame(names, cur.FieldNames); Assert.Throws<NotSupportedException>(() => cur.FieldNames.Add("x")); // Custom order, key-val, get after iteration. qry.Sql = "SELECT NAME, _key, AGE, _val FROM QueryPerson"; cur = cache.Query(qry); cur.GetAll(); Assert.AreEqual(new[] { "NAME", "_KEY", "AGE", "_VAL" }, cur.FieldNames); // Get after disposal. qry.Sql = "SELECT 1, AGE FROM QueryPerson"; cur = cache.Query(qry); cur.Dispose(); Assert.AreEqual(new[] { "1", "AGE" }, cur.FieldNames); } /// <summary> /// Validates the query results. /// </summary> /// <param name="cache">Cache.</param> /// <param name="qry">Query.</param> /// <param name="exp">Expected keys.</param> /// <param name="keepBinary">Keep binary flag.</param> private static void ValidateQueryResults(ICache<int, QueryPerson> cache, QueryBase qry, HashSet<int> exp, bool keepBinary) { if (keepBinary) { var cache0 = cache.WithKeepBinary<int, IBinaryObject>(); using (var cursor = cache0.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor.GetAll()) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name")); Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age")); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } using (var cursor = cache0.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.GetField<string>("name")); Assert.AreEqual(entry.Key, entry.Value.GetField<int>("age")); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } } else { using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor.GetAll()) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Name); Assert.AreEqual(entry.Key, entry.Value.Age); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } using (var cursor = cache.Query(qry)) { HashSet<int> exp0 = new HashSet<int>(exp); var all = new List<ICacheEntry<int, object>>(); foreach (var entry in cursor) { all.Add(entry); Assert.AreEqual(entry.Key.ToString(), entry.Value.Name); Assert.AreEqual(entry.Key, entry.Value.Age); exp0.Remove(entry.Key); } AssertMissingExpectedKeys(exp0, cache, all); } } } /// <summary> /// Asserts that all expected entries have been received. /// </summary> private static void AssertMissingExpectedKeys(ICollection<int> exp, ICache<int, QueryPerson> cache, IList<ICacheEntry<int, object>> all) { if (exp.Count == 0) return; var sb = new StringBuilder(); var aff = cache.Ignite.GetAffinity(cache.Name); foreach (var key in exp) { var part = aff.GetPartition(key); sb.AppendFormat( "Query did not return expected key '{0}' (exists: {1}), partition '{2}', partition nodes: ", key, cache.Get(key) != null, part); var partNodes = aff.MapPartitionToPrimaryAndBackups(part); foreach (var node in partNodes) sb.Append(node).Append(" "); sb.AppendLine(";"); } sb.Append("Returned keys: "); foreach (var e in all) sb.Append(e.Key).Append(" "); sb.AppendLine(";"); Assert.Fail(sb.ToString()); } /// <summary> /// Populates the cache with random entries and returns expected results set according to filter. /// </summary> /// <param name="cache">The cache.</param> /// <param name="cnt">Amount of cache entries to create.</param> /// <param name="loc">Local query flag.</param> /// <param name="expectedEntryFilter">The expected entry filter.</param> /// <returns>Expected results set.</returns> private static HashSet<int> PopulateCache(ICache<int, QueryPerson> cache, bool loc, int cnt, Func<int, bool> expectedEntryFilter) { var rand = new Random(); for (var i = 0; i < cnt; i++) { var val = rand.Next(cnt); cache.Put(val, new QueryPerson(val.ToString(), val)); } var entries = loc ? cache.GetLocalEntries(CachePeekMode.Primary) : cache; return new HashSet<int>(entries.Select(x => x.Key).Where(expectedEntryFilter)); } } /// <summary> /// Person. /// </summary> public class QueryPerson { /// <summary> /// Constructor. /// </summary> /// <param name="name">Name.</param> /// <param name="age">Age.</param> public QueryPerson(string name, int age) { Name = name; Age = age % 2000; Birthday = DateTime.UtcNow.AddYears(-Age); } /// <summary> /// Name. /// </summary> public string Name { get; set; } /// <summary> /// Age. /// </summary> public int Age { get; set; } /// <summary> /// Gets or sets the birthday. /// </summary> [QuerySqlField] // Enforce Timestamp serialization public DateTime Birthday { get; set; } } /// <summary> /// Query filter. /// </summary> [Serializable] public class ScanQueryFilter<TV> : ICacheEntryFilter<int, TV> { // Error message public const string ErrMessage = "Error in ScanQueryFilter.Invoke"; // Error flag public bool ThrowErr { get; set; } // Injection test [InstanceResource] public IIgnite Ignite { get; set; } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, TV> entry) { Assert.IsNotNull(Ignite); if (ThrowErr) throw new Exception(ErrMessage); return entry.Key < 50; } } /// <summary> /// binary query filter. /// </summary> public class BinarizableScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable { /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { var w = writer.GetRawWriter(); w.WriteBoolean(ThrowErr); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { var r = reader.GetRawReader(); ThrowErr = r.ReadBoolean(); } } /// <summary> /// Filter that can't be serialized. /// </summary> public class InvalidScanQueryFilter<TV> : ScanQueryFilter<TV>, IBinarizable { public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } }
// Copyright (c) Charles Weld // This code is distributed under the GNU LGPL (for details please see ~\Documentation\license.txt) using System; using System.Collections; using System.Collections.Generic; namespace Airion.Common.Collections { public abstract class ListCollectionWrapperBase : IList { #region Fields protected int age = 0; protected TriState isReadonly = TriState.NotAssigned; protected TriState isFixedSize = TriState.NotAssigned; protected int count = 0; #endregion #region Constructors public ListCollectionWrapperBase() { } #endregion #region IList public object this[int index] { get { CheckIndex(index); int relativeIndex; IList currentList = ListAt(index, out relativeIndex); return currentList[relativeIndex]; } set { age++; CheckIndex(index); int relativeIndex; IList currentList = ListAt(index, out relativeIndex); currentList[relativeIndex] = value; } } public virtual bool IsReadOnly { get { if(isReadonly == TriState.NotAssigned) { // readonly if any inner list is readonly or if there are no inner list bool hasReadonlyList = false; bool hasInnerList = false; foreach(IList innerList in GetWrappedLists()) { hasInnerList = true; if(innerList.IsReadOnly) { hasReadonlyList = true; break; } } isReadonly = (hasInnerList && !hasReadonlyList) ? TriState.False : TriState.True; } return isReadonly == TriState.True; } } public virtual bool IsFixedSize { get { if(isFixedSize == TriState.NotAssigned) { // readonly if any inner list is readonly or if there are no inner list bool hasFixedSizeList = false; bool hasInnerList = false; foreach(IList innerList in GetWrappedLists()) { hasInnerList = true; if(innerList.IsFixedSize) { hasFixedSizeList = true; break; } } isFixedSize = (hasInnerList && !hasFixedSizeList) ? TriState.False : TriState.True; } return isFixedSize == TriState.True; } } public virtual int Count { get { if(count == -1) { count = 0; foreach(IList innerList in GetWrappedLists()) { count += innerList.Count; } } return count; } } public object SyncRoot { get { throw new NotSupportedException("Synchronization not supported."); } } public bool IsSynchronized { get { throw new NotSupportedException("Synchronization not supported."); } } public int Add(object value) { CheckModifiablity(true); int offset; IList list; if(GetLastWrappedList(out list, out offset)) { age++; return offset + list.Add(value); } else { throw new NotSupportedException("Doesn't contain any internal lists."); } } public bool Contains(object value) { return IndexOf(value) != -1; } public virtual void Clear() { CheckModifiablity(true); int ageBefore = age; foreach(IList list in GetWrappedLists()) { list.Clear(); } count = 0; CheckAge(ageBefore); age++; } public int IndexOf(object value) { int ageBefore = age; IList list; int index; if(FindList(value, out list, out index)) { CheckAge(ageBefore); return index; } return -1; } public void Insert(int index, object value) { CheckIndex(index); CheckModifiablity(true); int ageBefore = age; int relativeIndex; IList list; if(ListAt(index, out list, out relativeIndex)) { list.Insert(relativeIndex, value); CheckAge(ageBefore); age++; } else { throw new InvalidOperationException("Collection modified asynchronously."); } } public void Remove(object value) { CheckModifiablity(true); int indexOf = IndexOf(value); if(indexOf != -1) { RemoveAt(indexOf); } } public void RemoveAt(int index) { CheckModifiablity(true); CheckIndex(index); int ageBefore = age; int relativeIndex; IList list; if(ListAt(index, out list, out relativeIndex)) { list.RemoveAt(relativeIndex); CheckAge(ageBefore); age++; } else { throw new InvalidOperationException("Collection modified asynchronously."); } } public void CopyTo(Array array, int index) { // check conditions if(array == null) throw new ArgumentNullException("array"); if(index < 0 || index >= array.Length) throw new ArgumentOutOfRangeException("index", index, String.Format("Index must be between 0 and the array's length ({1}).", array.Length)); if(array.Rank != 1) throw new ArgumentException("Array must not be multi-dimensional.", "array"); if(Count > (array.Length - index)) throw new ArgumentException("The specified array must be large enough to fit in all items."); int ageBefore = age; foreach(object item in this) { array.SetValue(item, index++); } CheckAge(ageBefore); } public IEnumerator GetEnumerator() { return new Enumerator(this); } #endregion #region Underlying list access routines /// <summary> /// Forces the the list collection wrapper to reset it's internal trackers (i.e. resynchronize with the list). /// </summary> public void Refresh() { isReadonly = TriState.NotAssigned; isFixedSize = TriState.NotAssigned; count = -1; age++; } protected IList ListAt(int index) { int relativeIndex; return ListAt(index, out relativeIndex); } protected virtual IList ListAt(int index, out int relativeIndex) { if(index >= 0) { int offset = 0; foreach(IList innerList in GetWrappedLists()) { if(index < offset + innerList.Count) { relativeIndex = index - offset; return innerList; } } throw new ArgumentOutOfRangeException("index", index, String.Format("Index must be between 0 and {0}.", Count)); } else { throw new ArgumentOutOfRangeException("index", index, String.Format("Index must be between 0 and {0}.", Count)); } } protected virtual bool ListAt(int index, out IList list, out int relativeIndex) { list = null; relativeIndex = -1; if(index >= 0) { int offset = 0; foreach(IList innerList in GetWrappedLists()) { if(index < offset + innerList.Count) { list = innerList; relativeIndex = index - offset; return true; } } return false; } else { return false; } } protected virtual bool FindList(object value, out IList list, out int index) { list = null; index = -1; int offset = 0; foreach(IList innerList in GetWrappedLists()) { int relativeIndex = innerList.IndexOf(value); if(relativeIndex != -1) { index = offset + relativeIndex; list = innerList; return true; } index += innerList.Count; } return false; } protected virtual bool GetLastWrappedList(out IList list, out int offset) { list = null; offset = -1; foreach(IList innerList in GetWrappedLists()) { list = innerList; offset += innerList.Count; } if(list != null) { offset -= list.Count; return true; } else { return false; } } protected abstract IEnumerable<IList> GetWrappedLists(); protected void CheckModifiablity(bool changingSize) { if(IsReadOnly) { throw new NotSupportedException("Cannot modify a readonly collection."); } if(changingSize && IsFixedSize) { throw new NotSupportedException("Cannot change a fixed size collection's size."); } } protected void CheckIndex(int index) { if(index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", index, String.Format("Index must be between 0 and {0}.", Count)); } protected void CheckAge(int ageBefore) { if(ageBefore != age) { throw new InvalidOperationException("Collection was modified in a unsychronized manner."); } } #endregion #region Inner Classes protected enum TriState { True, False, NotAssigned } public class Enumerator : IEnumerator { #region Fields private ListCollectionWrapperBase listCollection; private int index; private int startAge; #endregion #region Constructors public Enumerator(ListCollectionWrapperBase listCollection) { this.listCollection = listCollection; this.index = -1; this.startAge = listCollection.age; } #endregion #region Members public object Current { get { listCollection.CheckIndex(index); listCollection.CheckAge(startAge); int relativeIndex; IList list; if(listCollection.ListAt(index, out list, out relativeIndex)) { return list[relativeIndex]; } else { throw new InvalidOperationException("Collection was modified."); } } } public bool MoveNext() { listCollection.CheckAge(startAge); if(index <= listCollection.Count) { index++; } return index >= 0 && index < listCollection.Count; } public void Reset() { listCollection.CheckAge(startAge); index = -1; } #endregion } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Content.Server.Atmos.Components; using Content.Server.Atmos.EntitySystems; using Content.Server.Hands.Components; using Content.Server.Nutrition.Components; using Content.Server.Storage.Components; using Content.Server.Stunnable; using Content.Server.Throwing; using Content.Server.Tools.Components; using Content.Shared.Camera; using Content.Shared.CombatMode; using Content.Shared.Interaction; using Content.Shared.Item; using Content.Shared.PneumaticCannon; using Content.Shared.Popups; using Content.Shared.StatusEffect; using Content.Shared.Verbs; using Robust.Shared.Audio; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Maths; using Robust.Shared.Player; using Robust.Shared.Random; namespace Content.Server.PneumaticCannon { public sealed class PneumaticCannonSystem : EntitySystem { [Dependency] private readonly IRobustRandom _random = default!; [Dependency] private readonly StunSystem _stun = default!; [Dependency] private readonly AtmosphereSystem _atmos = default!; [Dependency] private readonly CameraRecoilSystem _cameraRecoil = default!; private HashSet<PneumaticCannonComponent> _currentlyFiring = new(); public override void Initialize() { base.Initialize(); SubscribeLocalEvent<PneumaticCannonComponent, ComponentInit>(OnComponentInit); SubscribeLocalEvent<PneumaticCannonComponent, InteractUsingEvent>(OnInteractUsing); SubscribeLocalEvent<PneumaticCannonComponent, AfterInteractEvent>(OnAfterInteract); SubscribeLocalEvent<PneumaticCannonComponent, GetVerbsEvent<AlternativeVerb>>(OnAlternativeVerbs); SubscribeLocalEvent<PneumaticCannonComponent, GetVerbsEvent<Verb>>(OnOtherVerbs); } public override void Update(float frameTime) { base.Update(frameTime); if (_currentlyFiring.Count == 0) return; foreach (var comp in _currentlyFiring.ToArray()) { if (comp.FireQueue.Count == 0) { _currentlyFiring.Remove(comp); // reset acc frametime to the fire interval if we're instant firing if (comp.InstantFire) { comp.AccumulatedFrametime = comp.FireInterval; } else { comp.AccumulatedFrametime = 0f; } return; } comp.AccumulatedFrametime += frameTime; if (comp.AccumulatedFrametime > comp.FireInterval) { var dat = comp.FireQueue.Dequeue(); Fire(comp, dat); comp.AccumulatedFrametime -= comp.FireInterval; } } } private void OnComponentInit(EntityUid uid, PneumaticCannonComponent component, ComponentInit args) { component.GasTankSlot = component.Owner.EnsureContainer<ContainerSlot>($"{component.Name}-gasTank"); if (component.InstantFire) component.AccumulatedFrametime = component.FireInterval; } private void OnInteractUsing(EntityUid uid, PneumaticCannonComponent component, InteractUsingEvent args) { args.Handled = true; if (EntityManager.HasComponent<GasTankComponent>(args.Used) && component.GasTankSlot.CanInsert(args.Used) && component.GasTankRequired) { component.GasTankSlot.Insert(args.Used); args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-gas-tank-insert", ("tank", args.Used), ("cannon", component.Owner))); UpdateAppearance(component); return; } if (EntityManager.TryGetComponent<ToolComponent?>(args.Used, out var tool)) { if (tool.Qualities.Contains(component.ToolModifyMode)) { // this is kind of ugly but it just cycles the enum var val = (int) component.Mode; val = (val + 1) % (int) PneumaticCannonFireMode.Len; component.Mode = (PneumaticCannonFireMode) val; args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-change-fire-mode", ("mode", component.Mode.ToString()))); // sound return; } if (tool.Qualities.Contains(component.ToolModifyPower)) { var val = (int) component.Power; val = (val + 1) % (int) PneumaticCannonPower.Len; component.Power = (PneumaticCannonPower) val; args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-change-power", ("power", component.Power.ToString()))); // sound return; } } // this overrides the ServerStorageComponent's insertion stuff because // it's not event-based yet and I can't cancel it, so tools and stuff // will modify mode/power then get put in anyway if (EntityManager.TryGetComponent<SharedItemComponent?>(args.Used, out var item) && EntityManager.TryGetComponent<ServerStorageComponent?>(component.Owner, out var storage)) { if (storage.CanInsert(args.Used)) { storage.Insert(args.Used); args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-insert-item-success", ("item", args.Used), ("cannon", component.Owner))); } else { args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-insert-item-failure", ("item", args.Used), ("cannon", component.Owner))); } } } private void OnAfterInteract(EntityUid uid, PneumaticCannonComponent component, AfterInteractEvent args) { if (EntityManager.TryGetComponent<SharedCombatModeComponent>(uid, out var combat) && !combat.IsInCombatMode) return; args.Handled = true; if (!HasGas(component) && component.GasTankRequired) { args.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-fire-no-gas", ("cannon", component.Owner))); SoundSystem.Play(Filter.Pvs(args.Used), "/Audio/Items/hiss.ogg", args.Used, AudioParams.Default); return; } AddToQueue(component, args.User, args.ClickLocation); } public void AddToQueue(PneumaticCannonComponent comp, EntityUid user, EntityCoordinates click) { if (!EntityManager.TryGetComponent<ServerStorageComponent?>(comp.Owner, out var storage)) return; if (storage.StoredEntities == null) return; if (storage.StoredEntities.Count == 0) { SoundSystem.Play(Filter.Pvs((comp).Owner), "/Audio/Weapons/click.ogg", ((IComponent) comp).Owner, AudioParams.Default); return; } _currentlyFiring.Add(comp); int entCounts = comp.Mode switch { PneumaticCannonFireMode.All => storage.StoredEntities.Count, PneumaticCannonFireMode.Single => 1, _ => 0 }; for (int i = 0; i < entCounts; i++) { var dir = (click.ToMapPos(EntityManager) - EntityManager.GetComponent<TransformComponent>(user).WorldPosition).Normalized; var randomAngle = GetRandomFireAngleFromPower(comp.Power).RotateVec(dir); var randomStrengthMult = _random.NextFloat(0.75f, 1.25f); var throwMult = GetRangeMultFromPower(comp.Power); var data = new PneumaticCannonComponent.FireData { User = user, Strength = comp.ThrowStrength * randomStrengthMult, Direction = (dir + randomAngle).Normalized * comp.BaseThrowRange * throwMult, }; comp.FireQueue.Enqueue(data); } } public void Fire(PneumaticCannonComponent comp, PneumaticCannonComponent.FireData data) { if (!HasGas(comp) && comp.GasTankRequired) { data.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-fire-no-gas", ("cannon", comp.Owner))); SoundSystem.Play(Filter.Pvs(((IComponent) comp).Owner), "/Audio/Items/hiss.ogg", ((IComponent) comp).Owner, AudioParams.Default); return; } if (!EntityManager.TryGetComponent<ServerStorageComponent?>(comp.Owner, out var storage)) return; if (Deleted(data.User)) return; if (storage.StoredEntities == null) return; if (storage.StoredEntities.Count == 0) return; // click sound? var ent = _random.Pick(storage.StoredEntities); storage.Remove(ent); SoundSystem.Play(Filter.Pvs(data.User), comp.FireSound.GetSound(), ((IComponent) comp).Owner, AudioParams.Default); if (EntityManager.HasComponent<CameraRecoilComponent>(data.User)) { var kick = Vector2.One * data.Strength; _cameraRecoil.KickCamera(data.User, kick); } ent.TryThrow(data.Direction, data.Strength, data.User, GetPushbackRatioFromPower(comp.Power)); // lasagna, anybody? ent.EnsureComponent<ForcefeedOnCollideComponent>(); if(EntityManager.TryGetComponent<StatusEffectsComponent?>(data.User, out var status) && comp.Power == PneumaticCannonPower.High) { _stun.TryParalyze(data.User, TimeSpan.FromSeconds(comp.HighPowerStunTime), true, status); data.User.PopupMessage(Loc.GetString("pneumatic-cannon-component-power-stun", ("cannon", comp.Owner))); } if (comp.GasTankSlot.ContainedEntity is {Valid: true} contained && comp.GasTankRequired) { // we checked for this earlier in HasGas so a GetComp is okay var gas = EntityManager.GetComponent<GasTankComponent>(contained); var environment = _atmos.GetTileMixture(EntityManager.GetComponent<TransformComponent>(comp.Owner).Coordinates, true); var removed = gas.RemoveAir(GetMoleUsageFromPower(comp.Power)); if (environment != null && removed != null) { _atmos.Merge(environment, removed); } } } /// <summary> /// Returns whether the pneumatic cannon has enough gas to shoot an item. /// </summary> public bool HasGas(PneumaticCannonComponent component) { var usage = GetMoleUsageFromPower(component.Power); if (component.GasTankSlot.ContainedEntity is not {Valid: true } contained) return false; // not sure how it wouldnt, but it might not! who knows if (EntityManager.TryGetComponent<GasTankComponent?>(contained, out var tank)) { if (tank.Air.TotalMoles < usage) return false; return true; } return false; } private void OnAlternativeVerbs(EntityUid uid, PneumaticCannonComponent component, GetVerbsEvent<AlternativeVerb> args) { if (component.GasTankSlot.ContainedEntities.Count == 0 || !component.GasTankRequired) return; if (!args.CanInteract) return; AlternativeVerb ejectTank = new(); ejectTank.Act = () => TryRemoveGasTank(component, args.User); ejectTank.Text = Loc.GetString("pneumatic-cannon-component-verb-gas-tank-name"); args.Verbs.Add(ejectTank); } private void OnOtherVerbs(EntityUid uid, PneumaticCannonComponent component, GetVerbsEvent<Verb> args) { if (!args.CanInteract) return; Verb ejectItems = new(); ejectItems.Act = () => TryEjectAllItems(component, args.User); ejectItems.Text = Loc.GetString("pneumatic-cannon-component-verb-eject-items-name"); args.Verbs.Add(ejectItems); } public void TryRemoveGasTank(PneumaticCannonComponent component, EntityUid user) { if (component.GasTankSlot.ContainedEntity is not {Valid: true} contained) { user.PopupMessage(Loc.GetString("pneumatic-cannon-component-gas-tank-none", ("cannon", component.Owner))); return; } if (component.GasTankSlot.Remove(contained)) { if (EntityManager.TryGetComponent<HandsComponent?>(user, out var hands)) { hands.PutInHand(contained); } user.PopupMessage(Loc.GetString("pneumatic-cannon-component-gas-tank-remove", ("tank", contained), ("cannon", component.Owner))); UpdateAppearance(component); } } public void TryEjectAllItems(PneumaticCannonComponent component, EntityUid user) { if (EntityManager.TryGetComponent<ServerStorageComponent?>(component.Owner, out var storage)) { if (storage.StoredEntities == null) return; foreach (var entity in storage.StoredEntities.ToArray()) { storage.Remove(entity); } user.PopupMessage(Loc.GetString("pneumatic-cannon-component-ejected-all", ("cannon", (component.Owner)))); } } private void UpdateAppearance(PneumaticCannonComponent component) { if (EntityManager.TryGetComponent<AppearanceComponent?>(component.Owner, out var appearance)) { appearance.SetData(PneumaticCannonVisuals.Tank, component.GasTankSlot.ContainedEntities.Count != 0); } } private Angle GetRandomFireAngleFromPower(PneumaticCannonPower power) { return power switch { PneumaticCannonPower.High => _random.NextAngle(-0.3, 0.3), PneumaticCannonPower.Medium => _random.NextAngle(-0.2, 0.2), PneumaticCannonPower.Low or _ => _random.NextAngle(-0.1, 0.1), }; } private float GetRangeMultFromPower(PneumaticCannonPower power) { return power switch { PneumaticCannonPower.High => 1.6f, PneumaticCannonPower.Medium => 1.3f, PneumaticCannonPower.Low or _ => 1.0f, }; } private float GetMoleUsageFromPower(PneumaticCannonPower power) { return power switch { PneumaticCannonPower.High => 9f, PneumaticCannonPower.Medium => 6f, PneumaticCannonPower.Low or _ => 3f, }; } private float GetPushbackRatioFromPower(PneumaticCannonPower power) { return power switch { PneumaticCannonPower.Medium => 8.0f, PneumaticCannonPower.High => 16.0f, PneumaticCannonPower.Low or _ => 0f }; } } }
namespace Mapbox.IO.Compression { using System; using System.Diagnostics; // Strictly speaking this class is not a HuffmanTree, this class is // a lookup table combined with a HuffmanTree. The idea is to speed up // the lookup for short symbols (they should appear more frequently ideally.) // However we don't want to create a huge table since it might take longer to // build the table than decoding (Deflate usually generates new tables frequently.) // // Jean-loup Gailly and Mark Adler gave a very good explanation about this. // The full text (algorithm.txt) can be found inside // ftp://ftp.uu.net/pub/archiving/zip/zlib/zlib.zip. // // Following paper explains decoding in details: // Hirschberg and Lelewer, "Efficient decoding of prefix codes," // Comm. ACM, 33,4, April 1990, pp. 449-459. // internal class HuffmanTree { internal const int MaxLiteralTreeElements = 288; internal const int MaxDistTreeElements = 32; internal const int EndOfBlockCode = 256; internal const int NumberOfCodeLengthTreeElements = 19; int tableBits; short[] table; short[] left; short[] right; byte[] codeLengthArray; #if DEBUG #pragma warning disable 0414 uint[] codeArrayDebug; #pragma warning restore 0414 #endif int tableMask; // huffman tree for static block static HuffmanTree staticLiteralLengthTree; static HuffmanTree staticDistanceTree; static HuffmanTree() { // construct the static literal tree and distance tree staticLiteralLengthTree = new HuffmanTree(GetStaticLiteralTreeLength()); staticDistanceTree = new HuffmanTree(GetStaticDistanceTreeLength()); } static public HuffmanTree StaticLiteralLengthTree { get { return staticLiteralLengthTree; } } static public HuffmanTree StaticDistanceTree { get { return staticDistanceTree; } } public HuffmanTree(byte[] codeLengths) { Debug.Assert( codeLengths.Length == MaxLiteralTreeElements || codeLengths.Length == MaxDistTreeElements || codeLengths.Length == NumberOfCodeLengthTreeElements, "we only expect three kinds of Length here"); codeLengthArray = codeLengths; if (codeLengthArray.Length == MaxLiteralTreeElements) { // bits for Literal/Length tree table tableBits = 9; } else { // bits for distance tree table and code length tree table tableBits = 7; } tableMask = (1 << tableBits) -1; CreateTable(); } // Generate the array contains huffman codes lengths for static huffman tree. // The data is in RFC 1951. static byte[] GetStaticLiteralTreeLength() { byte[] literalTreeLength = new byte[MaxLiteralTreeElements]; for (int i = 0; i <= 143; i++) literalTreeLength[i] = 8; for (int i = 144; i <= 255; i++) literalTreeLength[i] = 9; for (int i = 256; i <= 279; i++) literalTreeLength[i] = 7; for (int i = 280; i <= 287; i++) literalTreeLength[i] = 8; return literalTreeLength; } static byte[] GetStaticDistanceTreeLength() { byte[] staticDistanceTreeLength = new byte[MaxDistTreeElements]; for (int i = 0; i < MaxDistTreeElements; i++) { staticDistanceTreeLength[i] = 5; } return staticDistanceTreeLength; } // Calculate the huffman code for each character based on the code length for each character. // This algorithm is described in standard RFC 1951 uint[] CalculateHuffmanCode() { uint[] bitLengthCount = new uint[17]; foreach( int codeLength in codeLengthArray) { bitLengthCount[codeLength]++; } bitLengthCount[0] = 0; // clear count for length 0 uint[] nextCode = new uint[17]; uint tempCode = 0; for (int bits = 1; bits <= 16; bits++) { tempCode = (tempCode + bitLengthCount[bits-1]) << 1; nextCode[bits] = tempCode; } uint[] code = new uint[MaxLiteralTreeElements]; for (int i = 0; i < codeLengthArray.Length; i++) { int len = codeLengthArray[i]; if (len > 0) { code[i] = FastEncoderStatics.BitReverse(nextCode[len], len); nextCode[len]++; } } return code; } private void CreateTable() { uint[] codeArray = CalculateHuffmanCode(); table = new short[ 1 << tableBits]; #if DEBUG codeArrayDebug = codeArray; #endif // I need to find proof that left and right array will always be // enough. I think they are. left = new short[2* codeLengthArray.Length]; right = new short[2* codeLengthArray.Length]; short avail = (short)codeLengthArray.Length; for (int ch = 0; ch < codeLengthArray.Length; ch++) { // length of this code int len = codeLengthArray[ch]; if (len > 0) { // start value (bit reversed) int start = (int)codeArray[ch]; if (len <= tableBits) { // If a particular symbol is shorter than nine bits, // then that symbol's translation is duplicated // in all those entries that start with that symbol's bits. // For example, if the symbol is four bits, then it's duplicated // 32 times in a nine-bit table. If a symbol is nine bits long, // it appears in the table once. // // Make sure that in the loop below, code is always // less than table_size. // // On last iteration we store at array index: // initial_start_at + (locs-1)*increment // = initial_start_at + locs*increment - increment // = initial_start_at + (1 << tableBits) - increment // = initial_start_at + table_size - increment // // Therefore we must ensure: // initial_start_at + table_size - increment < table_size // or: initial_start_at < increment // int increment = 1 << len; if (start >= increment) { throw new InvalidDataException(SR.GetString(SR.InvalidHuffmanData)); } // Note the bits in the table are reverted. int locs = 1 << (tableBits - len); for (int j = 0; j < locs; j++) { table[start] = (short) ch; start += increment; } } else { // For any code which has length longer than num_elements, // build a binary tree. int overflowBits = len - tableBits; // the nodes we need to respent the data. int codeBitMask = 1 << tableBits; // mask to get current bit (the bits can't fit in the table) // the left, right table is used to repesent the // the rest bits. When we got the first part (number bits.) and look at // tbe table, we will need to follow the tree to find the real character. // This is in place to avoid bloating the table if there are // a few ones with long code. int index = start & ((1 << tableBits) -1); short[] array = table; do { short value = array[index]; if (value == 0) { // set up next pointer if this node is not used before. array[index] = (short)-avail; // use next available slot. value = (short)-avail; avail++; } if (value > 0) { // prevent an IndexOutOfRangeException from array[index] throw new InvalidDataException(SR.GetString(SR.InvalidHuffmanData)); } Debug.Assert( value < 0, "CreateTable: Only negative numbers are used for tree pointers!"); if ((start & codeBitMask) == 0) { // if current bit is 0, go change the left array array = left; } else { // if current bit is 1, set value in the right array array = right; } index = -value; // go to next node codeBitMask <<= 1; overflowBits--; } while (overflowBits != 0); array[index] = (short) ch; } } } } // // This function will try to get enough bits from input and // try to decode the bits. // If there are no enought bits in the input, this function will return -1. // public int GetNextSymbol(InputBuffer input) { // Try to load 16 bits into input buffer if possible and get the bitBuffer value. // If there aren't 16 bits available we will return all we have in the // input buffer. uint bitBuffer = input.TryLoad16Bits(); if( input.AvailableBits == 0) { // running out of input. return -1; } // decode an element int symbol = table[bitBuffer & tableMask]; if( symbol < 0) { // this will be the start of the binary tree // navigate the tree uint mask = (uint)1 << tableBits; do { symbol = -symbol; if ((bitBuffer & mask) == 0) symbol = left[symbol]; else symbol = right[symbol]; mask <<= 1; } while (symbol < 0); } int codeLength = codeLengthArray[symbol]; // huffman code lengths must be at least 1 bit long if (codeLength <= 0) { throw new InvalidDataException(SR.GetString(SR.InvalidHuffmanData)); } // // If this code is longer than the # bits we had in the bit buffer (i.e. // we read only part of the code), we can hit the entry in the table or the tree // for another symbol. However the length of another symbol will not match the // available bits count. if (codeLength > input.AvailableBits) { // We already tried to load 16 bits and maximum length is 15, // so this means we are running out of input. return -1; } input.SkipBits(codeLength); return symbol; } } }
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 PowerBIRestDemo.Areas.HelpPage.ModelDescriptions; using PowerBIRestDemo.Areas.HelpPage.Models; namespace PowerBIRestDemo.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); } } } }
// 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.Linq; using System.Security.Cryptography.Asn1; using System.Security.Cryptography.Pkcs.Asn1; using System.Security.Cryptography.X509Certificates; using Internal.Cryptography; namespace System.Security.Cryptography.Pkcs { public sealed class Rfc3161TimestampTokenInfo { private readonly byte[] _encodedBytes; private readonly Rfc3161TstInfo _parsedData; private ReadOnlyMemory<byte>? _tsaNameBytes; public Rfc3161TimestampTokenInfo( Oid policyId, Oid hashAlgorithmId, ReadOnlyMemory<byte> messageHash, ReadOnlyMemory<byte> serialNumber, DateTimeOffset timestamp, long? accuracyInMicroseconds = null, bool isOrdering = false, ReadOnlyMemory<byte>? nonce = null, ReadOnlyMemory<byte>? tsaName = null, X509ExtensionCollection extensions = null) { _encodedBytes = Encode( policyId, hashAlgorithmId, messageHash, serialNumber, timestamp, isOrdering, accuracyInMicroseconds, nonce, tsaName, extensions); if (!TryDecode(_encodedBytes, true, out _parsedData, out _, out _)) { Debug.Fail("Unable to decode the data we encoded"); throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } private Rfc3161TimestampTokenInfo(byte[] copiedBytes, Rfc3161TstInfo tstInfo) { _encodedBytes = copiedBytes; _parsedData = tstInfo; } public int Version => _parsedData.Version; public Oid PolicyId => _parsedData.Policy; public Oid HashAlgorithmId => _parsedData.MessageImprint.HashAlgorithm.Algorithm; public ReadOnlyMemory<byte> GetMessageHash() => _parsedData.MessageImprint.HashedMessage; public ReadOnlyMemory<byte> GetSerialNumber() => _parsedData.SerialNumber; public DateTimeOffset Timestamp => _parsedData.GenTime; public long? AccuracyInMicroseconds => _parsedData.Accuracy?.TotalMicros; public bool IsOrdering => _parsedData.Ordering; public ReadOnlyMemory<byte>? GetNonce() => _parsedData.Nonce; public bool HasExtensions => _parsedData.Extensions?.Length > 0; public ReadOnlyMemory<byte>? GetTimestampAuthorityName() { if (_tsaNameBytes == null) { GeneralNameAsn? tsaName = _parsedData.Tsa; if (tsaName == null) { return null; } using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { tsaName.Value.Encode(writer); _tsaNameBytes = writer.Encode(); Debug.Assert(_tsaNameBytes.HasValue); } } return _tsaNameBytes.Value; } public X509ExtensionCollection GetExtensions() { var coll = new X509ExtensionCollection(); if (!HasExtensions) { return coll; } X509ExtensionAsn[] rawExtensions = _parsedData.Extensions; foreach (X509ExtensionAsn rawExtension in rawExtensions) { X509Extension extension = new X509Extension( rawExtension.ExtnId, rawExtension.ExtnValue.ToArray(), rawExtension.Critical); // Currently there are no extensions defined. // Should this dip into CryptoConfig or other extensible // mechanisms for the CopyTo rich type uplift? coll.Add(extension); } return coll; } public byte[] Encode() { return _encodedBytes.CloneByteArray(); } public bool TryEncode(Span<byte> destination, out int bytesWritten) { if (destination.Length < _encodedBytes.Length) { bytesWritten = 0; return false; } _encodedBytes.AsSpan().CopyTo(destination); bytesWritten = _encodedBytes.Length; return true; } public static bool TryDecode( ReadOnlyMemory<byte> source, out Rfc3161TimestampTokenInfo timestampTokenInfo, out int bytesConsumed) { if (TryDecode(source, false, out Rfc3161TstInfo tstInfo, out bytesConsumed, out byte[] copiedBytes)) { timestampTokenInfo = new Rfc3161TimestampTokenInfo(copiedBytes, tstInfo); return true; } bytesConsumed = 0; timestampTokenInfo = null; return false; } private static bool TryDecode( ReadOnlyMemory<byte> source, bool ownsMemory, out Rfc3161TstInfo tstInfo, out int bytesConsumed, out byte[] copiedBytes) { // https://tools.ietf.org/html/rfc3161#section-2.4.2 // The eContent SHALL be the DER-encoded value of TSTInfo. AsnReader reader = new AsnReader(source, AsnEncodingRules.DER); try { ReadOnlyMemory<byte> firstElement = reader.PeekEncodedValue(); if (ownsMemory) { copiedBytes = null; } else { // Copy the data so no ReadOnlyMemory values are pointing back to user data. copiedBytes = firstElement.ToArray(); firstElement = copiedBytes; } Rfc3161TstInfo parsedInfo = Rfc3161TstInfo.Decode(firstElement, AsnEncodingRules.DER); // The deserializer doesn't do bounds checks. // Micros and Millis are defined as (1..999) // Seconds doesn't define that it's bounded by 0, // but negative accuracy doesn't make sense. // // (Reminder to readers: a null int? with an inequality operator // has the value false, so if accuracy is missing, or millis or micro is missing, // then the respective checks return false and don't throw). if (parsedInfo.Accuracy?.Micros > 999 || parsedInfo.Accuracy?.Micros < 1 || parsedInfo.Accuracy?.Millis > 999 || parsedInfo.Accuracy?.Millis < 1 || parsedInfo.Accuracy?.Seconds < 0) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } tstInfo = parsedInfo; bytesConsumed = firstElement.Length; return true; } catch (CryptographicException) { tstInfo = default; bytesConsumed = 0; copiedBytes = null; return false; } } private static byte[] Encode( Oid policyId, Oid hashAlgorithmId, ReadOnlyMemory<byte> messageHash, ReadOnlyMemory<byte> serialNumber, DateTimeOffset timestamp, bool isOrdering, long? accuracyInMicroseconds, ReadOnlyMemory<byte>? nonce, ReadOnlyMemory<byte>? tsaName, X509ExtensionCollection extensions) { if (policyId == null) throw new ArgumentNullException(nameof(policyId)); if (hashAlgorithmId == null) throw new ArgumentNullException(nameof(hashAlgorithmId)); var tstInfo = new Rfc3161TstInfo { // The only legal value as of 2017. Version = 1, Policy = policyId, MessageImprint = { HashAlgorithm = { Algorithm = hashAlgorithmId, Parameters = AlgorithmIdentifierAsn.ExplicitDerNull, }, HashedMessage = messageHash, }, SerialNumber = serialNumber, GenTime = timestamp, Ordering = isOrdering, Nonce = nonce, }; if (accuracyInMicroseconds != null) { tstInfo.Accuracy = new Rfc3161Accuracy(accuracyInMicroseconds.Value); } if (tsaName != null) { tstInfo.Tsa = GeneralNameAsn.Decode(tsaName.Value, AsnEncodingRules.DER); } if (extensions != null) { tstInfo.Extensions = extensions.OfType<X509Extension>(). Select(ex => new X509ExtensionAsn(ex)).ToArray(); } using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { tstInfo.Encode(writer); return writer.Encode(); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using System.Text; namespace Cuemon.Data { /// <summary> /// The DataManager is an abstract class in the <see cref="Data"/> namespace that can be used to implement execute commands of different database providers. /// </summary> public abstract class DataManager { #region Constructors #endregion #region Properties /// <summary> /// Gets the string used to open the connection. /// </summary> /// <value>The connection string used to establish the initial connection. The exact contents of the connection string depend on the specific data source for this connection.</value> public abstract string ConnectionString { get; } /// <summary> /// Gets or sets the default connection string. /// </summary> /// <value>The default connection string.</value> public static string DefaultConnectionString { get; set; } #endregion #region Methods /// <summary> /// Parses and returns a <see cref="Type"/> equivalent of <paramref name="dbType"/>. /// </summary> /// <param name="dbType">The <see cref="DbType"/> to parse.</param> /// <returns>A <see cref="Type"/> equivalent of <paramref name="dbType"/>.</returns> public static Type ParseDbType(DbType dbType) { switch (dbType) { case DbType.Byte: case DbType.SByte: return typeof(byte); case DbType.Binary: return typeof(byte[]); case DbType.Boolean: return typeof(bool); case DbType.Currency: case DbType.Double: return typeof(double); case DbType.Date: case DbType.DateTime: case DbType.Time: case DbType.DateTimeOffset: case DbType.DateTime2: return typeof(DateTime); case DbType.Guid: return typeof(Guid); case DbType.Int64: return typeof(long); case DbType.Int32: return typeof(int); case DbType.Int16: return typeof(short); case DbType.Object: return typeof(object); case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.StringFixedLength: case DbType.String: return typeof(string); case DbType.Single: return typeof(float); case DbType.UInt64: return typeof(ulong); case DbType.UInt32: return typeof(uint); case DbType.UInt16: return typeof(ushort); case DbType.Decimal: case DbType.VarNumeric: return typeof(decimal); case DbType.Xml: return typeof(string); } throw new ArgumentOutOfRangeException(nameof(dbType), string.Format(CultureInfo.InvariantCulture, "Type, '{0}', is unsupported.", dbType)); } /// <summary> /// Creates and returns a <see cref="KeyValuePair{TKey,TValue}"/> sequence of column names and values resolved from the specified <paramref name="reader"/>. /// </summary> /// <param name="reader">The reader to resolve column names and values from.</param> /// <returns>A <see cref="KeyValuePair{TKey,TValue}"/> sequence of column names and values resolved from the specified <paramref name="reader"/>.</returns> public static IEnumerable<KeyValuePair<string, object>> GetReaderColumns(DbDataReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } if (reader.IsClosed) { throw new ArgumentException("Reader is closed.", nameof(reader)); } return GetReaderColumnsIterator(reader); } private static IEnumerable<KeyValuePair<string, object>> GetReaderColumnsIterator(DbDataReader reader) { for (var f = 0; f < reader.FieldCount; f++) { yield return new KeyValuePair<string, object>(reader.GetName(f), reader.GetValue(f)); } } /// <summary> /// Converts the given <see cref="DbDataReader"/> compatible object to a stream. /// Note: DbDataReader must return only one field (for instance, a XML field), otherwise an exception is thrown! /// </summary> /// <param name="value">The <see cref="DbDataReader"/> to build a stream from.</param> /// <returns>A <b><see cref="Stream"/></b> object.</returns> public static Stream ReaderToStream(DbDataReader value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } Stream stream; Stream tempStream = null; try { if (value.FieldCount > 1) { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "The executed command statement appears to contain invalid fields. Expected field count is 1. Actually field count was {0}.", value.FieldCount)); } tempStream = new MemoryStream(); while (value.Read()) { var bytes = Convertible.GetBytes(value.GetString(0)); tempStream.Write(bytes, 0, bytes.Length); } tempStream.Position = 0; stream = tempStream; tempStream = null; } finally { tempStream?.Dispose(); } return stream; } /// <summary> /// Converts the given <see cref="DbDataReader"/> compatible object to a string. /// Note: DbDataReader must return only one field, otherwise an exception is thrown! /// </summary> /// <param name="value">The <see cref="DbDataReader"/> to build a string from.</param> /// <returns>A <b><see cref="string"/></b> object.</returns> public static string ReaderToString(DbDataReader value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.FieldCount > 1) { throw new InvalidDataException(string.Format(CultureInfo.InvariantCulture, "The executed command statement appears to contain invalid fields. Expected field count is 1. Actually field count was {0}.", value.FieldCount)); } var stringBuilder = new StringBuilder(); while (value.Read()) { stringBuilder.Append(value.GetString(0)); } return stringBuilder.ToString(); } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public abstract DataManager Clone(); /// <summary> /// Executes the command statement and returns the number of rows affected. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns> /// A <b><see cref="int"/></b> value. /// </returns> public int Execute(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteCore(dataCommand, parameters, dbCommand => { try { return dbCommand.ExecuteNonQuery(); } finally { if (dbCommand.Connection.State != ConnectionState.Closed) { dbCommand.Connection.Close(); } } }); } /// <summary> /// Executes the command statement and returns <c>true</c> if one or more records exists; otherwise <c>false</c>. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns> /// A <b><see cref="bool"/></b> value. /// </returns> public bool ExecuteExists(IDataCommand dataCommand, params IDbDataParameter[] parameters) { using (var reader = ExecuteReader(dataCommand, parameters)) { return reader.Read(); } } /// <summary> /// Executes the command statement and returns an identity value as int. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns><see cref="int"/></returns> public abstract int ExecuteIdentityInt32(IDataCommand dataCommand, params IDbDataParameter[] parameters); /// <summary> /// Executes the command statement and returns an identity value as long. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns><see cref="long"/></returns> public abstract long ExecuteIdentityInt64(IDataCommand dataCommand, params IDbDataParameter[] parameters); /// <summary> /// Executes the command statement and returns an identity value as decimal. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns><see cref="decimal"/></returns> public abstract decimal ExecuteIdentityDecimal(IDataCommand dataCommand, params IDbDataParameter[] parameters); /// <summary> /// Executes the command statement and returns an object supporting the DbDataReader interface. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns> /// An object supporting the <b><see cref="DbDataReader"/></b> interface. /// </returns> public DbDataReader ExecuteReader(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteCore(dataCommand, parameters, dbCommand => dbCommand.ExecuteReader(CommandBehavior.CloseConnection)); } /// <summary> /// Executes the command statement and returns a string object with the retrieved XML. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns> /// An <b><see cref="string"/></b> object. /// </returns> public virtual string ExecuteXmlString(IDataCommand dataCommand, params IDbDataParameter[] parameters) { using (var reader = ExecuteReader(dataCommand, parameters)) { return ReaderToString(reader); } } /// <summary> /// Executes the command statement, and returns the value from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand"/>.</returns> public object ExecuteScalar(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteCore(dataCommand, parameters, dbCommand => { try { return dbCommand.ExecuteScalar(); } finally { if (dbCommand.Connection.State != ConnectionState.Closed) { dbCommand.Connection.Close(); } } }); } /// <summary> /// Executes the command statement, and returns the value as the specified <paramref name="returnType"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="returnType">The type to return the first column value as.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand"/> as the specified <paramref name="returnType"/>.</returns> /// <remarks>This method uses <see cref="CultureInfo.InvariantCulture"/> when casting the first column of the first row in the result from <paramref name="dataCommand"/>.</remarks> public object ExecuteScalarAsType(IDataCommand dataCommand, Type returnType, params IDbDataParameter[] parameters) { return ExecuteScalarAsType(dataCommand, returnType, CultureInfo.InvariantCulture, parameters); } /// <summary> /// Executes the command statement, and returns the value as the specified <paramref name="returnType"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="returnType">The type to return the first column value as.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand"/> as the specified <paramref name="returnType"/>.</returns> public object ExecuteScalarAsType(IDataCommand dataCommand, Type returnType, IFormatProvider provider, params IDbDataParameter[] parameters) { return Decorator.Enclose(ExecuteScalar(dataCommand, parameters)).ChangeType(returnType, o => o.FormatProvider = provider); } /// <summary> /// Executes the command statement, and returns the value as <typeparamref name="TResult" /> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <typeparam name="TResult">The type of the return value.</typeparam> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <typeparamref name="TResult"/>.</returns> /// <remarks>This method uses <see cref="CultureInfo.InvariantCulture"/> when casting the first column of the first row in the result from <paramref name="dataCommand"/>.</remarks> public TResult ExecuteScalarAs<TResult>(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return (TResult)ExecuteScalarAsType(dataCommand, typeof(TResult), parameters); } /// <summary> /// Executes the command statement, and returns the value as <typeparamref name="TResult" /> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <typeparam name="TResult">The type of the return value.</typeparam> /// <param name="dataCommand">The data command to execute.</param> /// <param name="provider">An object that supplies culture-specific formatting information.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <typeparamref name="TResult"/>.</returns> public TResult ExecuteScalarAs<TResult>(IDataCommand dataCommand, IFormatProvider provider, params IDbDataParameter[] parameters) { return (TResult)ExecuteScalarAsType(dataCommand, typeof(TResult), provider, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="bool"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="bool"/>.</returns> public bool ExecuteScalarAsBoolean(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<bool>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="DateTime"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="DateTime"/>.</returns> public DateTime ExecuteScalarAsDateTime(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<DateTime>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="short"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="short"/>.</returns> public short ExecuteScalarAsInt16(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<short>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="int"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="int"/>.</returns> public int ExecuteScalarAsInt32(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<int>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="long"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="long"/>.</returns> public long ExecuteScalarAsInt64(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<long>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="byte"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="byte"/>.</returns> public byte ExecuteScalarAsByte(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<byte>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="sbyte"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="sbyte"/>.</returns> public sbyte ExecuteScalarAsSByte(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<sbyte>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="decimal"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="decimal"/>.</returns> public decimal ExecuteScalarAsDecimal(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<decimal>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="double"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="double"/>.</returns> public double ExecuteScalarAsDouble(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<double>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="ushort"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="ushort"/>.</returns> public ushort ExecuteScalarAsUInt16(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<ushort>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="uint"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="uint"/>.</returns> public uint ExecuteScalarAsUInt32(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<uint>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="ulong"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="ulong"/>.</returns> public ulong ExecuteScalarAsUInt64(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<ulong>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="string"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="string"/>.</returns> public string ExecuteScalarAsString(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<string>(dataCommand, parameters); } /// <summary> /// Executes the command statement, and returns the value as <see cref="Guid"/> from the first column of the first row in the result set. /// Additional columns or rows are ignored. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>The first column of the first row in the result from <paramref name="dataCommand" /> as <see cref="Guid"/>.</returns> public Guid ExecuteScalarAsGuid(IDataCommand dataCommand, params IDbDataParameter[] parameters) { return ExecuteScalarAs<Guid>(dataCommand, parameters); } /// <summary> /// Core method for executing methods on the <see cref="DbCommand"/> object resolved from the virtual <see cref="ExecuteCommandCore"/> method. /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <param name="commandInvoker">The function delegate that will invoke a method on the resolved <see cref="DbCommand"/> from the virtual <see cref="ExecuteCommandCore"/> method.</param> /// <returns>A value of <typeparamref name="T"/> that is equal to the invoked method of the <see cref="DbCommand"/> object.</returns> protected virtual T ExecuteCore<T>(IDataCommand dataCommand, IDbDataParameter[] parameters, Func<DbCommand, T> commandInvoker) { return InvokeCommandCore(dataCommand, parameters, commandInvoker); } private T InvokeCommandCore<T>(IDataCommand dataCommand, IDbDataParameter[] parameters, Func<DbCommand, T> sqlInvoker) { T result; DbCommand command = null; try { using (command = ExecuteCommandCore(dataCommand, parameters)) { result = sqlInvoker(command); } } finally { command?.Parameters.Clear(); } return result; } /// <summary> /// Core method for executing all commands. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>System.Data.Common.DbCommand</returns> protected virtual DbCommand ExecuteCommandCore(IDataCommand dataCommand, params IDbDataParameter[] parameters) { if (dataCommand == null) throw new ArgumentNullException(nameof(dataCommand)); DbCommand command = null; try { command = GetCommandCore(dataCommand, parameters); command.CommandTimeout = (int)dataCommand.Timeout.TotalSeconds; OpenConnection(command); } catch (Exception) { command?.Parameters.Clear(); throw; } return command; } private static void OpenConnection(DbCommand command) { Validator.ThrowIfNull(command, nameof(command)); Validator.ThrowIfNull(command.Connection, nameof(command), $"The connection of the {nameof(command)} was not set."); if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } } /// <summary> /// Gets the command object to be used by all execute related methods. /// </summary> /// <param name="dataCommand">The data command to execute.</param> /// <param name="parameters">The parameters to use in the command.</param> /// <returns>An instance of a <see cref="DbCommand"/> implementation.</returns> protected abstract DbCommand GetCommandCore(IDataCommand dataCommand, params IDbDataParameter[] parameters); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.Globalization; using System.Net; namespace System.Security.Authentication.ExtendedProtection { public class ServiceNameCollection : ReadOnlyCollectionBase { public ServiceNameCollection(ICollection items) { if (items == null) { throw new ArgumentNullException("items"); } // Normalize and filter for duplicates. foreach (string serviceName in items) { AddIfNew(InnerList, serviceName); } } public ServiceNameCollection Merge(string serviceName) { ArrayList newServiceNames = new ArrayList(); newServiceNames.AddRange(this.InnerList); AddIfNew(newServiceNames, serviceName); ServiceNameCollection newCollection = new ServiceNameCollection(newServiceNames); return newCollection; } public ServiceNameCollection Merge(IEnumerable serviceNames) { ArrayList newServiceNames = new ArrayList(); newServiceNames.AddRange(this.InnerList); // We have a pretty bad performance here: O(n^2), but since service name lists should // be small (<<50) and Merge() should not be called frequently, this shouldn't be an issue. foreach (object item in serviceNames) { AddIfNew(newServiceNames, item as string); } ServiceNameCollection newCollection = new ServiceNameCollection(newServiceNames); return newCollection; } // Normalize, check for duplicates, and add if the value is unique. private static void AddIfNew(ArrayList newServiceNames, string serviceName) { if (String.IsNullOrEmpty(serviceName)) { throw new ArgumentException(SR.security_ServiceNameCollection_EmptyServiceName); } serviceName = NormalizeServiceName(serviceName); if (!Contains(serviceName, newServiceNames)) { newServiceNames.Add(serviceName); } } // Assumes searchServiceName and serviceNames have already been normalized. internal static bool Contains(string searchServiceName, ICollection serviceNames) { Debug.Assert(serviceNames != null); Debug.Assert(!String.IsNullOrEmpty(searchServiceName)); foreach (string serviceName in serviceNames) { if (Match(serviceName, searchServiceName)) { return true; } } return false; } public bool Contains(string searchServiceName) { string searchName = NormalizeServiceName(searchServiceName); return Contains(searchName, InnerList); } // Normalizes any punycode to unicode in an Service Name (SPN) host. // If the algorithm fails at any point then the original input is returned. // ServiceName is in one of the following forms: // prefix/host // prefix/host:port // prefix/host/DistinguishedName // prefix/host:port/DistinguishedName internal static string NormalizeServiceName(string inputServiceName) { if (string.IsNullOrWhiteSpace(inputServiceName)) { return inputServiceName; } // Separate out the prefix int slashIndex = inputServiceName.IndexOf('/'); if (slashIndex < 0) { return inputServiceName; } string prefix = inputServiceName.Substring(0, slashIndex + 1); // Includes slash string hostPortAndDistinguisher = inputServiceName.Substring(slashIndex + 1); // Excludes slash if (string.IsNullOrWhiteSpace(hostPortAndDistinguisher)) { return inputServiceName; } string host = hostPortAndDistinguisher; string port = string.Empty; string distinguisher = string.Empty; // Check for the absence of a port or distinguisher. UriHostNameType hostType = Uri.CheckHostName(hostPortAndDistinguisher); if (hostType == UriHostNameType.Unknown) { string hostAndPort = hostPortAndDistinguisher; // Check for distinguisher. int nextSlashIndex = hostPortAndDistinguisher.IndexOf('/'); if (nextSlashIndex >= 0) { // host:port/distinguisher or host/distinguisher hostAndPort = hostPortAndDistinguisher.Substring(0, nextSlashIndex); // Excludes Slash distinguisher = hostPortAndDistinguisher.Substring(nextSlashIndex); // Includes Slash host = hostAndPort; // We don't know if there is a port yet. // No need to validate the distinguisher. } // Check for port. int colonIndex = hostAndPort.LastIndexOf(':'); // Allow IPv6 addresses. if (colonIndex >= 0) { // host:port host = hostAndPort.Substring(0, colonIndex); // Excludes colon port = hostAndPort.Substring(colonIndex + 1); // Excludes colon // Loosely validate the port just to make sure it was a port and not something else. UInt16 portValue; if (!UInt16.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out portValue)) { return inputServiceName; } // Re-include the colon for the final output. Do not change the port format. port = hostAndPort.Substring(colonIndex); } hostType = Uri.CheckHostName(host); // Re-validate the host. } if (hostType != UriHostNameType.Dns) { // UriHostNameType.IPv4, UriHostNameType.IPv6: Do not normalize IPv4/6 hosts. // UriHostNameType.Basic: This is never returned by CheckHostName today // UriHostNameType.Unknown: Nothing recognizable to normalize // default Some new UriHostNameType? return inputServiceName; } // Now we have a valid DNS host, normalize it. Uri constructedUri; // We need to avoid any unexpected exceptions on this code path. if (!Uri.TryCreate(UriScheme.Http + UriScheme.SchemeDelimiter + host, UriKind.Absolute, out constructedUri)) { return inputServiceName; } string normalizedHost = constructedUri.GetComponents( UriComponents.NormalizedHost, UriFormat.SafeUnescaped); string normalizedServiceName = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}", prefix, normalizedHost, port, distinguisher); // Don't return the new one unless we absolutely have to. It may have only changed casing. if (Match(inputServiceName, normalizedServiceName)) { return inputServiceName; } return normalizedServiceName; } // Assumes already normalized. internal static bool Match(string serviceName1, string serviceName2) { return (String.Compare(serviceName1, serviceName2, StringComparison.OrdinalIgnoreCase) == 0); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.PythonTools.Analysis.Analyzer; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Values { internal class FunctionInfo : AnalysisValue, IReferenceableContainer, IHasRichDescription { private Dictionary<AnalysisValue, IAnalysisSet> _methods; private Dictionary<string, VariableDef> _functionAttrs; private readonly FunctionDefinition _functionDefinition; private readonly FunctionAnalysisUnit _analysisUnit; private readonly ProjectEntry _projectEntry; public bool IsStatic; public bool IsClassMethod; public bool IsProperty; private ReferenceDict _references; private readonly int _declVersion; private int _callDepthLimit; private int _callsSinceLimitChange; internal CallChainSet _allCalls; internal FunctionInfo(FunctionDefinition node, AnalysisUnit declUnit, InterpreterScope declScope) { _projectEntry = declUnit.ProjectEntry; _functionDefinition = node; _declVersion = declUnit.ProjectEntry.AnalysisVersion; if (_functionDefinition.Name == "__new__") { IsClassMethod = true; } object value; if (!ProjectEntry.Properties.TryGetValue(AnalysisLimits.CallDepthKey, out value) || (_callDepthLimit = (value as int?) ?? -1) < 0) { _callDepthLimit = declUnit.ProjectState.Limits.CallDepth; } _analysisUnit = new FunctionAnalysisUnit(this, declUnit, declScope, _projectEntry); } public ProjectEntry ProjectEntry { get { return _projectEntry; } } public override IPythonProjectEntry DeclaringModule { get { return _analysisUnit.ProjectEntry; } } public FunctionDefinition FunctionDefinition { get { return _functionDefinition; } } public override AnalysisUnit AnalysisUnit { get { return _analysisUnit; } } public override int DeclaringVersion { get { return _declVersion; } } public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var callArgs = ArgumentSet.FromArgs(FunctionDefinition, unit, args, keywordArgNames); FunctionAnalysisUnit calledUnit; bool updateArguments = true; if (callArgs.Count == 0 || (ProjectState.Limits.UnifyCallsToNew && Name == "__new__") || _callDepthLimit == 0) { calledUnit = (FunctionAnalysisUnit)AnalysisUnit; } else { if (_allCalls == null) { _allCalls = new CallChainSet(); } var chain = new CallChain(node, unit, _callDepthLimit); var aggregate = GetAggregate(unit); if (!_allCalls.TryGetValue(aggregate, chain, _callDepthLimit, out calledUnit)) { if (unit.ForEval) { // Call expressions that weren't analyzed get the union result // of all calls to this function. var res = AnalysisSet.Empty; foreach (var call in _allCalls.Values) { res = res.Union(call.ReturnValue.GetTypesNoCopy(unit, DeclaringModule)); } return res; } else { _callsSinceLimitChange += 1; if (_callsSinceLimitChange >= ProjectState.Limits.DecreaseCallDepth && _callDepthLimit > 1) { _callDepthLimit -= 1; _callsSinceLimitChange = 0; AnalysisLog.ReduceCallDepth(this, _allCalls.Count, _callDepthLimit); _allCalls.Clear(); chain = chain.Trim(_callDepthLimit); } calledUnit = new CalledFunctionAnalysisUnit(aggregate, (FunctionAnalysisUnit)AnalysisUnit, chain, callArgs); _allCalls.Add(aggregate, chain, calledUnit); updateArguments = false; } } } if (updateArguments && calledUnit.UpdateParameters(callArgs)) { AnalysisLog.UpdateUnit(calledUnit); } if (keywordArgNames != null && keywordArgNames.Any()) { calledUnit.AddNamedParameterReferences(unit, keywordArgNames); } calledUnit.ReturnValue.AddDependency(unit); return calledUnit.ReturnValue.Types; } private IVersioned GetAggregate(AnalysisUnit unit) { IVersioned agg; var fau = unit as CalledFunctionAnalysisUnit; if (fau == null || _callDepthLimit == 1) { // The caller is top-level or a normal FAU, not one with a call chain. // Just aggregate the caller w/ ourselves agg = AggregateProjectEntry.GetAggregate(unit.ProjectEntry, ProjectEntry); } else { // The caller is part of a call chain, aggregate ourselves with everyone // else who's in it. agg = AggregateProjectEntry.GetAggregate(fau.DependencyProject, ProjectEntry); } return agg; } public override string Name { get { return FunctionDefinition.Name; } } internal IEnumerable<KeyValuePair<string, string>> GetParameterString() { for (int i = 0; i < FunctionDefinition.Parameters.Count; i++) { if (i != 0) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Comma, ", "); } var p = FunctionDefinition.Parameters[i]; var name = MakeParameterName(p); var defaultValue = GetDefaultValue(ProjectState, p, DeclaringModule.Tree); yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Parameter, name); if (!String.IsNullOrWhiteSpace(defaultValue)) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, " = "); yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, defaultValue); } } } internal static IEnumerable<KeyValuePair<string, string>> GetReturnTypeString(Func<int, IAnalysisSet> getReturnValue) { var retTypes = getReturnValue(0); for (int strength = 1; retTypes.Count > 10 && strength <= UnionComparer.MAX_STRENGTH; ++strength) { retTypes = getReturnValue(strength); } var seenNames = new HashSet<string>(); var addDots = false; var descriptions = new List<string>(); foreach (var av in retTypes) { if (av == null) { continue; } if (av.Push()) { try { var desc = av.ShortDescription; if (!string.IsNullOrWhiteSpace(desc) && seenNames.Add(desc)) { descriptions.Add(desc.Replace("\r\n", "\n").Replace("\n", "\r\n ")); } } finally { av.Pop(); } } else { addDots = true; } } var first = true; descriptions.Sort(); foreach (var desc in descriptions) { if (first) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, " -> "); first = false; } else { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Comma, ", "); } yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Type, desc); } if (addDots) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "..."); } } internal static IEnumerable<KeyValuePair<string,string>> GetDocumentationString(string documentation) { if (!String.IsNullOrEmpty(documentation)) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, documentation); } } internal IEnumerable<KeyValuePair<string, string>> GetQualifiedLocationString() { var qualifiedNameParts = new Stack<string>(); for (var item = FunctionDefinition.Parent; item is FunctionDefinition || item is ClassDefinition; item = item.Parent) { if (!string.IsNullOrEmpty(item.Name)) { qualifiedNameParts.Push(item.Name); } } if (qualifiedNameParts.Count > 0) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "declared in "); yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, string.Join(".", qualifiedNameParts)); } } public IEnumerable<KeyValuePair<string, string>> GetRichDescription() { if (FunctionDefinition.IsLambda) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "lambda "); foreach (var kv in GetParameterString()) { yield return kv; } yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, ": "); if (FunctionDefinition.IsGenerator) { var lambdaExpr = ((ExpressionStatement)FunctionDefinition.Body).Expression; Expression yieldExpr = null; YieldExpression ye; YieldFromExpression yfe; if ((ye = lambdaExpr as YieldExpression) != null) { yieldExpr = ye.Expression; } else if ((yfe = lambdaExpr as YieldFromExpression) != null) { yieldExpr = yfe.Expression; } else { Debug.Assert(false, "lambdaExpr is not YieldExpression or YieldFromExpression"); } yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, yieldExpr.ToCodeString(DeclaringModule.Tree)); } else { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, ((ReturnStatement)FunctionDefinition.Body).Expression.ToCodeString(DeclaringModule.Tree)); } } else { if (FunctionDefinition.IsCoroutine) { yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "async "); } yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "def "); yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Name, GetFullName()); yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, "("); foreach (var kv in GetParameterString()) { yield return kv; } yield return new KeyValuePair<string, string>(WellKnownRichDescriptionKinds.Misc, ")"); } foreach (var kv in GetReturnTypeString(GetReturnValue)) { yield return kv; } bool hasNl = false; var nlKind = WellKnownRichDescriptionKinds.EndOfDeclaration; foreach (var kv in GetDocumentationString(Documentation)) { if (!hasNl) { yield return new KeyValuePair<string, string>(nlKind, "\r\n"); nlKind = WellKnownRichDescriptionKinds.Misc; hasNl = true; } yield return kv; } hasNl = false; foreach (var kv in GetQualifiedLocationString()) { if (!hasNl) { yield return new KeyValuePair<string, string>(nlKind, "\r\n"); hasNl = true; } yield return kv; } } private string GetFullName() { var name = FunctionDefinition.Name; for (var stmt = FunctionDefinition.Parent; stmt != null; stmt = stmt.Parent) { if (stmt.IsGlobal) { return DeclaringModule.ModuleName + "." + name; } if (!string.IsNullOrEmpty(stmt.Name)) { name = stmt.Name + "." + name; } } return name; } public override IAnalysisSet GetDescriptor(Node node, AnalysisValue instance, AnalysisValue context, AnalysisUnit unit) { if ((instance == ProjectState._noneInst && !IsClassMethod) || IsStatic) { return SelfSet; } if (_methods == null) { _methods = new Dictionary<AnalysisValue, IAnalysisSet>(); } IAnalysisSet result; if (!_methods.TryGetValue(instance, out result) || result == null) { if (IsClassMethod) { _methods[instance] = result = new BoundMethodInfo(this, context).SelfSet; } else { _methods[instance] = result = new BoundMethodInfo(this, instance).SelfSet; } } if (IsProperty) { return result.Call(node, unit, ExpressionEvaluator.EmptySets, ExpressionEvaluator.EmptyNames); } return result; } public override string Documentation { get { if (FunctionDefinition.Body != null) { return FunctionDefinition.Body.Documentation.TrimDocumentation(); } return ""; } } public override PythonMemberType MemberType { get { return IsProperty ? PythonMemberType.Property : PythonMemberType.Function; } } public override string ToString() { return "FunctionInfo " + _analysisUnit.FullName + " (" + _declVersion + ")"; } public override IEnumerable<LocationInfo> Locations { get { var start = FunctionDefinition.NameExpression.GetStart(FunctionDefinition.GlobalParent); var end = FunctionDefinition.GetEnd(FunctionDefinition.GlobalParent); return new[] { new LocationInfo( ProjectEntry.FilePath, start.Line, start.Column, end.Line, end.Column ) }; } } private class StringArrayComparer : IEqualityComparer<string[]> { private IEqualityComparer<string> _comparer; public StringArrayComparer() { _comparer = StringComparer.Ordinal; } public StringArrayComparer(IEqualityComparer<string> comparer) { _comparer = comparer; } public bool Equals(string[] x, string[] y) { if (x == null || y == null) { return x == null && y == null; } if (x.Length != y.Length) { return false; } for (int i = 0; i < x.Length; ++i) { if (!_comparer.Equals(x[i], y[i])) { return false; } } return true; } public int GetHashCode(string[] obj) { if (obj == null) { return 0; } int hc = 261563 ^ obj.Length; foreach (var p in obj) { hc ^= _comparer.GetHashCode(p); } return hc; } } public override IEnumerable<OverloadResult> Overloads { get { var references = new Dictionary<string[], IEnumerable<AnalysisVariable>[]>(new StringArrayComparer()); var units = new HashSet<AnalysisUnit>(); units.Add(AnalysisUnit); if (_allCalls != null) { units.UnionWith(_allCalls.Values); } foreach (var unit in units) { var vars = FunctionDefinition.Parameters.Select(p => { VariableDef param; if (unit.Scope.TryGetVariable(p.Name, out param)) { return param; } return null; }).ToArray(); var parameters = vars .Select(p => string.Join(", ", p.Types.Select(av => av.ShortDescription).OrderBy(s => s).Distinct())) .ToArray(); IEnumerable<AnalysisVariable>[] refs; if (references.TryGetValue(parameters, out refs)) { refs = refs.Zip(vars, (r, v) => r.Concat(ProjectEntry.Analysis.ToVariables(v))).ToArray(); } else { refs = vars.Select(v => ProjectEntry.Analysis.ToVariables(v)).ToArray(); } references[parameters] = refs; } foreach (var keyValue in references) { yield return new SimpleOverloadResult( FunctionDefinition.Parameters.Select((p, i) => { var name = MakeParameterName(p); var defaultValue = GetDefaultValue(ProjectState, p, DeclaringModule.Tree); var type = keyValue.Key[i]; var refs = keyValue.Value[i]; return new ParameterResult(name, string.Empty, type, false, refs, defaultValue); }).ToArray(), FunctionDefinition.Name, Documentation ); } } } internal static string MakeParameterName(Parameter curParam) { string name = curParam.Name; if (curParam.IsDictionary) { name = "**" + name; } else if (curParam.IsList) { name = "*" + curParam.Name; } return name; } internal static string GetDefaultValue(PythonAnalyzer state, Parameter curParam, PythonAst tree) { if (curParam.DefaultValue != null) { // TODO: Support all possible expressions for default values, we should // probably have a PythonAst walker for expressions or we should add ToCodeString() // onto Python ASTs so they can round trip ConstantExpression defaultValue = curParam.DefaultValue as ConstantExpression; if (defaultValue != null) { return defaultValue.GetConstantRepr(state.LanguageVersion); } else { NameExpression nameExpr = curParam.DefaultValue as NameExpression; if (nameExpr != null) { return nameExpr.Name; } else { DictionaryExpression dict = curParam.DefaultValue as DictionaryExpression; if (dict != null) { if (dict.Items.Count == 0) { return "{}"; } else { return "{...}"; } } else { ListExpression list = curParam.DefaultValue as ListExpression; if (list != null) { if (list.Items.Count == 0) { return "[]"; } else { return "[...]"; } } else { TupleExpression tuple = curParam.DefaultValue as TupleExpression; if (tuple != null) { if (tuple.Items.Count == 0) { return "()"; } else { return "(...)"; } } else { return curParam.DefaultValue.ToCodeString(tree); } } } } } } return null; } public override void SetMember(Node node, AnalysisUnit unit, string name, IAnalysisSet value) { if (_functionAttrs == null) { _functionAttrs = new Dictionary<string, VariableDef>(); } VariableDef varRef; if (!_functionAttrs.TryGetValue(name, out varRef)) { _functionAttrs[name] = varRef = new VariableDef(); } varRef.AddAssignment(node, unit); varRef.AddTypes(unit, value, true, DeclaringModule); } public override IAnalysisSet GetTypeMember(Node node, AnalysisUnit unit, string name) { return ProjectState.ClassInfos[BuiltinTypeId.Function].GetMember(node, unit, name); } public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) { VariableDef tmp; if (_functionAttrs != null && _functionAttrs.TryGetValue(name, out tmp)) { tmp.AddDependency(unit); tmp.AddReference(node, unit); return tmp.Types; } // TODO: Create one and add a dependency if (name == "__name__") { return unit.ProjectState.GetConstant(FunctionDefinition.Name); } return GetTypeMember(node, unit, name); } public override IDictionary<string, IAnalysisSet> GetAllMembers(IModuleContext moduleContext, GetMemberOptions options = GetMemberOptions.None) { if (!options.HasFlag(GetMemberOptions.DeclaredOnly) && (_functionAttrs == null || _functionAttrs.Count == 0)) { return ProjectState.ClassInfos[BuiltinTypeId.Function].GetAllMembers(moduleContext, options); } Dictionary<string, IAnalysisSet> res; if (options.HasFlag(GetMemberOptions.DeclaredOnly)) { res = new Dictionary<string, IAnalysisSet>(); } else { res = new Dictionary<string, IAnalysisSet>(ProjectState.ClassInfos[BuiltinTypeId.Function].Instance.GetAllMembers(moduleContext)); } if (_functionAttrs != null) { foreach (var variable in _functionAttrs) { IAnalysisSet existing; if (!res.TryGetValue(variable.Key, out existing)) { res[variable.Key] = variable.Value.Types; } else { res[variable.Key] = existing.Union(variable.Value.TypesNoCopy); } } } return res; } // Returns False if no more parameters can be updated for this unit. private bool UpdateSingleDefaultParameter(AnalysisUnit unit, InterpreterScope scope, int index, IParameterInfo info) { if (index >= FunctionDefinition.Parameters.Count) { return false; } VariableDef param; var name = FunctionDefinition.Parameters[index].Name; if (scope.TryGetVariable(name, out param)) { var av = ProjectState.GetAnalysisSetFromObjects(info.ParameterTypes); if ((info.IsParamArray && !(param is ListParameterVariableDef)) || (info.IsKeywordDict && !(param is DictParameterVariableDef))) { return false; } param.AddTypes(unit, av, true, DeclaringModule); } return true; } internal void UpdateDefaultParameters(AnalysisUnit unit, IEnumerable<IParameterInfo> parameters) { var finishedScopes = new HashSet<InterpreterScope>(); var scopeSet = new HashSet<InterpreterScope>(); scopeSet.Add(AnalysisUnit.Scope); if (_allCalls != null) { scopeSet.UnionWith(_allCalls.Values.Select(au => au.Scope)); } int index = 0; foreach (var p in parameters) { foreach (var scope in scopeSet) { if (finishedScopes.Contains(scope)) { continue; } if (!UpdateSingleDefaultParameter(unit, scope, index, p)) { finishedScopes.Add(scope); } } index += 1; } } internal IAnalysisSet[] GetParameterTypes(int unionStrength = 0) { var result = new IAnalysisSet[FunctionDefinition.Parameters.Count]; var units = new HashSet<AnalysisUnit>(); units.Add(AnalysisUnit); if (_allCalls != null) { units.UnionWith(_allCalls.Values); } for (int i = 0; i < result.Length; ++i) { result[i] = (unionStrength >= 0 && unionStrength <= UnionComparer.MAX_STRENGTH) ? AnalysisSet.CreateUnion(UnionComparer.Instances[unionStrength]) : AnalysisSet.Empty; VariableDef param; foreach (var unit in units) { if (unit != null && unit.Scope != null && unit.Scope.TryGetVariable(FunctionDefinition.Parameters[i].Name, out param)) { result[i] = result[i].Union(param.TypesNoCopy); } } } return result; } internal IAnalysisSet GetReturnValue(int unionStrength = 0) { var result = (unionStrength >= 0 && unionStrength <= UnionComparer.MAX_STRENGTH) ? AnalysisSet.CreateUnion(UnionComparer.Instances[unionStrength]) : AnalysisSet.Empty; var units = new HashSet<AnalysisUnit>(); units.Add(AnalysisUnit); if (_allCalls != null) { units.UnionWith(_allCalls.Values); } result = result.UnionAll(units.OfType<FunctionAnalysisUnit>().Select(unit => unit.ReturnValue.TypesNoCopy)); return result; } public PythonAnalyzer ProjectState { get { return ProjectEntry.ProjectState; } } internal override void AddReference(Node node, AnalysisUnit unit) { if (!unit.ForEval) { if (_references == null) { _references = new ReferenceDict(); } _references.GetReferences(unit.DeclaringModule.ProjectEntry).AddReference(new EncodedLocation(unit, node)); } } internal override IEnumerable<LocationInfo> References { get { if (_references != null) { return _references.AllReferences; } return new LocationInfo[0]; } } public override IPythonType PythonType { get { return ProjectState.Types[BuiltinTypeId.Function]; } } internal override bool IsOfType(IAnalysisSet klass) { return klass.Contains(ProjectState.ClassInfos[BuiltinTypeId.Function]); } internal override bool UnionEquals(AnalysisValue av, int strength) { if (strength >= MergeStrength.ToObject) { return av is FunctionInfo || av is BuiltinFunctionInfo || av == ProjectState.ClassInfos[BuiltinTypeId.Function].Instance; } return base.UnionEquals(av, strength); } internal override int UnionHashCode(int strength) { if (strength >= MergeStrength.ToObject) { return ProjectState.ClassInfos[BuiltinTypeId.Function].Instance.UnionHashCode(strength); } return base.UnionHashCode(strength); } internal override AnalysisValue UnionMergeTypes(AnalysisValue av, int strength) { if (strength >= MergeStrength.ToObject) { return ProjectState.ClassInfos[BuiltinTypeId.Function].Instance; } return base.UnionMergeTypes(av, strength); } #region IReferenceableContainer Members public IEnumerable<IReferenceable> GetDefinitions(string name) { VariableDef def; if (_functionAttrs != null && _functionAttrs.TryGetValue(name, out def)) { return new IReferenceable[] { def }; } return new IReferenceable[0]; } #endregion } }
// // Copyright (C) 2008-2009 Jordi Mas i Hernandez, [email protected] // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using Gdk; using Mono.Addins; using System.Collections.Generic; using System.ComponentModel; using Mistelix.Transitions; using Mistelix.DataModel; using Mistelix.Widgets; namespace Mistelix.Core { // Generates MPEG for DVD menu. Designed for a single menu public class DvdMenu : IDisposable { Project project; Gdk.Pixbuf background; bool asynchronous; BackgroundWorker thumbnailing; public EventHandler CompletedThumbnails; public DvdMenu (Project project) { this.project = project; UpdateTheme (); } ~DvdMenu () { Dispose (false); } public bool Asynchronous { get { return asynchronous; } set { if (value == true && CompletedThumbnails == null) throw new InvalidOperationException ("You must set the CompletedThumbnail event"); asynchronous = value; if (value == true) { thumbnailing = new BackgroundWorker (); thumbnailing.WorkerSupportsCancellation = true; thumbnailing.DoWork += new DoWorkEventHandler (DoWork); } } } public void Dispose () { Dispose (true); System.GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { Logger.Debug ("DvdMenu.Disposing"); if (background != null) background.Dispose (); } public string GenerateMPEG (/*, ProgressEventHandler progress*/) { SlideShow sw; Logger.Debug ("DvdMenu.GenerateMPEG"); Save (project.FileToFullPath (Defines.MAIN_MENU_FILE_PNG)); string outfile; sw = new SlideShow (); sw.filename = Defines.MAIN_MENU_FILE_SRC; sw.images.Add (new SlideImage (project.FileToFullPath (Defines.MAIN_MENU_FILE_PNG), string.Empty, 5, TransitionManager.None.Name)); outfile = sw.Generate (project, null); if (Mistelix.Debugging == false) File.Delete (project.FileToFullPath (Defines.MAIN_MENU_FILE_PNG)); return outfile; } public void UpdateTheme () { string name; Theme theme = null; Gdk.Pixbuf im = null; if (project == null) return; name = project.Details.ThemeName; if (name != null) theme = ThemeManager.FromName (name); if (background != null) background.Dispose (); foreach (Button button in project.Buttons) button.InvalidateThumbnail (); if (theme == null) { background = null; return; } try { if (string.IsNullOrEmpty (project.Details.CustomMenuBackground) == false) im = new Gdk.Pixbuf (project.Details.CustomMenuBackground); } catch { Logger.Error (String.Format ("DvdMenu.UpdateTheme. Error loading custom background {0}", project.Details.CustomMenuBackground)); } try { if (im == null) im = new Gdk.Pixbuf (Path.Combine (Defines.DATA_DIR, theme.MenuBackground)); } catch { Logger.Error (String.Format ("DvdMenu.UpdateTheme. Error loading menu background {0}", Path.Combine (Defines.DATA_DIR, theme.MenuBackground))); } background = im.ScaleSimple (project.Details.Width, project.Details.Height, InterpType.Nearest); im.Dispose (); } public void Draw (Cairo.Context cr, Core.Button moving_button) { bool fire_thread = false; // See: http://kapo-cpp.blogspot.com/2008/01/drawing-pixbuf-to-cairo-context-2.html if (background != null) { Gdk.CairoHelper.SetSourcePixbuf (cr, background, 0, 0); cr.Paint (); } if (project == null) return; // Draw buttons foreach (Button button in project.Buttons) { if (moving_button != null && moving_button.LinkedId == button.LinkedId) { if (DrawButton (cr, button) == true) fire_thread = true; Utils.DrawSelectionBox (cr, moving_button.X, moving_button.Y, button.DrawingBoxWidth, button.DrawingBoxHeight); } else { if (DrawButton (cr, button) == true) fire_thread = true; } } if (fire_thread == true) { if (thumbnailing.IsBusy == false) thumbnailing.RunWorkerAsync (this); } } // return value indicates if the thumbnail of the button was not painted and we need to create them after bool DrawButton (Cairo.Context cr, Button button) { if (asynchronous == false || (asynchronous == true && button.IsThumbnailCreated)) { // In the button object the image is already loaded and cached button.Draw (cr, project); return false; } return true; } public void Save (string file) { Cairo.ImageSurface s = new Cairo.ImageSurface (Cairo.Format.Rgb24, project.Details.Width, project.Details.Height); Cairo.Context cr = new Cairo.Context (s); bool previous = asynchronous; asynchronous = false; Draw (cr, null); asynchronous = previous; s.WriteToPng (file); ((IDisposable)cr).Dispose (); s.Destroy (); } void DoWork (object sender, DoWorkEventArgs e) { foreach (Button button in project.Buttons) button.LoadThumbnail (project); if (CompletedThumbnails != null) CompletedThumbnails (this, EventArgs.Empty); } } }
using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Tmds.DBus.Tests { public class ServiceNameTests { [Fact] public async Task Register() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; var conn1 = new Connection(address); await conn1.ConnectAsync(); await conn1.RegisterServiceAsync(serviceName); bool released = await conn1.UnregisterServiceAsync(serviceName); Assert.Equal(true, released); } } [Fact] public async Task NameAlreadyRegisteredOnOtherConnection() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; var conn1 = new Connection(address); await conn1.ConnectAsync(); await conn1.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.None); var conn2 = new Connection(address); await conn2.ConnectAsync(); await Assert.ThrowsAsync<InvalidOperationException>(() => conn2.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.None)); } } [Fact] public async Task NameAlreadyRegisteredOnSameConnection() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; var conn1 = new Connection(address); await conn1.ConnectAsync(); await conn1.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.None); await Assert.ThrowsAsync<InvalidOperationException>(() => conn1.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.None)); } } [Fact] public async Task ReplaceRegistered() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; var conn1 = new Connection(address); await conn1.ConnectAsync(); await conn1.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.AllowReplacement); var conn2 = new Connection(address); await conn2.ConnectAsync(); await conn2.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.ReplaceExisting); } } [Fact] public async Task EmitLost() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; var conn1 = new Connection(address); await conn1.ConnectAsync(); var onLost = new ObservableAction(); await conn1.RegisterServiceAsync(serviceName, onLost.Action, ServiceRegistrationOptions.AllowReplacement); var conn2 = new Connection(address); await conn2.ConnectAsync(); await conn2.RegisterServiceAsync(serviceName, ServiceRegistrationOptions.ReplaceExisting); await onLost.AssertNumberOfCallsAsync(1); } } [Fact] public async Task EmitAquired() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; var conn1 = new Connection(address); await conn1.ConnectAsync(); var conn1OnLost = new ObservableAction(); var conn1OnAquired = new ObservableAction(); await conn1.QueueServiceRegistrationAsync(serviceName, conn1OnAquired.Action, conn1OnLost.Action, ServiceRegistrationOptions.AllowReplacement); await conn1OnAquired.AssertNumberOfCallsAsync(1); await conn1OnLost.AssertNumberOfCallsAsync(0); var conn2 = new Connection(address); await conn2.ConnectAsync(); var conn2OnLost = new ObservableAction(); var conn2OnAquired = new ObservableAction(); await conn2.QueueServiceRegistrationAsync(serviceName, conn2OnAquired.Action, conn2OnLost.Action); await conn1OnAquired.AssertNumberOfCallsAsync(1); await conn1OnLost.AssertNumberOfCallsAsync(1); await conn2OnAquired.AssertNumberOfCallsAsync(1); await conn2OnLost.AssertNumberOfCallsAsync(0); } } [Fact] public async Task ResolveService() { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; IConnection conn1 = new Connection(address); var conn1Info = await conn1.ConnectAsync(); IConnection conn2 = new Connection(address); await conn2.ConnectAsync(); var owner = await conn2.ResolveServiceOwnerAsync(serviceName); Assert.Equal(null, owner); await conn1.RegisterServiceAsync(serviceName); owner = await conn2.ResolveServiceOwnerAsync(serviceName); Assert.Equal(conn1Info.LocalName, owner); await conn1.UnregisterServiceAsync(serviceName); owner = await conn2.ResolveServiceOwnerAsync(serviceName); Assert.Equal(null, owner); } } private static bool IsTravis = System.Environment.GetEnvironmentVariable("TRAVIS") == "true"; [Theory] [InlineData("tmds.dbus.test", false)] [InlineData("tmds.dbus.test.*", false)] [InlineData("tmds.dbus.*", false)] [InlineData("tmds.*", false)] [InlineData(".*", true)] [InlineData("*", true)] public async Task WatchResolveService(string resolvedService, bool filterEvents) { using (var dbusDaemon = new DBusDaemon()) { string serviceName = "tmds.dbus.test"; await dbusDaemon.StartAsync(); var address = dbusDaemon.Address; IConnection conn1 = new Connection(address); var conn1Info = await conn1.ConnectAsync(); IConnection conn2 = new Connection(address); var conn2Info = await conn2.ConnectAsync(); var changeEvents = new BlockingCollection<ServiceOwnerChangedEventArgs>(new ConcurrentQueue<ServiceOwnerChangedEventArgs>()); Action<ServiceOwnerChangedEventArgs> onChange = change => { if (!filterEvents || (change.ServiceName == serviceName)) changeEvents.Add(change); }; var resolver = await conn2.ResolveServiceOwnerAsync(resolvedService, onChange); await conn1.RegisterServiceAsync(serviceName); var e = await changeEvents.TakeAsync(); Assert.Equal(serviceName, e.ServiceName); Assert.Equal(null, e.OldOwner); Assert.Equal(conn1Info.LocalName, e.NewOwner); await conn1.UnregisterServiceAsync(serviceName); e = await changeEvents.TakeAsync(); Assert.Equal(serviceName, e.ServiceName); Assert.Equal(conn1Info.LocalName, e.OldOwner); Assert.Equal(null, e.NewOwner); resolver.Dispose(); await conn1.RegisterServiceAsync(serviceName); resolver = await conn2.ResolveServiceOwnerAsync(resolvedService, onChange); e = await changeEvents.TakeAsync(); Assert.Equal(serviceName, e.ServiceName); Assert.Equal(null, e.OldOwner); Assert.Equal(conn1Info.LocalName, e.NewOwner); } } } static class BlockingCollectionExtensions { public static Task<T> TakeAsync<T>(this BlockingCollection<T> collection) { // avoid blocking xunit synchronizationcontext threadpool return Task.Run(() => { var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(10)); return collection.Take(cts.Token); }); } } }
/* * 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 Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI40; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.LowLevelAPI40 { /// <summary> /// C_CreateObject, C_DestroyObject, C_CopyObject and C_GetObjectSize tests. /// </summary> [TestClass] public class _16_CreateCopyDestroyObjectTest { /// <summary> /// C_CreateObject and C_DestroyObject test. /// </summary> [TestMethod] public void _01_CreateDestroyObjectTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0) 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.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint 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.ToUInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare attribute template of new data object CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[5]; template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_DATA); template[1] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); template[2] = CkaUtils.CreateAttribute(CKA.CKA_APPLICATION, Settings.ApplicationName); template[3] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName); template[4] = CkaUtils.CreateAttribute(CKA.CKA_VALUE, "Data object content"); // Create object uint objectId = CK.CK_INVALID_HANDLE; rv = pkcs11.C_CreateObject(session, template, Convert.ToUInt32(template.Length), ref objectId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // In LowLevelAPI we have to free unmanaged memory taken by attributes for (int i = 0; i < template.Length; i++) { UnmanagedMemory.Free(ref template[i].value); template[i].valueLen = 0; } // Do something interesting with new object // Destroy object rv = pkcs11.C_DestroyObject(session, objectId); 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_CopyObject test. /// </summary> [TestMethod] public void _02_CopyObjectTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0) 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.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint 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.ToUInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Create object that can be copied uint objectId = CK.CK_INVALID_HANDLE; rv = Helpers.CreateDataObject(pkcs11, session, ref objectId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Copy object uint copiedObjectId = CK.CK_INVALID_HANDLE; rv = pkcs11.C_CopyObject(session, objectId, null, 0, ref copiedObjectId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with new object rv = pkcs11.C_DestroyObject(session, copiedObjectId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, objectId); 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_GetObjectSize test. /// </summary> [TestMethod] public void _03_GetObjectSizeTest() { if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0) 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.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present uint slotId = Helpers.GetUsableSlot(pkcs11); uint 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.ToUInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Create object uint objectId = CK.CK_INVALID_HANDLE; rv = Helpers.CreateDataObject(pkcs11, session, ref objectId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Determine object size uint objectSize = 0; rv = pkcs11.C_GetObjectSize(session, objectId, ref objectSize); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(objectSize > 0); rv = pkcs11.C_DestroyObject(session, objectId); 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()); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ReplicationNetworksOperations operations. /// </summary> internal partial class ReplicationNetworksOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationNetworksOperations { /// <summary> /// Initializes a new instance of the ReplicationNetworksOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ReplicationNetworksOperations(SiteRecoveryManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SiteRecoveryManagementClient /// </summary> public SiteRecoveryManagementClient Client { get; private set; } /// <summary> /// Gets the list of networks. View-only API. /// </summary> /// <remarks> /// Lists the networks available in a vault /// </remarks> /// <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<Network>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationNetworks").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); 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<IPage<Network>>(); _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<Network>>(_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 list of networks under a fabric. /// </summary> /// <remarks> /// Lists the networks available for a fabric. /// </remarks> /// <param name='fabricName'> /// Fabric name /// </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<Network>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByReplicationFabrics", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); 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<IPage<Network>>(); _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<Network>>(_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 a network with specified server id and network name. /// </summary> /// <remarks> /// Gets the details of a network. /// </remarks> /// <param name='fabricName'> /// Server Id. /// </param> /// <param name='networkName'> /// Primary network name. /// </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<Network>> GetWithHttpMessagesAsync(string fabricName, string networkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ResourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName"); } if (Client.ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (networkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("networkName", networkName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}").ToString(); _url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{networkName}", System.Uri.EscapeDataString(networkName)); 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<Network>(); _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<Network>(_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 list of networks. View-only API. /// </summary> /// <remarks> /// Lists the networks available in a vault /// </remarks> /// <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<Network>>> 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<Network>>(); _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<Network>>(_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 list of networks under a fabric. /// </summary> /// <remarks> /// Lists the networks available for a fabric. /// </remarks> /// <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<Network>>> ListByReplicationFabricsNextWithHttpMessagesAsync(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, "ListByReplicationFabricsNext", 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<Network>>(); _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<Network>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate.Helpers; using SDKTemplate.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Windows.Foundation; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Media.Protection; using Windows.Media.Streaming.Adaptive; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Web.Http; using Windows.Web.Http.Filters; using Windows.Web.Http.Headers; namespace SDKTemplate { /// See the README.md for discussion of this scenario. /// /// Note: We register but do not unregister event handlers in this scenario, see the EventHandler /// scenario for patterns that can be used to clean up. public sealed partial class Scenario3_RequestModification : Page { private AzureKeyAcquisitionMethod tokenMethod; private CancellationTokenSource ctsForAppHttpClientForKeys = new CancellationTokenSource(); public Scenario3_RequestModification() { this.InitializeComponent(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { // Cancel any HTTP requests the app was making: ctsForAppHttpClientForKeys.Cancel(); // Release handles on various media objects to ensure a quick clean-up ContentSelectorControl.MediaPlaybackItem = null; var mediaPlayer = mediaPlayerElement.MediaPlayer; if (mediaPlayer != null) { mediaPlayerLogger?.Dispose(); mediaPlayerLogger = null; UnregisterHandlers(mediaPlayer); mediaPlayerElement.SetMediaPlayer(null); mediaPlayer.Dispose(); } // We clean up HDCP explicitly. Otherwise, the OutputProtectionManager // will continue to impose our policy until it is finalized by the // garbage collector. hdcpSession?.Dispose(); hdcpSession = null; } private void UnregisterHandlers(MediaPlayer mediaPlayer) { AdaptiveMediaSource adaptiveMediaSource = null; MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem; if (mpItem != null) { adaptiveMediaSource = mpItem.Source.AdaptiveMediaSource; } MediaSource source = mediaPlayer.Source as MediaSource; if (source != null) { adaptiveMediaSource = source.AdaptiveMediaSource; } mediaPlaybackItemLogger?.Dispose(); mediaPlaybackItemLogger = null; mediaSourceLogger?.Dispose(); mediaSourceLogger = null; adaptiveMediaSourceLogger?.Dispose(); adaptiveMediaSourceLogger = null; UnregisterForAdaptiveMediaSourceEvents(adaptiveMediaSource); } AddAuthorizationHeaderFilter httpClientFilter; HdcpSession hdcpSession; AdaptiveMediaSource adaptiveMediaSource; private void Page_OnLoaded(object sender, RoutedEventArgs e) { // We enforce HDCP in this scenario that uses encryption but not PlayReady. hdcpSession = new HdcpSession(); // The protection level may change if screens are plugged or unplugged from the system or // if explicitly set in the radio buttons in the UI. hdcpSession.ProtectionChanged += (HdcpSession session, object args) => { // After a change, impose a maximum bitrate based on the actual protection level. HdcpProtection? protection = session.GetEffectiveProtection(); SetMaxBitrateForProtectionLevel(protection, adaptiveMediaSource); }; // Explicitly create the instance of MediaPlayer if you need to register for its events // (like MediaOpened / MediaFailed) prior to setting an IMediaPlaybackSource. var mediaPlayer = new MediaPlayer(); // We use a helper class that logs all the events for the MediaPlayer: mediaPlayerLogger = new MediaPlayerLogger(LoggerControl, mediaPlayer); mediaPlayerElement.SetMediaPlayer(mediaPlayer); ContentSelectorControl.Initialize( mediaPlayer, MainPage.ContentManagementSystemStub.Where(m =>!m.PlayReady), null, LoggerControl, LoadSourceFromUriAsync); ContentSelectorControl.HideLoadUri(); // Avoid free text URIs for this scenario. // Initialize tokenMethod based on the default selected radio button. var defaultRadioButton = AzureAuthorizationMethodPanel.Children.OfType<RadioButton>().First(button => button.IsChecked.Value); Enum.TryParse((string)defaultRadioButton.Tag, out tokenMethod); Log("Content Id 13 and 14 require that you choose an authorization method."); ContentSelectorControl.SetSelectedModel(MainPage.ContentManagementSystemStub.Where(m => m.Id == 13).FirstOrDefault()); } #region Content Loading private async Task<MediaPlaybackItem> LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null) { UnregisterHandlers(mediaPlayerElement.MediaPlayer); if (tokenMethod == AzureKeyAcquisitionMethod.AuthorizationHeader) { if (ContentSelectorControl.SelectedModel == null) { return null; } // Use an IHttpFilter to identify key request URIs and insert an Authorization header with the Bearer token. var baseProtocolFilter = new HttpBaseProtocolFilter(); baseProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; // Always set WriteBehavior = NoCache httpClientFilter = new AddAuthorizationHeaderFilter(baseProtocolFilter); httpClientFilter.AuthorizationHeader = new HttpCredentialsHeaderValue("Bearer", ContentSelectorControl.SelectedModel.AesToken); httpClient = new HttpClient(httpClientFilter); // Here is where you can add any required custom CDN headers. httpClient.DefaultRequestHeaders.Append("X-HeaderKey", "HeaderValue"); // NOTE: It is not recommended to set Authorization headers needed for key request on the // default headers of the HttpClient, as these will also be used on non-HTTPS calls // for media segments and manifests -- and thus will be easily visible. } AdaptiveMediaSourceCreationResult result = null; if (httpClient != null) { result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient); } else { result = await AdaptiveMediaSource.CreateFromUriAsync(uri); } MediaSource source; if (result.Status == AdaptiveMediaSourceCreationStatus.Success) { adaptiveMediaSource = result.MediaSource; // We use a helper class that logs all the events for the AdaptiveMediaSource: adaptiveMediaSourceLogger = new AdaptiveMediaSourceLogger(LoggerControl, adaptiveMediaSource); // In addition to logging, we use the callbacks to update some UI elements in this scenario: RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource); // At this point, we have read the manifest of the media source, and all bitrates are known. // Now that we have bitrates, attempt to cap them based on HdcpProtection. HdcpProtection? protection = hdcpSession.GetEffectiveProtection(); SetMaxBitrateForProtectionLevel(protection, adaptiveMediaSource); source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource); } else { Log($"Error creating the AdaptiveMediaSource. Status: {result.Status}, ExtendedError.Message: {result.ExtendedError.Message}, ExtendedError.HResult: {result.ExtendedError.HResult.ToString("X8")}"); return null; } // We use a helper class that logs all the events for the MediaSource: mediaSourceLogger = new MediaSourceLogger(LoggerControl, source); // Save the original Uri. source.CustomProperties["uri"] = uri.ToString(); // You're likely to put a content tracking id into the CustomProperties. source.CustomProperties["contentId"] = Guid.NewGuid().ToString(); var mpItem = new MediaPlaybackItem(source); // We use a helper class that logs all the events for the MediaPlaybackItem: mediaPlaybackItemLogger = new MediaPlaybackItemLogger(LoggerControl, mpItem); HideDescriptionOnSmallScreen(); return mpItem; } private async void HideDescriptionOnSmallScreen() { // On small screens, hide the description text to make room for the video. await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible; }); } #endregion #region AdaptiveMediaSource Event Handlers private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource) { adaptiveMediaSource.DownloadRequested += DownloadRequested; adaptiveMediaSource.DownloadFailed += DownloadFailed; } private void UnregisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource) { if (adaptiveMediaSource != null) { adaptiveMediaSource.DownloadRequested -= DownloadRequested; adaptiveMediaSource.DownloadFailed -= DownloadFailed; } } private async void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args) { if (args.ResourceType == AdaptiveMediaSourceResourceType.Key) { switch (tokenMethod) { case AzureKeyAcquisitionMethod.None: break; case AzureKeyAcquisitionMethod.AuthorizationHeader: // By updating the IHttpFilter KeyHost property here, we ensure it's up to date // before the network request is made. It is the IHttpFilter that will insert // the Authorization header. if (httpClientFilter != null) { httpClientFilter.KeyHost = args.ResourceUri.Host; } break; case AzureKeyAcquisitionMethod.UrlQueryParameter: ModifyKeyRequestUri(args); break; case AzureKeyAcquisitionMethod.ApplicationDownloaded: await AppDownloadedKeyRequest(args); break; default: break; } } } private void ModifyKeyRequestUri(AdaptiveMediaSourceDownloadRequestedEventArgs args) { if (ContentSelectorControl.SelectedModel == null) { return; } // This pattern can be used to modify Uris, for example: // To a redirect traffic to a secondary endpoint // To change an segment request into a byte-range Uri into another resource // Add the Bearer token to the Uri and modify the args.Result.ResourceUri string armoredAuthToken = System.Net.WebUtility.UrlEncode("Bearer=" + ContentSelectorControl.SelectedModel.AesToken); string uriWithTokenParameter = $"{args.ResourceUri.AbsoluteUri}&token={armoredAuthToken}"; args.Result.ResourceUri = new Uri(uriWithTokenParameter); } private async Task AppDownloadedKeyRequest(AdaptiveMediaSourceDownloadRequestedEventArgs args) { if (ContentSelectorControl.SelectedModel == null) { return; } // For AzureKeyAcquisitionMethod.ApplicationDownloaded we do the following: // Call .GetDeferral() to allow asynchronous work to be performed // Get the requested network resource using app code // Set .Result.InputStream or .Result.Buffer with the response data // Complete the deferral to indicate that we are done. // With this pattern, the app has complete control over any downloaded content. // Obtain a deferral so we can perform asynchronous operations. var deferral = args.GetDeferral(); try { var appHttpClientForKeys = new HttpClient(); appHttpClientForKeys.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", ContentSelectorControl.SelectedModel.AesToken); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, args.ResourceUri); HttpResponseMessage response = await appHttpClientForKeys.SendRequestAsync( request, HttpCompletionOption.ResponseHeadersRead).AsTask(ctsForAppHttpClientForKeys.Token); if (response.IsSuccessStatusCode) { args.Result.InputStream = await response.Content.ReadAsInputStreamAsync(); // Alternatively, we could use: // args.Result.Buffer = await response.Content.ReadAsBufferAsync(); } else { // The app code failed. Report this by setting the args.Result.ExtendedStatus. // This will ensure that the AdaptiveMediaSource does not attempt to download the resource // itself, and instead treats the download as having failed. switch (response.StatusCode) { case HttpStatusCode.Unauthorized: // HTTP_E_STATUS_DENIED args.Result.ExtendedStatus = 0x80190191; break; case HttpStatusCode.NotFound: // HTTP_E_STATUS_NOT_FOUND args.Result.ExtendedStatus = 0x80190194; break; default: // HTTP_E_STATUS_UNEXPECTED args.Result.ExtendedStatus = 0x80190001; break; } Log($"Key Download Failed: {response.StatusCode} {args.ResourceUri}"); } } catch (TaskCanceledException) { Log($"Request canceled: {args.ResourceUri}"); } catch (Exception e) { Log($"Key Download Failed: {e.Message} {args.ResourceUri}"); } finally { // Complete the deferral when done. deferral.Complete(); } } private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args) { Log($"DownloadFailed: {args.HttpResponseMessage}, {args.ResourceType}, {args.ResourceUri}"); } #endregion #region AzureKeyAcquisitionMethod enum AzureKeyAcquisitionMethod { None, AuthorizationHeader, UrlQueryParameter, ApplicationDownloaded, } private void AzureMethodSelected_Click(object sender, RoutedEventArgs e) { AzureKeyAcquisitionMethod selectedMethod; string selected = (sender as RadioButton).Tag.ToString(); if (Enum.TryParse(selected, out selectedMethod)) { tokenMethod = selectedMethod; } } #endregion #region HdcpDesiredMinimumProtection /// <summary> /// Handles the radio button selections from the UI and imposes that minimum desired protection /// </summary> private async void HdcpDesiredMinimumProtection_Click(object sender, RoutedEventArgs e) { HdcpProtection desiredMinimumProtection = HdcpProtection.Off; string selected = (sender as RadioButton).Tag.ToString(); if (Enum.TryParse(selected, out desiredMinimumProtection)) { var result = await hdcpSession.SetDesiredMinProtectionAsync(desiredMinimumProtection); HdcpProtection? actualProtection = hdcpSession.GetEffectiveProtection(); if (result != HdcpSetProtectionResult.Success) { Log($"ERROR: Unable to set HdcpProtection.{desiredMinimumProtection}, Error: {result}, Actual HDCP: {actualProtection}"); } else { Log($"HDCP Requested Minimum: {desiredMinimumProtection}, Actual: {actualProtection}"); } } } /// <summary> /// Enforces a fictitious content publisher's rules for bandwidth maximums based on HDCP protection levels. /// </summary> /// <param name="protection">Protection level to use when imposing bandwidth restriction.</param> /// <param name="ams">AdaptiveMediaSource on which to impose restrictions</param> private async void SetMaxBitrateForProtectionLevel(HdcpProtection? protection, AdaptiveMediaSource ams) { await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { EffectiveHdcpProtectionText.Text = protection.ToString(); if (ams != null && ams.AvailableBitrates.Count > 1) { // Get a sorted list of available bitrates. var bitrates = new List<uint>(ams.AvailableBitrates); bitrates.Sort(); // Apply maximum bitrate policy based on a fictitious content publisher's rules. switch (protection) { case HdcpProtection.OnWithTypeEnforcement: // Allow full bitrate. ams.DesiredMaxBitrate = bitrates[bitrates.Count - 1]; DesiredMaxBitrateText.Text = "full bitrate allowed"; break; case HdcpProtection.On: // When there is no HDCP Type 1, make the highest bitrate unavailable. ams.DesiredMaxBitrate = bitrates[bitrates.Count - 2]; DesiredMaxBitrateText.Text = "highest bitrate is unavailable"; break; case HdcpProtection.Off: case null: default: // When there is no HDCP at all (Off), or the system is still trying to determine what // HDCP protection level to apply (null), then make only the lowest bitrate available. ams.DesiredMaxBitrate = bitrates[0]; DesiredMaxBitrateText.Text = "lowest bitrate only"; break; } Log($"Imposed DesiredMaxBitrate={ams.DesiredMaxBitrate} for HdcpProtection.{protection}"); } }); } #endregion #region Utilities private void Log(string message) { LoggerControl.Log(message); } MediaPlayerLogger mediaPlayerLogger; MediaSourceLogger mediaSourceLogger; MediaPlaybackItemLogger mediaPlaybackItemLogger; AdaptiveMediaSourceLogger adaptiveMediaSourceLogger; #endregion } #region IHttpFilter to add an authorization header public class AddAuthorizationHeaderFilter : IHttpFilter { public AddAuthorizationHeaderFilter(IHttpFilter innerFilter) { if (innerFilter == null) { throw new ArgumentException("innerFilter cannot be null."); } this.innerFilter = innerFilter; } internal HttpCredentialsHeaderValue AuthorizationHeader; private IHttpFilter innerFilter; // NOTE: In production, an app might need logic for several failover key-delivery hosts. public string KeyHost { get; set; } public IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> SendRequestAsync(HttpRequestMessage request) { bool isKeyRequest = String.Equals(request.RequestUri.Host, KeyHost, StringComparison.OrdinalIgnoreCase); if (isKeyRequest && AuthorizationHeader != null) { request.Headers.Authorization = AuthorizationHeader; } return innerFilter.SendRequestAsync(request); } public void Dispose() { } } #endregion }
/* Copyright 2014 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 UnityEngine; using System; using System.Collections; using System.Collections.Generic; /* GoogleAnalyticsAndroidV4 handles building hits using the Android SDK. Developers should call the methods in GoogleAnalyticsV4, which will call the appropriate methods in this class if the application is built for Android. */ public class GoogleAnalyticsAndroidV4 : IDisposable { #if UNITY_ANDROID && !UNITY_EDITOR private string trackingCode; private string appVersion; private string appName; private string bundleIdentifier; private int dispatchPeriod; private int sampleFrequency; //private GoogleAnalyticsV4.DebugMode logLevel; private bool anonymizeIP; private bool adIdCollection; private bool dryRun; private int sessionTimeout; private AndroidJavaObject tracker; private AndroidJavaObject logger; private AndroidJavaObject currentActivityObject; private AndroidJavaObject googleAnalyticsSingleton; //private bool startSessionOnNextHit = false; //private bool endSessionOnNextHit = false; internal void InitializeTracker() { Debug.Log("Initializing Google Analytics Android Tracker."); using (AndroidJavaObject googleAnalyticsClass = new AndroidJavaClass("com.google.android.gms.analytics.GoogleAnalytics")) using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { currentActivityObject = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); googleAnalyticsSingleton = googleAnalyticsClass.CallStatic<AndroidJavaObject>("getInstance", currentActivityObject); tracker = googleAnalyticsSingleton.Call<AndroidJavaObject>("newTracker", trackingCode); googleAnalyticsSingleton.Call("setLocalDispatchPeriod", dispatchPeriod); googleAnalyticsSingleton.Call("setDryRun", dryRun); tracker.Call("setSampleRate", (double)sampleFrequency); tracker.Call("setAppName", appName); tracker.Call("setAppId", bundleIdentifier); tracker.Call("setAppVersion", appVersion); tracker.Call("setAnonymizeIp", anonymizeIP); tracker.Call("enableAdvertisingIdCollection", adIdCollection); } } internal void SetTrackerVal(Field fieldName, object value) { object[] args = new object[] { fieldName.ToString(), value }; tracker.Call("set", args); } private void SetSessionOnBuilder(AndroidJavaObject hitBuilder) { } internal void StartSession() { //startSessionOnNextHit = true; } internal void StopSession() { //endSessionOnNextHit = true; } public void SetOptOut(bool optOut) { googleAnalyticsSingleton.Call("setAppOptOut", optOut); } internal void LogScreen (AppViewHitBuilder builder) { tracker.Call("setScreenName", builder.GetScreenName()); AndroidJavaObject eventBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$ScreenViewBuilder"); object[] builtScreenView = new object[] { eventBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtScreenView); } internal void LogEvent(EventHitBuilder builder) { AndroidJavaObject eventBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$EventBuilder"); eventBuilder.Call<AndroidJavaObject>("setCategory", new object[] { builder.GetEventCategory() }); eventBuilder.Call<AndroidJavaObject>("setAction", new object[] { builder.GetEventAction() }); eventBuilder.Call<AndroidJavaObject>("setLabel", new object[] { builder.GetEventLabel() }); eventBuilder.Call<AndroidJavaObject>("setValue", new object[] { builder.GetEventValue() }); object[] builtEvent = new object[] { eventBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtEvent); } internal void LogTransaction(TransactionHitBuilder builder) { AndroidJavaObject transactionBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$TransactionBuilder"); transactionBuilder.Call<AndroidJavaObject>("setTransactionId", new object[] { builder.GetTransactionID() }); transactionBuilder.Call<AndroidJavaObject>("setAffiliation", new object[] { builder.GetAffiliation() }); transactionBuilder.Call<AndroidJavaObject>("setRevenue", new object[] { builder.GetRevenue() }); transactionBuilder.Call<AndroidJavaObject>("setTax", new object[] { builder.GetTax() }); transactionBuilder.Call<AndroidJavaObject>("setShipping", new object[] { builder.GetShipping() }); transactionBuilder.Call<AndroidJavaObject>("setCurrencyCode", new object[] { builder.GetCurrencyCode() }); object[] builtTransaction = new object[] { transactionBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtTransaction); } internal void LogItem(ItemHitBuilder builder) { AndroidJavaObject itemBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$ItemBuilder"); itemBuilder.Call<AndroidJavaObject>("setTransactionId", new object[] { builder.GetTransactionID() }); itemBuilder.Call<AndroidJavaObject>("setName", new object[] { builder.GetName() }); itemBuilder.Call<AndroidJavaObject>("setSku", new object[] { builder.GetSKU() }); itemBuilder.Call<AndroidJavaObject>("setCategory", new object[] { builder.GetCategory() }); itemBuilder.Call<AndroidJavaObject>("setPrice", new object[] { builder.GetPrice() }); itemBuilder.Call<AndroidJavaObject>("setQuantity", new object[] { builder.GetQuantity() }); itemBuilder.Call<AndroidJavaObject>("setCurrencyCode", new object[] { builder.GetCurrencyCode() }); object[] builtItem = new object[] { itemBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtItem); } public void LogException(ExceptionHitBuilder builder) { AndroidJavaObject exceptionBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$ExceptionBuilder"); exceptionBuilder.Call<AndroidJavaObject>("setDescription", new object[] { builder.GetExceptionDescription() }); exceptionBuilder.Call<AndroidJavaObject>("setFatal", new object[] { builder.IsFatal() }); object[] builtException = new object[] { exceptionBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtException); } public void LogSocial(SocialHitBuilder builder) { AndroidJavaObject socialBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$SocialBuilder"); socialBuilder.Call<AndroidJavaObject>("setAction", new object[] { builder.GetSocialAction() }); socialBuilder.Call<AndroidJavaObject>("setNetwork", new object[] { builder.GetSocialNetwork() }); socialBuilder.Call<AndroidJavaObject>("setTarget", new object[] { builder.GetSocialTarget() }); object[] builtSocial = new object[] { socialBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtSocial); } public void LogTiming(TimingHitBuilder builder) { AndroidJavaObject timingBuilder = new AndroidJavaObject("com.google.android.gms.analytics.HitBuilders$TimingBuilder"); timingBuilder.Call<AndroidJavaObject>("setCategory", new object[] { builder.GetTimingCategory() }); timingBuilder.Call<AndroidJavaObject>("setLabel", new object[] { builder.GetTimingLabel() }); timingBuilder.Call<AndroidJavaObject>("setValue", new object[] { builder.GetTimingInterval() }); timingBuilder.Call<AndroidJavaObject>("setVariable", new object[] { builder.GetTimingName() }); object[] builtTiming = new object[] { timingBuilder.Call<AndroidJavaObject>("build") }; tracker.Call("send", builtTiming); } public void DispatchHits() { } public void SetSampleFrequency(int sampleFrequency) { this.sampleFrequency = sampleFrequency; } public void ClearUserIDOverride() { SetTrackerVal(Fields.USER_ID, null); } public void SetTrackingCode(string trackingCode) { this.trackingCode = trackingCode; } public void SetAppName(string appName) { this.appName = appName; } public void SetBundleIdentifier(string bundleIdentifier) { this.bundleIdentifier = bundleIdentifier; } public void SetAppVersion(string appVersion) { this.appVersion = appVersion; } public void SetDispatchPeriod(int dispatchPeriod) { this.dispatchPeriod = dispatchPeriod; } public void SetLogLevelValue(GoogleAnalyticsV4.DebugMode logLevel) { //this.logLevel = logLevel; } public void SetAnonymizeIP(bool anonymizeIP) { this.anonymizeIP = anonymizeIP; } public void SetAdIdCollection(bool adIdCollection) { this.adIdCollection = adIdCollection; } public void SetDryRun(bool dryRun) { this.dryRun = dryRun; } #endif public void Dispose() { #if UNITY_ANDROID && !UNITY_EDITOR googleAnalyticsSingleton.Dispose(); tracker.Dispose(); #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Net.Sockets; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public class SendReceiveTest : ClientWebSocketTestBase { public static bool PartialMessagesSupported => PlatformDetection.ClientWebSocketPartialMessagesSupported; public SendReceiveTest(ITestOutputHelper output) : base(output) { } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(9296)] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_PartialMessageDueToSmallReceiveBuffer_Success(Uri server) { var sendBuffer = new byte[1024]; var sendSegment = new ArraySegment<byte>(sendBuffer); var receiveBuffer = new byte[1024]; var receiveSegment = new ArraySegment<byte>(receiveBuffer); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // The server will read buffers and aggregate it up to 64KB before echoing back a complete message. // But since this test uses a receive buffer that is small, we will get back partial message fragments // as we read them until we read the complete message payload. for (int i = 0; i < 63; i++) { await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, false, ctsDefault.Token); } await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token); WebSocketReceiveResult recvResult = await cws.ReceiveAsync(receiveSegment, ctsDefault.Token); Assert.Equal(false, recvResult.EndOfMessage); while (recvResult.EndOfMessage == false) { recvResult = await cws.ReceiveAsync(receiveSegment, ctsDefault.Token); } await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageDueToSmallReceiveBufferTest", ctsDefault.Token); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported), nameof(PartialMessagesSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_PartialMessageBeforeCompleteMessageArrives_Success(Uri server) { var rand = new Random(); var sendBuffer = new byte[ushort.MaxValue + 1]; rand.NextBytes(sendBuffer); var sendSegment = new ArraySegment<byte>(sendBuffer); // Ask the remote server to echo back received messages without ever signaling "end of message". var ub = new UriBuilder(server); ub.Query = "replyWithPartialMessages"; using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(ub.Uri, TimeOutMilliseconds, _output)) { var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // Send data to the server; the server will reply back with one or more partial messages. We should be // able to consume that data as it arrives, without having to wait for "end of message" to be signaled. await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token); int totalBytesReceived = 0; var receiveBuffer = new byte[sendBuffer.Length]; while (totalBytesReceived < receiveBuffer.Length) { WebSocketReceiveResult recvResult = await cws.ReceiveAsync( new ArraySegment<byte>(receiveBuffer, totalBytesReceived, receiveBuffer.Length - totalBytesReceived), ctsDefault.Token); Assert.Equal(false, recvResult.EndOfMessage); Assert.InRange(recvResult.Count, 0, receiveBuffer.Length - totalBytesReceived); totalBytesReceived += recvResult.Count; } Assert.Equal(receiveBuffer.Length, totalBytesReceived); Assert.Equal<byte>(sendBuffer, receiveBuffer); await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageBeforeCompleteMessageArrives", ctsDefault.Token); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendAsync_SendCloseMessageType_ThrowsArgumentExceptionWithMessage(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); string expectedInnerMessage = ResourceHelper.GetExceptionMessage( "net_WebSockets_Argument_InvalidMessageType", "Close", "SendAsync", "Binary", "Text", "CloseOutputAsync"); var expectedException = new ArgumentException(expectedInnerMessage, "messageType"); string expectedMessage = expectedException.Message; AssertExtensions.Throws<ArgumentException>("messageType", () => { Task t = cws.SendAsync(new ArraySegment<byte>(), WebSocketMessageType.Close, true, cts.Token); }); Assert.Equal(WebSocketState.Open, cws.State); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendAsync_MultipleOutstandingSendOperations_Throws(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Task[] tasks = new Task[10]; try { for (int i = 0; i < tasks.Length; i++) { tasks[i] = cws.SendAsync( WebSocketData.GetBufferFromText("hello"), WebSocketMessageType.Text, true, cts.Token); } Task.WaitAll(tasks); Assert.Equal(WebSocketState.Open, cws.State); } catch (AggregateException ag) { foreach (var ex in ag.InnerExceptions) { if (ex is InvalidOperationException) { Assert.Equal( ResourceHelper.GetExceptionMessage( "net_Websockets_AlreadyOneOutstandingOperation", "SendAsync"), ex.Message); Assert.Equal(WebSocketState.Aborted, cws.State); } else if (ex is WebSocketException) { // Multiple cases. Assert.Equal(WebSocketState.Aborted, cws.State); WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode; Assert.True( (errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success), "WebSocketErrorCode"); } else { Assert.IsAssignableFrom<OperationCanceledException>(ex); } } } } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Task[] tasks = new Task[2]; await cws.SendAsync( WebSocketData.GetBufferFromText(".delay5sec"), WebSocketMessageType.Text, true, cts.Token); var recvBuffer = new byte[100]; var recvSegment = new ArraySegment<byte>(recvBuffer); try { for (int i = 0; i < tasks.Length; i++) { tasks[i] = cws.ReceiveAsync(recvSegment, cts.Token); } Task.WaitAll(tasks); Assert.Equal(WebSocketState.Open, cws.State); } catch (AggregateException ag) { foreach (var ex in ag.InnerExceptions) { if (ex is InvalidOperationException) { Assert.Equal( ResourceHelper.GetExceptionMessage( "net_Websockets_AlreadyOneOutstandingOperation", "ReceiveAsync"), ex.Message); Assert.Equal(WebSocketState.Aborted, cws.State); } else if (ex is WebSocketException) { // Multiple cases. Assert.Equal(WebSocketState.Aborted, cws.State); WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode; Assert.True( (errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success), "WebSocketErrorCode"); } else if (ex is OperationCanceledException) { Assert.Equal(WebSocketState.Aborted, cws.State); } else { Assert.True(false, "Unexpected exception: " + ex.Message); } } } } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendAsync_SendZeroLengthPayloadAsEndOfMessage_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); string message = "hello"; await cws.SendAsync( WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, false, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); await cws.SendAsync(new ArraySegment<byte>(new byte[0]), WebSocketMessageType.Text, true, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); var recvBuffer = new byte[100]; var receiveSegment = new ArraySegment<byte>(recvBuffer); WebSocketReceiveResult recvRet = await cws.ReceiveAsync(receiveSegment, cts.Token); Assert.Equal(WebSocketState.Open, cws.State); Assert.Equal(message.Length, recvRet.Count); Assert.Equal(WebSocketMessageType.Text, recvRet.MessageType); Assert.Equal(true, recvRet.EndOfMessage); Assert.Equal(null, recvRet.CloseStatus); Assert.Equal(null, recvRet.CloseStatusDescription); var recvSegment = new ArraySegment<byte>(receiveSegment.Array, receiveSegment.Offset, recvRet.Count); Assert.Equal(message, WebSocketData.GetTextFromBuffer(recvSegment)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_VaryingLengthBuffers_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var rand = new Random(); var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); // Values chosen close to boundaries in websockets message length handling as well // as in vectors used in mask application. foreach (int bufferSize in new int[] { 1, 3, 4, 5, 31, 32, 33, 125, 126, 127, 128, ushort.MaxValue - 1, ushort.MaxValue, ushort.MaxValue + 1, ushort.MaxValue * 2 }) { byte[] sendBuffer = new byte[bufferSize]; rand.NextBytes(sendBuffer); await cws.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, ctsDefault.Token); byte[] receiveBuffer = new byte[bufferSize]; int totalReceived = 0; while (true) { WebSocketReceiveResult recvResult = await cws.ReceiveAsync( new ArraySegment<byte>(receiveBuffer, totalReceived, receiveBuffer.Length - totalReceived), ctsDefault.Token); Assert.InRange(recvResult.Count, 0, receiveBuffer.Length - totalReceived); totalReceived += recvResult.Count; if (recvResult.EndOfMessage) break; } Assert.Equal(receiveBuffer.Length, totalReceived); Assert.Equal<byte>(sendBuffer, receiveBuffer); } await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "SendReceive_VaryingLengthBuffers_Success", ctsDefault.Token); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task SendReceive_Concurrent_Success(Uri server) { using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output)) { var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds); byte[] receiveBuffer = new byte[10]; byte[] sendBuffer = new byte[10]; for (int i = 0; i < sendBuffer.Length; i++) { sendBuffer[i] = (byte)i; } for (int i = 0; i < sendBuffer.Length; i++) { Task<WebSocketReceiveResult> receive = cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer, receiveBuffer.Length - i - 1, 1), ctsDefault.Token); Task send = cws.SendAsync(new ArraySegment<byte>(sendBuffer, i, 1), WebSocketMessageType.Binary, true, ctsDefault.Token); await Task.WhenAll(receive, send); Assert.Equal(1, receive.Result.Count); } await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "SendReceive_VaryingLengthBuffers_Success", ctsDefault.Token); Array.Reverse(receiveBuffer); Assert.Equal<byte>(sendBuffer, receiveBuffer); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(WebSocketsSupported))] public async Task SendReceive_ConnectionClosedPrematurely_ReceiveAsyncFailsAndWebSocketStateUpdated() { var options = new LoopbackServer.Options { WebSocketEndpoint = true }; Func<ClientWebSocket, Socket, Uri, Task> connectToServerThatAbortsConnection = async (clientSocket, server, url) => { AutoResetEvent pendingReceiveAsyncPosted = new AutoResetEvent(false); // Start listening for incoming connections on the server side. Task<List<string>> acceptTask = LoopbackServer.AcceptSocketAsync(server, async (socket, stream, reader, writer) => { // Complete the WebSocket upgrade. After this is done, the client-side ConnectAsync should complete. Assert.True(await LoopbackServer.WebSocketHandshakeAsync(socket, reader, writer)); // Wait for client-side ConnectAsync to complete and for a pending ReceiveAsync to be posted. pendingReceiveAsyncPosted.WaitOne(TimeOutMilliseconds); // Close the underlying connection prematurely (without sending a WebSocket Close frame). socket.Shutdown(SocketShutdown.Both); socket.Close(); return null; }, options); // Initiate a connection attempt. var cts = new CancellationTokenSource(TimeOutMilliseconds); await clientSocket.ConnectAsync(url, cts.Token); // Post a pending ReceiveAsync before the TCP connection is torn down. var recvBuffer = new byte[100]; var recvSegment = new ArraySegment<byte>(recvBuffer); Task pendingReceiveAsync = clientSocket.ReceiveAsync(recvSegment, cts.Token); pendingReceiveAsyncPosted.Set(); // Wait for the server to close the underlying connection. acceptTask.Wait(cts.Token); // Validate I/O errors and socket state. if (!PlatformDetection.IsWindows) { _output.WriteLine("[Non-Windows] ManagedWebSocket-based implementation."); WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); WebSocketException newReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => clientSocket.ReceiveAsync(recvSegment, cts.Token)); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, newReceiveException.WebSocketErrorCode); Assert.Equal(WebSocketState.Open, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } else if (PlatformDetection.IsFullFramework) { _output.WriteLine("[Windows] ManagedWebSocket-based implementation."); WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); WebSocketException newReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => clientSocket.ReceiveAsync(recvSegment, cts.Token)); Assert.Equal(WebSocketError.Success, newReceiveException.WebSocketErrorCode); Assert.Equal( ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"), newReceiveException.Message); Assert.Equal(WebSocketState.Aborted, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } else if (PlatformDetection.IsUap) { _output.WriteLine("WinRTWebSocket-based implementation."); const uint WININET_E_CONNECTION_ABORTED = 0x80072EFE; WebSocketException pendingReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => pendingReceiveAsync); Assert.Equal(WebSocketError.ConnectionClosedPrematurely, pendingReceiveException.WebSocketErrorCode); Assert.NotNull(pendingReceiveException.InnerException); Assert.Equal(WININET_E_CONNECTION_ABORTED, (uint)pendingReceiveException.InnerException.HResult); WebSocketException newReceiveException = await Assert.ThrowsAsync<WebSocketException>(() => clientSocket.ReceiveAsync(recvSegment, cts.Token)); Assert.Equal(WebSocketError.Success, newReceiveException.WebSocketErrorCode); Assert.Equal( ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"), newReceiveException.Message); Assert.Equal(WebSocketState.Aborted, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } else { _output.WriteLine("WinHttpWebSocket-based implementation."); const uint WININET_E_CONNECTION_RESET = 0x80072eff; Win32Exception pendingReceiveException = await Assert.ThrowsAnyAsync<Win32Exception>(() => pendingReceiveAsync); Assert.Equal(WININET_E_CONNECTION_RESET, (uint)pendingReceiveException.HResult); Win32Exception newReceiveException = await Assert.ThrowsAnyAsync<Win32Exception>(() => clientSocket.ReceiveAsync(recvSegment, cts.Token)); Assert.Equal(WININET_E_CONNECTION_RESET, (uint)newReceiveException.HResult); Assert.Equal(WebSocketState.Open, clientSocket.State); Assert.Null(clientSocket.CloseStatus); } }; await LoopbackServer.CreateServerAsync(async (server, url) => { using (ClientWebSocket clientSocket = new ClientWebSocket()) { await connectToServerThatAbortsConnection(clientSocket, server, url); } }, options); } } }
//******************************************************************************************************************************************************************************************// // Public Domain // // // // Written by Peter O. in 2014. // // // // Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ // // // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // //******************************************************************************************************************************************************************************************// using System; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers { internal sealed class FastIntegerFixed : IComparable<FastIntegerFixed> { // NOTE: Integer modes are mutually exclusive private enum IntegerMode : byte { SmallValue = 0, LargeValue = 2, } private const int CacheFirst = -24; private const int CacheLast = 128; private readonly int smallValue; // if integerMode is 0 private readonly EInteger largeValue; // if integerMode is 2 private readonly IntegerMode integerMode; public static readonly FastIntegerFixed Zero = new FastIntegerFixed( IntegerMode.SmallValue, 0, null); public static readonly FastIntegerFixed One = new FastIntegerFixed( IntegerMode.SmallValue, 1, null); private static readonly FastIntegerFixed[] Cache = FastIntegerFixedCache(CacheFirst, CacheLast); private static FastIntegerFixed[] FastIntegerFixedCache( int first, int last) { #if DEBUG if (first < -65535) { throw new ArgumentException("first (" + first + ") is not greater or equal" + "\u0020to " + (-65535)); } if (first > 65535) { throw new ArgumentException("first (" + first + ") is not less or equal to" + "\u002065535"); } if (last < -65535) { throw new ArgumentException("last (" + last + ") is not greater or equal" + "\u0020to -65535"); } if (last > 65535) { throw new ArgumentException("last (" + last + ") is not less or equal to" + "65535"); } #endif FastIntegerFixed[] cache = new FastIntegerFixed[(last - first) + 1]; for (int i = first; i <= last; ++i) { if (i == 0) { cache[i - first] = Zero; } else if (i == 1) { cache[i - first] = One; } else { cache[i - first] = new FastIntegerFixed(IntegerMode.SmallValue, i, null); } } return cache; } private FastIntegerFixed( IntegerMode integerMode, int smallValue, EInteger largeValue) { this.integerMode = integerMode; this.smallValue = smallValue; this.largeValue = largeValue; } public override bool Equals(object obj) { if (!(obj is FastIntegerFixed fi)) { return false; } if (this.integerMode != fi.integerMode) { return false; } switch (this.integerMode) { case IntegerMode.SmallValue: return this.smallValue == fi.smallValue; case IntegerMode.LargeValue: return this.largeValue.Equals(fi.largeValue); default: return true; } } public override int GetHashCode() { int hash = this.integerMode.GetHashCode(); switch (this.integerMode) { case IntegerMode.SmallValue: hash = unchecked((hash * 31) + this.smallValue); break; case IntegerMode.LargeValue: hash = unchecked((hash * 31) + this.largeValue.GetHashCode()); break; } return hash; } internal static FastIntegerFixed FromInt32(int intVal) { return (intVal >= CacheFirst && intVal <= CacheLast) ? Cache[intVal - CacheFirst] : new FastIntegerFixed(IntegerMode.SmallValue, intVal, null); } internal static FastIntegerFixed FromInt64(long longVal) { return (longVal >= Int32.MinValue && longVal <= Int32.MaxValue) ? FromInt32((int)longVal) : new FastIntegerFixed( IntegerMode.LargeValue, 0, EInteger.FromInt64(longVal)); } internal static FastIntegerFixed FromBig(EInteger bigintVal) { return bigintVal.CanFitInInt32() ? FromInt32(bigintVal.ToInt32Unchecked()) : new FastIntegerFixed(IntegerMode.LargeValue, 0, bigintVal); } internal int ToInt32() { return (this.integerMode == IntegerMode.SmallValue) ? this.smallValue : this.largeValue.ToInt32Unchecked(); } public static FastIntegerFixed FromFastInteger(FastInteger fi) { if (fi.CanFitInInt32()) { return FromInt32(fi.ToInt32()); } else { return FastIntegerFixed.FromBig(fi.ToEInteger()); } } public FastInteger ToFastInteger() { if (this.integerMode == IntegerMode.SmallValue) { return new FastInteger(this.smallValue); } else { return FastInteger.FromBig(this.largeValue); } } public FastIntegerFixed Increment() { if (this.integerMode == IntegerMode.SmallValue && this.smallValue != Int32.MaxValue) { return FromInt32(this.smallValue + 1); } else { return Add(this, FastIntegerFixed.One); } } public int Mod(int value) { if (value < 0) { throw new NotSupportedException(); } if (this.integerMode == IntegerMode.SmallValue && this.smallValue >= 0) { return this.smallValue % value; } else { EInteger retval = this.ToEInteger().Remainder(EInteger.FromInt32( value)); return retval.ToInt32Checked(); } } public static FastIntegerFixed Add(FastIntegerFixed a, FastIntegerFixed b) { if (a.integerMode == IntegerMode.SmallValue && b.integerMode == IntegerMode.SmallValue) { if (a.smallValue == 0) { return b; } if (b.smallValue == 0) { return a; } if (((a.smallValue | b.smallValue) >> 30) == 0) { return FromInt32(a.smallValue + b.smallValue); } if ((a.smallValue < 0 && b.smallValue >= Int32.MinValue - a.smallValue) || (a.smallValue > 0 && b.smallValue <= Int32.MaxValue - a.smallValue)) { return FromInt32(a.smallValue + b.smallValue); } } EInteger bigA = a.ToEInteger(); EInteger bigB = b.ToEInteger(); return FastIntegerFixed.FromBig(bigA.Add(bigB)); } public static FastIntegerFixed Subtract( FastIntegerFixed a, FastIntegerFixed b) { if (a.integerMode == IntegerMode.SmallValue && b.integerMode == IntegerMode.SmallValue) { if (b.smallValue == 0) { return a; } if ( (b.smallValue < 0 && Int32.MaxValue + b.smallValue >= a.smallValue) || (b.smallValue > 0 && Int32.MinValue + b.smallValue <= a.smallValue)) { return FromInt32(a.smallValue - b.smallValue); } } EInteger bigA = a.ToEInteger(); EInteger bigB = b.ToEInteger(); return FastIntegerFixed.FromBig(bigA.Subtract(bigB)); } public FastIntegerFixed Add(int ib) { FastIntegerFixed a = this; if (this.integerMode == IntegerMode.SmallValue) { if (ib == 0) { return this; } if (this.smallValue == 0) { return FromInt32(ib); } if (((a.smallValue | ib) >> 30) == 0) { return FromInt32(a.smallValue + ib); } if ((a.smallValue < 0 && ib >= Int32.MinValue - a.smallValue) || (a.smallValue > 0 && ib <= Int32.MaxValue - a.smallValue)) { return FromInt32(a.smallValue + ib); } } EInteger bigA = a.ToEInteger(); return FastIntegerFixed.FromBig(bigA.Add(ib)); } public FastIntegerFixed Subtract(int ib) { if (ib == 0) { return this; } if (this.integerMode == IntegerMode.SmallValue) { if ( (ib < 0 && Int32.MaxValue + ib >= this.smallValue) || (ib > 0 && Int32.MinValue + ib <= this.smallValue)) { return FromInt32(this.smallValue - ib); } } EInteger bigA = this.ToEInteger(); return FastIntegerFixed.FromBig(bigA.Subtract(ib)); } public FastIntegerFixed Add( FastIntegerFixed b) { return Add(this, b); } public FastIntegerFixed Subtract( FastIntegerFixed b) { return Subtract(this, b); } public FastIntegerFixed Add( EInteger b) { if (this.integerMode == IntegerMode.SmallValue && b.CanFitInInt32()) { return this.Add(b.ToInt32Unchecked()); } else { return FastIntegerFixed.FromBig( this.ToEInteger().Add(b)); } } public FastIntegerFixed Subtract( EInteger b) { if (this.integerMode == IntegerMode.SmallValue && b.CanFitInInt32()) { return this.Subtract(b.ToInt32Unchecked()); } else { return FastIntegerFixed.FromBig( this.ToEInteger().Subtract(b)); } } public FastIntegerFixed Abs() { switch (this.integerMode) { case IntegerMode.SmallValue: if (this.smallValue == Int32.MinValue) { return FastIntegerFixed.FromInt32(Int32.MaxValue).Increment(); } else if (this.smallValue < 0) { return FastIntegerFixed.FromInt32(-this.smallValue); } else { return this; } case IntegerMode.LargeValue: return this.largeValue.Sign < 0 ? new FastIntegerFixed(IntegerMode.LargeValue, 0, this.largeValue.Abs()) : this; default: throw new InvalidOperationException(); } } public FastIntegerFixed Negate() { switch (this.integerMode) { case IntegerMode.SmallValue: if (this.smallValue == Int32.MinValue) { return FastIntegerFixed.FromInt32(Int32.MaxValue).Increment(); } else { return FastIntegerFixed.FromInt32(-this.smallValue); } case IntegerMode.LargeValue: return new FastIntegerFixed( IntegerMode.LargeValue, 0, this.largeValue.Negate()); default: throw new InvalidOperationException(); } } public int CompareTo(EInteger evalue) { switch (this.integerMode) { case IntegerMode.SmallValue: return -evalue.CompareTo(this.smallValue); case IntegerMode.LargeValue: return this.largeValue.CompareTo(evalue); default: throw new InvalidOperationException(); } } public int CompareTo(FastInteger fint) { switch (this.integerMode) { case IntegerMode.SmallValue: return -fint.CompareToInt(this.smallValue); case IntegerMode.LargeValue: return -fint.CompareTo(this.largeValue); default: throw new InvalidOperationException(); } } public int CompareTo(FastIntegerFixed val) { switch (this.integerMode) { case IntegerMode.SmallValue: switch (val.integerMode) { case IntegerMode.SmallValue: int vsv = val.smallValue; return (this.smallValue == vsv) ? 0 : (this.smallValue < vsv ? -1 : 1); case IntegerMode.LargeValue: return -val.largeValue.CompareTo(this.smallValue); } break; case IntegerMode.LargeValue: return this.largeValue.CompareTo(val.ToEInteger()); } throw new InvalidOperationException(); } internal FastIntegerFixed Copy() { switch (this.integerMode) { case IntegerMode.SmallValue: return FromInt32(this.smallValue); case IntegerMode.LargeValue: return FastIntegerFixed.FromBig(this.largeValue); default: throw new InvalidOperationException(); } } internal bool IsEvenNumber { get { switch (this.integerMode) { case IntegerMode.SmallValue: return (this.smallValue & 1) == 0; case IntegerMode.LargeValue: return this.largeValue.IsEven; default: throw new InvalidOperationException(); } } } internal bool CanFitInInt32() { return this.integerMode == IntegerMode.SmallValue || this.largeValue.CanFitInInt32(); } /// <summary>This is an internal API.</summary> /// <returns>A text string.</returns> public override string ToString() { switch (this.integerMode) { case IntegerMode.SmallValue: return FastInteger.IntToString(this.smallValue); case IntegerMode.LargeValue: return this.largeValue.ToString(); default: return String.Empty; } } internal int Sign { get { switch (this.integerMode) { case IntegerMode.SmallValue: return (this.smallValue == 0) ? 0 : ((this.smallValue < 0) ? -1 : 1); case IntegerMode.LargeValue: return this.largeValue.Sign; default: return 0; } } } internal bool IsValueZero { get { switch (this.integerMode) { case IntegerMode.SmallValue: return this.smallValue == 0; case IntegerMode.LargeValue: return this.largeValue.IsZero; default: return false; } } } internal bool CanFitInInt64() { switch (this.integerMode) { case IntegerMode.SmallValue: return true; case IntegerMode.LargeValue: return this.largeValue .CanFitInInt64(); default: throw new InvalidOperationException(); } } internal long ToInt64() { switch (this.integerMode) { case IntegerMode.SmallValue: return (long)this.smallValue; case IntegerMode.LargeValue: return this.largeValue .ToInt64Unchecked(); default: throw new InvalidOperationException(); } } internal int CompareToInt64(long valLong) { switch (this.integerMode) { case IntegerMode.SmallValue: return (valLong == this.smallValue) ? 0 : (this.smallValue < valLong ? -1 : 1); case IntegerMode.LargeValue: return this.largeValue.CompareTo(valLong); default: return 0; } } internal int CompareToInt(int val) { switch (this.integerMode) { case IntegerMode.SmallValue: return (val == this.smallValue) ? 0 : (this.smallValue < val ? -1 : 1); case IntegerMode.LargeValue: return this.largeValue.CompareTo((EInteger)val); default: return 0; } } internal EInteger ToEInteger() { switch (this.integerMode) { case IntegerMode.SmallValue: return EInteger.FromInt32(this.smallValue); case IntegerMode.LargeValue: return this.largeValue; default: throw new InvalidOperationException(); } } } }
// dnlib: See LICENSE.txt for more info using System; #if THREAD_SAFE using ThreadSafe = dnlib.Threading.Collections; #else using ThreadSafe = System.Collections.Generic; #endif namespace dnlib.DotNet { /// <summary> /// The table row can be referenced by a MD token /// </summary> public interface IMDTokenProvider { /// <summary> /// Returns the metadata token /// </summary> MDToken MDToken { get; } /// <summary> /// Gets/sets the row ID /// </summary> uint Rid { get; set; } } /// <summary> /// All <c>*MD</c> classes implement this interface. /// </summary> public interface IMDTokenProviderMD : IMDTokenProvider { /// <summary> /// Gets the original row ID /// </summary> uint OrigRid { get; } } /// <summary> /// An assembly. Implemented by <see cref="AssemblyRef"/>, <see cref="AssemblyDef"/> and /// <see cref="AssemblyNameInfo"/>. /// </summary> public interface IAssembly : IFullName { /// <summary> /// The assembly version /// </summary> Version Version { get; set; } /// <summary> /// Assembly flags /// </summary> AssemblyAttributes Attributes { get; set; } /// <summary> /// Public key or public key token /// </summary> PublicKeyBase PublicKeyOrToken { get; } /// <summary> /// Locale, aka culture /// </summary> UTF8String Culture { get; set; } /// <summary> /// Gets the full name of the assembly but use a public key token /// </summary> string FullNameToken { get; } /// <summary> /// Gets/sets the <see cref="AssemblyAttributes.PublicKey"/> bit /// </summary> bool HasPublicKey { get; set; } /// <summary> /// Gets/sets the processor architecture /// </summary> AssemblyAttributes ProcessorArchitecture { get; set; } /// <summary> /// Gets/sets the processor architecture /// </summary> AssemblyAttributes ProcessorArchitectureFull { get; set; } /// <summary> /// <c>true</c> if unspecified processor architecture /// </summary> bool IsProcessorArchitectureNone { get; } /// <summary> /// <c>true</c> if neutral (PE32) architecture /// </summary> bool IsProcessorArchitectureMSIL { get; } /// <summary> /// <c>true</c> if x86 (PE32) architecture /// </summary> bool IsProcessorArchitectureX86 { get; } /// <summary> /// <c>true</c> if IA-64 (PE32+) architecture /// </summary> bool IsProcessorArchitectureIA64 { get; } /// <summary> /// <c>true</c> if x64 (PE32+) architecture /// </summary> bool IsProcessorArchitectureX64 { get; } /// <summary> /// <c>true</c> if ARM (PE32) architecture /// </summary> bool IsProcessorArchitectureARM { get; } /// <summary> /// <c>true</c> if eg. reference assembly (not runnable) /// </summary> bool IsProcessorArchitectureNoPlatform { get; } /// <summary> /// Gets/sets the <see cref="AssemblyAttributes.PA_Specified"/> bit /// </summary> bool IsProcessorArchitectureSpecified { get; set; } /// <summary> /// Gets/sets the <see cref="AssemblyAttributes.EnableJITcompileTracking"/> bit /// </summary> bool EnableJITcompileTracking { get; set; } /// <summary> /// Gets/sets the <see cref="AssemblyAttributes.DisableJITcompileOptimizer"/> bit /// </summary> bool DisableJITcompileOptimizer { get; set; } /// <summary> /// Gets/sets the <see cref="AssemblyAttributes.Retargetable"/> bit /// </summary> bool IsRetargetable { get; set; } /// <summary> /// Gets/sets the content type /// </summary> AssemblyAttributes ContentType { get; set; } /// <summary> /// <c>true</c> if content type is <c>Default</c> /// </summary> bool IsContentTypeDefault { get; } /// <summary> /// <c>true</c> if content type is <c>WindowsRuntime</c> /// </summary> bool IsContentTypeWindowsRuntime { get; } } public static partial class Extensions { /// <summary> /// Checks whether <paramref name="asm"/> appears to be the core library (eg. /// mscorlib, System.Runtime or corefx) /// </summary> /// <param name="asm">The assembly</param> public static bool IsCorLib(this IAssembly asm) { string asmName; return asm != null && UTF8String.IsNullOrEmpty(asm.Culture) && ((asmName = UTF8String.ToSystemStringOrEmpty(asm.Name)).Equals("mscorlib", StringComparison.OrdinalIgnoreCase) || asmName.Equals("System.Runtime", StringComparison.OrdinalIgnoreCase) || asmName.Equals("corefx", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Converts <paramref name="asm"/> to a <see cref="AssemblyRef"/> instance /// </summary> /// <param name="asm">The assembly</param> /// <returns>A new <see cref="AssemblyRef"/> instance</returns> public static AssemblyRef ToAssemblyRef(this IAssembly asm) { if (asm == null) return null; // Always create a new one, even if it happens to be an AssemblyRef return new AssemblyRefUser(asm.Name, asm.Version, asm.PublicKeyOrToken, asm.Culture) { Attributes = asm.Attributes }; } /// <summary> /// Converts <paramref name="type"/> to a <see cref="TypeSig"/> /// </summary> /// <param name="type">The type</param> /// <param name="checkValueType"><c>true</c> if we should try to figure out whether /// <paramref name="type"/> is a <see cref="ValueType"/></param> /// <returns>A <see cref="TypeSig"/> instance or <c>null</c> if <paramref name="type"/> /// is invalid</returns> public static TypeSig ToTypeSig(this ITypeDefOrRef type, bool checkValueType = true) { if (type == null) return null; var module = type.Module; if (module != null) { var corLibType = module.CorLibTypes.GetCorLibTypeSig(type); if (corLibType != null) return corLibType; } var td = type as TypeDef; if (td != null) return CreateClassOrValueType(type, checkValueType ? td.IsValueType : false); var tr = type as TypeRef; if (tr != null) { if (checkValueType) td = tr.Resolve(); return CreateClassOrValueType(type, td == null ? false : td.IsValueType); } var ts = type as TypeSpec; if (ts != null) return ts.TypeSig; return null; } static TypeSig CreateClassOrValueType(ITypeDefOrRef type, bool isValueType) { if (isValueType) return new ValueTypeSig(type); return new ClassSig(type); } /// <summary> /// Returns a <see cref="TypeDefOrRefSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="TypeDefOrRefSig"/> or <c>null</c> if it's not a /// <see cref="TypeDefOrRefSig"/></returns> public static TypeDefOrRefSig TryGetTypeDefOrRefSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as TypeDefOrRefSig; } /// <summary> /// Returns a <see cref="ClassOrValueTypeSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ClassOrValueTypeSig"/> or <c>null</c> if it's not a /// <see cref="ClassOrValueTypeSig"/></returns> public static ClassOrValueTypeSig TryGetClassOrValueTypeSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as ClassOrValueTypeSig; } /// <summary> /// Returns a <see cref="ValueTypeSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ValueTypeSig"/> or <c>null</c> if it's not a /// <see cref="ValueTypeSig"/></returns> public static ValueTypeSig TryGetValueTypeSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as ValueTypeSig; } /// <summary> /// Returns a <see cref="ClassSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ClassSig"/> or <c>null</c> if it's not a /// <see cref="ClassSig"/></returns> public static ClassSig TryGetClassSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as ClassSig; } /// <summary> /// Returns a <see cref="GenericSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericSig"/> or <c>null</c> if it's not a /// <see cref="GenericSig"/></returns> public static GenericSig TryGetGenericSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as GenericSig; } /// <summary> /// Returns a <see cref="GenericVar"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericVar"/> or <c>null</c> if it's not a /// <see cref="GenericVar"/></returns> public static GenericVar TryGetGenericVar(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as GenericVar; } /// <summary> /// Returns a <see cref="GenericMVar"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericMVar"/> or <c>null</c> if it's not a /// <see cref="GenericMVar"/></returns> public static GenericMVar TryGetGenericMVar(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as GenericMVar; } /// <summary> /// Returns a <see cref="GenericInstSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="GenericInstSig"/> or <c>null</c> if it's not a /// <see cref="GenericInstSig"/></returns> public static GenericInstSig TryGetGenericInstSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as GenericInstSig; } /// <summary> /// Returns a <see cref="PtrSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="PtrSig"/> or <c>null</c> if it's not a /// <see cref="PtrSig"/></returns> public static PtrSig TryGetPtrSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as PtrSig; } /// <summary> /// Returns a <see cref="ByRefSig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ByRefSig"/> or <c>null</c> if it's not a /// <see cref="ByRefSig"/></returns> public static ByRefSig TryGetByRefSig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as ByRefSig; } /// <summary> /// Returns a <see cref="ArraySig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="ArraySig"/> or <c>null</c> if it's not a /// <see cref="ArraySig"/></returns> public static ArraySig TryGetArraySig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as ArraySig; } /// <summary> /// Returns a <see cref="SZArraySig"/> /// </summary> /// <param name="type">The type</param> /// <returns>A <see cref="SZArraySig"/> or <c>null</c> if it's not a /// <see cref="SZArraySig"/></returns> public static SZArraySig TryGetSZArraySig(this ITypeDefOrRef type) { var ts = type as TypeSpec; return ts == null ? null : ts.TypeSig.RemovePinnedAndModifiers() as SZArraySig; } /// <summary> /// Returns the base type of <paramref name="tdr"/>. Throws if we can't resolve /// a <see cref="TypeRef"/>. /// </summary> /// <param name="tdr">The type</param> /// <returns>The base type or <c>null</c> if there's no base type</returns> public static ITypeDefOrRef GetBaseTypeThrow(this ITypeDefOrRef tdr) { return tdr.GetBaseType(true); } /// <summary> /// Returns the base type of <paramref name="tdr"/> /// </summary> /// <param name="tdr">The type</param> /// <param name="throwOnResolveFailure"><c>true</c> if we should throw if we can't /// resolve a <see cref="TypeRef"/>. <c>false</c> if we should ignore the error and /// just return <c>null</c>.</param> /// <returns>The base type or <c>null</c> if there's no base type, or if /// <paramref name="throwOnResolveFailure"/> is <c>true</c> and we couldn't resolve /// a <see cref="TypeRef"/></returns> public static ITypeDefOrRef GetBaseType(this ITypeDefOrRef tdr, bool throwOnResolveFailure = false) { var td = tdr as TypeDef; if (td != null) return td.BaseType; var tr = tdr as TypeRef; if (tr != null) { td = throwOnResolveFailure ? tr.ResolveThrow() : tr.Resolve(); return td == null ? null : td.BaseType; } var ts = tdr as TypeSpec; if (ts == null) return null; var git = ts.TypeSig.ToGenericInstSig(); if (git != null) { var genType = git.GenericType; tdr = genType == null ? null : genType.TypeDefOrRef; } else { var sig = ts.TypeSig.ToTypeDefOrRefSig(); tdr = sig == null ? null : sig.TypeDefOrRef; } td = tdr as TypeDef; if (td != null) return td.BaseType; tr = tdr as TypeRef; if (tr != null) { td = throwOnResolveFailure ? tr.ResolveThrow() : tr.Resolve(); return td == null ? null : td.BaseType; } return null; } /// <summary> /// Gets the scope type, resolves it, and returns the <see cref="TypeDef"/> /// </summary> /// <param name="tdr">Type</param> /// <returns>A <see cref="TypeDef"/> or <c>null</c> if input was <c>null</c> or if we /// couldn't resolve the reference.</returns> public static TypeDef ResolveTypeDef(this ITypeDefOrRef tdr) { var td = tdr as TypeDef; if (td != null) return td; var tr = tdr as TypeRef; if (tr != null) return tr.Resolve(); if (tdr == null) return null; tdr = tdr.ScopeType; td = tdr as TypeDef; if (td != null) return td; tr = tdr as TypeRef; if (tr != null) return tr.Resolve(); return null; } /// <summary> /// Gets the scope type, resolves it, and returns the <see cref="TypeDef"/> /// </summary> /// <param name="tdr">Type</param> /// <returns>A <see cref="TypeDef"/> instance.</returns> /// <exception cref="TypeResolveException">If the type couldn't be resolved</exception> public static TypeDef ResolveTypeDefThrow(this ITypeDefOrRef tdr) { var td = tdr as TypeDef; if (td != null) return td; var tr = tdr as TypeRef; if (tr != null) return tr.ResolveThrow(); if (tdr == null) throw new TypeResolveException("Can't resolve a null pointer"); tdr = tdr.ScopeType; td = tdr as TypeDef; if (td != null) return td; tr = tdr as TypeRef; if (tr != null) return tr.ResolveThrow(); throw new TypeResolveException(string.Format("Could not resolve type: {0} ({1})", tdr, tdr == null ? null : tdr.DefinitionAssembly)); } /// <summary> /// Resolves an <see cref="IField"/> to a <see cref="FieldDef"/>. Returns <c>null</c> if it /// was not possible to resolve it. See also <see cref="ResolveFieldDefThrow"/> /// </summary> /// <param name="field">Field to resolve</param> /// <returns>The <see cref="FieldDef"/> or <c>null</c> if <paramref name="field"/> is /// <c>null</c> or if it wasn't possible to resolve it (the field doesn't exist or its /// assembly couldn't be loaded)</returns> public static FieldDef ResolveFieldDef(this IField field) { var fd = field as FieldDef; if (fd != null) return fd; var mr = field as MemberRef; if (mr != null) return mr.ResolveField(); return null; } /// <summary> /// Resolves an <see cref="IField"/> to a <see cref="FieldDef"/> and throws an exception if /// it was not possible to resolve it. See also <see cref="ResolveFieldDef"/> /// </summary> /// <param name="field">Field to resolve</param> /// <returns>The <see cref="FieldDef"/></returns> public static FieldDef ResolveFieldDefThrow(this IField field) { var fd = field as FieldDef; if (fd != null) return fd; var mr = field as MemberRef; if (mr != null) return mr.ResolveFieldThrow(); throw new MemberRefResolveException(string.Format("Could not resolve field: {0}", field)); } /// <summary> /// Resolves an <see cref="IMethod"/> to a <see cref="MethodDef"/>. Returns <c>null</c> if it /// was not possible to resolve it. See also <see cref="ResolveMethodDefThrow"/>. If /// <paramref name="method"/> is a <see cref="MethodSpec"/>, then the /// <see cref="MethodSpec.Method"/> property is resolved and returned. /// </summary> /// <param name="method">Method to resolve</param> /// <returns>The <see cref="MethodDef"/> or <c>null</c> if <paramref name="method"/> is /// <c>null</c> or if it wasn't possible to resolve it (the method doesn't exist or its /// assembly couldn't be loaded)</returns> public static MethodDef ResolveMethodDef(this IMethod method) { var md = method as MethodDef; if (md != null) return md; var mr = method as MemberRef; if (mr != null) return mr.ResolveMethod(); var ms = method as MethodSpec; if (ms != null) { md = ms.Method as MethodDef; if (md != null) return md; mr = ms.Method as MemberRef; if (mr != null) return mr.ResolveMethod(); } return null; } /// <summary> /// Resolves an <see cref="IMethod"/> to a <see cref="MethodDef"/> and throws an exception /// if it was not possible to resolve it. See also <see cref="ResolveMethodDef"/>. If /// <paramref name="method"/> is a <see cref="MethodSpec"/>, then the /// <see cref="MethodSpec.Method"/> property is resolved and returned. /// </summary> /// <param name="method">Method to resolve</param> /// <returns>The <see cref="MethodDef"/></returns> public static MethodDef ResolveMethodDefThrow(this IMethod method) { var md = method as MethodDef; if (md != null) return md; var mr = method as MemberRef; if (mr != null) return mr.ResolveMethodThrow(); var ms = method as MethodSpec; if (ms != null) { md = ms.Method as MethodDef; if (md != null) return md; mr = ms.Method as MemberRef; if (mr != null) return mr.ResolveMethodThrow(); } throw new MemberRefResolveException(string.Format("Could not resolve method: {0}", method)); } /// <summary> /// Returns the definition assembly of a <see cref="MemberRef"/> /// </summary> /// <param name="mr">Member reference</param> /// <returns></returns> static internal IAssembly GetDefinitionAssembly(this MemberRef mr) { if (mr == null) return null; var parent = mr.Class; var tdr = parent as ITypeDefOrRef; if (tdr != null) return tdr.DefinitionAssembly; if (parent is ModuleRef) { var mod = mr.Module; return mod == null ? null : mod.Assembly; } var md = parent as MethodDef; if (md != null) { var declType = md.DeclaringType; return declType == null ? null : declType.DefinitionAssembly; } return null; } } /// <summary> /// Implemented by <see cref="MethodDef"/> and <see cref="FileDef"/>, which are the only /// valid managed entry point tokens. /// </summary> public interface IManagedEntryPoint : ICodedToken { } /// <summary> /// Interface to access a module def/ref /// </summary> public interface IModule : IScope, IFullName { } /// <summary> /// Type of scope /// </summary> public enum ScopeType { /// <summary> /// It's an <see cref="dnlib.DotNet.AssemblyRef"/> instance /// </summary> AssemblyRef, /// <summary> /// It's a <see cref="dnlib.DotNet.ModuleRef"/> instance /// </summary> ModuleRef, /// <summary> /// It's a <see cref="dnlib.DotNet.ModuleDef"/> instance /// </summary> ModuleDef, } /// <summary> /// Implemented by modules and assemblies /// </summary> public interface IScope { /// <summary> /// Gets the scope type /// </summary> ScopeType ScopeType { get; } /// <summary> /// Gets the scope name /// </summary> string ScopeName { get; } } /// <summary> /// Interface to get the full name of a type, field, or method /// </summary> public interface IFullName { /// <summary> /// Gets the full name /// </summary> string FullName { get; } /// <summary> /// Simple name of implementer /// </summary> UTF8String Name { get; set; } } /// <summary> /// Implemented by all member refs and types /// </summary> public interface IOwnerModule { /// <summary> /// Gets the owner module /// </summary> ModuleDef Module { get; } } /// <summary> /// Methods to check whether the implementer is a type or a method. /// </summary> public interface IIsTypeOrMethod { /// <summary> /// <c>true</c> if it's a type /// </summary> bool IsType { get; } /// <summary> /// <c>true</c> if it's a method /// </summary> bool IsMethod { get; } } /// <summary> /// Implemented by types, fields, methods, properties, events /// </summary> public interface IMemberRef : ICodedToken, IFullName, IOwnerModule, IIsTypeOrMethod { /// <summary> /// Gets the declaring type /// </summary> ITypeDefOrRef DeclaringType { get; } /// <summary> /// <c>true</c> if it's a <see cref="FieldDef"/> or a <see cref="MemberRef"/> that's /// referencing a field. /// </summary> bool IsField { get; } /// <summary> /// <c>true</c> if it's a <see cref="TypeSpec"/> /// </summary> bool IsTypeSpec { get; } /// <summary> /// <c>true</c> if it's a <see cref="TypeRef"/> /// </summary> bool IsTypeRef { get; } /// <summary> /// <c>true</c> if it's a <see cref="TypeDef"/> /// </summary> bool IsTypeDef { get; } /// <summary> /// <c>true</c> if it's a <see cref="MethodSpec"/> /// </summary> bool IsMethodSpec { get; } /// <summary> /// <c>true</c> if it's a <see cref="MethodDef"/> /// </summary> bool IsMethodDef { get; } /// <summary> /// <c>true</c> if it's a <see cref="MemberRef"/> /// </summary> bool IsMemberRef { get; } /// <summary> /// <c>true</c> if it's a <see cref="FieldDef"/> /// </summary> bool IsFieldDef { get; } /// <summary> /// <c>true</c> if it's a <see cref="PropertyDef"/> /// </summary> bool IsPropertyDef { get; } /// <summary> /// <c>true</c> if it's a <see cref="EventDef"/> /// </summary> bool IsEventDef { get; } /// <summary> /// <c>true</c> if it's a <see cref="GenericParam"/> /// </summary> bool IsGenericParam { get; } } /// <summary> /// All member definitions implement this interface: <see cref="TypeDef"/>, /// <see cref="FieldDef"/>, <see cref="MethodDef"/>, <see cref="EventDef"/>, /// <see cref="PropertyDef"/>, and <see cref="GenericParam"/>. /// </summary> public interface IMemberDef : IDnlibDef, IMemberRef { /// <summary> /// Gets the declaring type /// </summary> new TypeDef DeclaringType { get; } } /// <summary> /// Implemented by the following classes: <see cref="TypeDef"/>, /// <see cref="FieldDef"/>, <see cref="MethodDef"/>, <see cref="EventDef"/>, /// <see cref="PropertyDef"/>, <see cref="GenericParam"/>, <see cref="AssemblyDef"/>, /// and <see cref="ModuleDef"/> /// </summary> public interface IDnlibDef : ICodedToken, IFullName, IHasCustomAttribute { } /// <summary> /// Implemented by types and methods /// </summary> public interface IGenericParameterProvider : ICodedToken, IIsTypeOrMethod { /// <summary> /// Gets the number of generic parameters / arguments /// </summary> int NumberOfGenericParameters { get; } } /// <summary> /// Implemented by fields (<see cref="FieldDef"/> and <see cref="MemberRef"/>) /// </summary> public interface IField : ICodedToken, ITokenOperand, IFullName, IMemberRef { /// <summary> /// Gets/sets the field signature /// </summary> FieldSig FieldSig { get; set; } } /// <summary> /// Implemented by methods (<see cref="MethodDef"/>, <see cref="MemberRef"/> and <see cref="MethodSpec"/>) /// </summary> public interface IMethod : ICodedToken, ITokenOperand, IFullName, IGenericParameterProvider, IMemberRef { /// <summary> /// Method signature /// </summary> MethodSig MethodSig { get; set; } } /// <summary> /// Implemented by tables that can be a token in the <c>ldtoken</c> instruction /// </summary> public interface ITokenOperand : ICodedToken { } /// <summary> /// The table row can be referenced by a coded token /// </summary> public interface ICodedToken : IMDTokenProvider { } /// <summary> /// TypeDefOrRef coded token interface /// </summary> public interface ITypeDefOrRef : ICodedToken, IHasCustomAttribute, IMemberRefParent, IType, ITokenOperand, IMemberRef { /// <summary> /// The coded token tag /// </summary> int TypeDefOrRefTag { get; } } /// <summary> /// HasConstant coded token interface /// </summary> public interface IHasConstant : ICodedToken, IHasCustomAttribute, IFullName { /// <summary> /// The coded token tag /// </summary> int HasConstantTag { get; } /// <summary> /// Gets/sets the constant value /// </summary> Constant Constant { get; set; } } /// <summary> /// HasCustomAttribute coded token interface /// </summary> public interface IHasCustomAttribute : ICodedToken { /// <summary> /// The coded token tag /// </summary> int HasCustomAttributeTag { get; } /// <summary> /// Gets all custom attributes /// </summary> CustomAttributeCollection CustomAttributes { get; } /// <summary> /// <c>true</c> if <see cref="CustomAttributes"/> is not empty /// </summary> bool HasCustomAttributes { get; } } /// <summary> /// HasFieldMarshal coded token interface /// </summary> public interface IHasFieldMarshal : ICodedToken, IHasCustomAttribute, IHasConstant, IFullName { /// <summary> /// The coded token tag /// </summary> int HasFieldMarshalTag { get; } /// <summary> /// Gets/sets the marshal type /// </summary> MarshalType MarshalType { get; set; } /// <summary> /// <c>true</c> if <see cref="MarshalType"/> is not <c>null</c> /// </summary> bool HasMarshalType { get; } } /// <summary> /// HasDeclSecurity coded token interface /// </summary> public interface IHasDeclSecurity : ICodedToken, IHasCustomAttribute, IFullName { /// <summary> /// The coded token tag /// </summary> int HasDeclSecurityTag { get; } /// <summary> /// Gets the permission sets /// </summary> ThreadSafe.IList<DeclSecurity> DeclSecurities { get; } /// <summary> /// <c>true</c> if <see cref="DeclSecurities"/> is not empty /// </summary> bool HasDeclSecurities { get; } } /// <summary> /// MemberRefParent coded token interface /// </summary> public interface IMemberRefParent : ICodedToken, IHasCustomAttribute, IFullName { /// <summary> /// The coded token tag /// </summary> int MemberRefParentTag { get; } } /// <summary> /// HasSemantic coded token interface /// </summary> public interface IHasSemantic : ICodedToken, IHasCustomAttribute, IFullName, IMemberRef { /// <summary> /// The coded token tag /// </summary> int HasSemanticTag { get; } } /// <summary> /// MethodDefOrRef coded token interface /// </summary> public interface IMethodDefOrRef : ICodedToken, IHasCustomAttribute, ICustomAttributeType, IMethod { /// <summary> /// The coded token tag /// </summary> int MethodDefOrRefTag { get; } } /// <summary> /// MemberForwarded coded token interface /// </summary> public interface IMemberForwarded : ICodedToken, IHasCustomAttribute, IFullName, IMemberRef { /// <summary> /// The coded token tag /// </summary> int MemberForwardedTag { get; } /// <summary> /// Gets/sets the impl map /// </summary> ImplMap ImplMap { get; set; } /// <summary> /// <c>true</c> if <see cref="ImplMap"/> is not <c>null</c> /// </summary> bool HasImplMap { get; } } /// <summary> /// Implementation coded token interface /// </summary> public interface IImplementation : ICodedToken, IHasCustomAttribute, IFullName { /// <summary> /// The coded token tag /// </summary> int ImplementationTag { get; } } /// <summary> /// CustomAttributeType coded token interface /// </summary> public interface ICustomAttributeType : ICodedToken, IHasCustomAttribute, IMethod { /// <summary> /// The coded token tag /// </summary> int CustomAttributeTypeTag { get; } } /// <summary> /// ResolutionScope coded token interface /// </summary> public interface IResolutionScope : ICodedToken, IHasCustomAttribute, IFullName { /// <summary> /// The coded token tag /// </summary> int ResolutionScopeTag { get; } } /// <summary> /// TypeOrMethodDef coded token interface /// </summary> public interface ITypeOrMethodDef : ICodedToken, IHasCustomAttribute, IHasDeclSecurity, IMemberRefParent, IFullName, IMemberRef, IGenericParameterProvider { /// <summary> /// The coded token tag /// </summary> int TypeOrMethodDefTag { get; } /// <summary> /// Gets the generic parameters /// </summary> ThreadSafe.IList<GenericParam> GenericParameters { get; } /// <summary> /// <c>true</c> if <see cref="GenericParameters"/> is not empty /// </summary> bool HasGenericParameters { get; } } public static partial class Extensions { /// <summary> /// Converts a <see cref="TypeSig"/> to a <see cref="ITypeDefOrRef"/> /// </summary> /// <param name="sig">The sig</param> public static ITypeDefOrRef ToTypeDefOrRef(this TypeSig sig) { if (sig == null) return null; var tdrSig = sig as TypeDefOrRefSig; if (tdrSig != null) return tdrSig.TypeDefOrRef; var module = sig.Module; if (module == null) return new TypeSpecUser(sig); return module.UpdateRowId(new TypeSpecUser(sig)); } /// <summary> /// Returns <c>true</c> if it's an integer or a floating point type /// </summary> /// <param name="tdr">Type</param> /// <returns></returns> internal static bool IsPrimitive(this IType tdr) { if (tdr == null) return false; if (!tdr.DefinitionAssembly.IsCorLib()) return false; switch (tdr.FullName) { case "System.Boolean": case "System.Char": case "System.SByte": case "System.Byte": case "System.Int16": case "System.UInt16": case "System.Int32": case "System.UInt32": case "System.Int64": case "System.UInt64": case "System.Single": case "System.Double": case "System.IntPtr": case "System.UIntPtr": return true; default: return false; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gccv = Google.Cloud.Channel.V1; using sys = System; namespace Google.Cloud.Channel.V1 { /// <summary>Resource name for the <c>ChannelPartnerLink</c> resource.</summary> public sealed partial class ChannelPartnerLinkName : gax::IResourceName, sys::IEquatable<ChannelPartnerLinkName> { /// <summary>The possible contents of <see cref="ChannelPartnerLinkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c>. /// </summary> AccountChannelPartnerLink = 1, } private static gax::PathTemplate s_accountChannelPartnerLink = new gax::PathTemplate("accounts/{account}/channelPartnerLinks/{channel_partner_link}"); /// <summary>Creates a <see cref="ChannelPartnerLinkName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ChannelPartnerLinkName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ChannelPartnerLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ChannelPartnerLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ChannelPartnerLinkName"/> with the pattern /// <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c>. /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelPartnerLinkId"> /// The <c>ChannelPartnerLink</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns>A new instance of <see cref="ChannelPartnerLinkName"/> constructed from the provided ids.</returns> public static ChannelPartnerLinkName FromAccountChannelPartnerLink(string accountId, string channelPartnerLinkId) => new ChannelPartnerLinkName(ResourceNameType.AccountChannelPartnerLink, accountId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), channelPartnerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(channelPartnerLinkId, nameof(channelPartnerLinkId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ChannelPartnerLinkName"/> with pattern /// <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c>. /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelPartnerLinkId"> /// The <c>ChannelPartnerLink</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ChannelPartnerLinkName"/> with pattern /// <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c>. /// </returns> public static string Format(string accountId, string channelPartnerLinkId) => FormatAccountChannelPartnerLink(accountId, channelPartnerLinkId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ChannelPartnerLinkName"/> with pattern /// <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c>. /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelPartnerLinkId"> /// The <c>ChannelPartnerLink</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ChannelPartnerLinkName"/> with pattern /// <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c>. /// </returns> public static string FormatAccountChannelPartnerLink(string accountId, string channelPartnerLinkId) => s_accountChannelPartnerLink.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), gax::GaxPreconditions.CheckNotNullOrEmpty(channelPartnerLinkId, nameof(channelPartnerLinkId))); /// <summary> /// Parses the given resource name string into a new <see cref="ChannelPartnerLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c></description> /// </item> /// </list> /// </remarks> /// <param name="channelPartnerLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ChannelPartnerLinkName"/> if successful.</returns> public static ChannelPartnerLinkName Parse(string channelPartnerLinkName) => Parse(channelPartnerLinkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ChannelPartnerLinkName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="channelPartnerLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ChannelPartnerLinkName"/> if successful.</returns> public static ChannelPartnerLinkName Parse(string channelPartnerLinkName, bool allowUnparsed) => TryParse(channelPartnerLinkName, allowUnparsed, out ChannelPartnerLinkName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ChannelPartnerLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c></description> /// </item> /// </list> /// </remarks> /// <param name="channelPartnerLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ChannelPartnerLinkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string channelPartnerLinkName, out ChannelPartnerLinkName result) => TryParse(channelPartnerLinkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ChannelPartnerLinkName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="channelPartnerLinkName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ChannelPartnerLinkName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string channelPartnerLinkName, bool allowUnparsed, out ChannelPartnerLinkName result) { gax::GaxPreconditions.CheckNotNull(channelPartnerLinkName, nameof(channelPartnerLinkName)); gax::TemplatedResourceName resourceName; if (s_accountChannelPartnerLink.TryParseName(channelPartnerLinkName, out resourceName)) { result = FromAccountChannelPartnerLink(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(channelPartnerLinkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ChannelPartnerLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string accountId = null, string channelPartnerLinkId = null) { Type = type; UnparsedResource = unparsedResourceName; AccountId = accountId; ChannelPartnerLinkId = channelPartnerLinkId; } /// <summary> /// Constructs a new instance of a <see cref="ChannelPartnerLinkName"/> class from the component parts of /// pattern <c>accounts/{account}/channelPartnerLinks/{channel_partner_link}</c> /// </summary> /// <param name="accountId">The <c>Account</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="channelPartnerLinkId"> /// The <c>ChannelPartnerLink</c> ID. Must not be <c>null</c> or empty. /// </param> public ChannelPartnerLinkName(string accountId, string channelPartnerLinkId) : this(ResourceNameType.AccountChannelPartnerLink, accountId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountId, nameof(accountId)), channelPartnerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(channelPartnerLinkId, nameof(channelPartnerLinkId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Account</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AccountId { get; } /// <summary> /// The <c>ChannelPartnerLink</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string ChannelPartnerLinkId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.AccountChannelPartnerLink: return s_accountChannelPartnerLink.Expand(AccountId, ChannelPartnerLinkId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ChannelPartnerLinkName); /// <inheritdoc/> public bool Equals(ChannelPartnerLinkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ChannelPartnerLinkName a, ChannelPartnerLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ChannelPartnerLinkName a, ChannelPartnerLinkName b) => !(a == b); } public partial class ChannelPartnerLink { /// <summary> /// <see cref="gccv::ChannelPartnerLinkName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gccv::ChannelPartnerLinkName ChannelPartnerLinkName { get => string.IsNullOrEmpty(Name) ? null : gccv::ChannelPartnerLinkName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Drawing; using System.Drawing.Imaging; namespace Hydra.Framework.ImageProcessing.Analysis.Filters { // //********************************************************************** /// <summary> /// Canny edge detector /// </summary> //********************************************************************** // public class CannyEdgeDetector : IFilter { #region Private Constants // //********************************************************************** /// <summary> /// Default Low Threshold /// </summary> //********************************************************************** // private const byte LowThreshold_sc = 20; // //********************************************************************** /// <summary> /// Default High Threshold /// </summary> //********************************************************************** // private const byte HighThreshold_sc = 100; #endregion #region Private Member Variables // //********************************************************************** /// <summary> /// GrayScale Filter /// </summary> //********************************************************************** // private IFilter grayscaleFilter_m = new GrayscaleBT709(); // //********************************************************************** /// <summary> /// Gaussian Filter /// </summary> //********************************************************************** // private GaussianBlur gaussianFilter_m = new GaussianBlur(); // //********************************************************************** /// <summary> /// Lowest Threshold /// </summary> //********************************************************************** // private byte lowThreshold_m = LowThreshold_sc; // //********************************************************************** /// <summary> /// Highest Threshold /// </summary> //********************************************************************** // private byte highThreshold_m = HighThreshold_sc; // //********************************************************************** /// <summary> /// Sobel Kernels (X) /// </summary> //********************************************************************** // private static int[,] xKernel_m = new int[,] { {-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1} }; // //********************************************************************** /// <summary> /// Sobel Kernels (Y) /// </summary> //********************************************************************** // private static int[,] yKernel_m = new int[,] { { 1, 2, 1}, { 0, 0, 0}, {-1, -2, -1} }; #endregion #region Constructors // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:CannyEdgeDetector"/> class. /// </summary> //********************************************************************** // public CannyEdgeDetector() { } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:CannyEdgeDetector"/> class. /// </summary> /// <param name="lowThreshold">The low threshold.</param> /// <param name="highThreshold">The high threshold.</param> //********************************************************************** // public CannyEdgeDetector(byte lowThreshold, byte highThreshold) { this.lowThreshold_m = lowThreshold; this.highThreshold_m = highThreshold; } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:CannyEdgeDetector"/> class. /// </summary> /// <param name="lowThreshold">The low threshold.</param> /// <param name="highThreshold">The high threshold.</param> /// <param name="sigma">The sigma.</param> //********************************************************************** // public CannyEdgeDetector(byte lowThreshold, byte highThreshold, double sigma) { this.lowThreshold_m = lowThreshold; this.highThreshold_m = highThreshold; gaussianFilter_m.Sigma = sigma; } #endregion #region Properties // //********************************************************************** /// <summary> /// Gets or sets the low threshold property. /// </summary> /// <value>The low threshold.</value> //********************************************************************** // public byte LowThreshold { get { return lowThreshold_m; } set { lowThreshold_m = value; } } // //********************************************************************** /// <summary> /// Gets or sets the high threshold property. /// </summary> /// <value>The high threshold.</value> //********************************************************************** // public byte HighThreshold { get { return highThreshold_m; } set { highThreshold_m = value; } } // //********************************************************************** /// <summary> /// Gets or sets the Gaussian sigma property (sigma value for Gaussian blurring) /// </summary> /// <value>The gaussian sigma.</value> //********************************************************************** // public double GaussianSigma { get { return gaussianFilter_m.Sigma; } set { gaussianFilter_m.Sigma = value; } } // //********************************************************************** /// <summary> /// Gets or sets the size of the Gaussian size property (size value for Gaussian blurring). /// </summary> /// <value>The size of the gaussian.</value> //********************************************************************** // public int GaussianSize { get { return gaussianFilter_m.Size; } set { gaussianFilter_m.Size = value; } } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Apply filter /// </summary> /// <param name="srcImg">The SRC img.</param> /// <returns></returns> //********************************************************************** // public Bitmap Apply(Bitmap srcImg) { // // Step 1 - grayscale initial image // Bitmap grayImage = (srcImg.PixelFormat == PixelFormat.Format8bppIndexed) ? srcImg : grayscaleFilter_m.Apply(srcImg); // // Step 2 - blur image // Bitmap blurredImage = gaussianFilter_m.Apply(grayImage); // // get source image size // int width = srcImg.Width; int height = srcImg.Height; // // lock source bitmap data // BitmapData srcData = blurredImage.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); // // create new image // Bitmap dstImg = Hydra.Framework.ImageProcessing.Analysis.Image.CreateGrayscaleImage(width, height); // // lock destination bitmap data // BitmapData dstData = dstImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); int stride = srcData.Stride; int offset = stride - width; int widthM1 = width - 1; int heightM1 = height - 1; int i, j, ir; double v, gx, gy; double orientation, toPI = 180.0 / System.Math.PI; byte leftPixel = 0, rightPixel = 0; // // orientation array // byte[] orients = new byte[width * height]; // // do the job (Warning Unsafe Code) // unsafe { byte * src = (byte *) srcData.Scan0.ToPointer() + stride; byte * dst = (byte *) dstData.Scan0.ToPointer() + stride; int p = width; // // Step 3 - calculate magnitude and edge orientation // // for each line for (int y = 1; y < heightM1; y ++) { src++; dst++; p++; // // for each pixel // for (int x = 1; x < widthM1; x ++, src ++, dst ++, p ++) { gx = gy = 0; // // for each kernel row // for (i = 0; i < 3; i++) { ir = i - 1; // // for each kernel column // for (j = 0; j < 3; j++) { // // source value // v = src[ir * stride + j - 1]; gx += v * xKernel_m[i, j]; gy += v * yKernel_m[i, j]; } } // // get gradient value // *dst = (byte) Math.Min(Math.Abs(gx) + Math.Abs(gy), 255); // // --- get orientation // can not divide by zero // if (gx == 0) { orientation = (gy == 0) ? 0 : 90; } else { double div = gy / gx; // // handle angles of the 2nd and 4th quads // if (div < 0) { orientation = 180 - System.Math.Atan(- div) * toPI; } // // handle angles of the 1st and 3rd quads // else { orientation = System.Math.Atan(div) * toPI; } // // get closest angle from 0, 45, 90, 135 set // if (orientation < 22.5) orientation = 0; else if (orientation < 67.5) orientation = 45; else if (orientation < 112.5) orientation = 90; else if (orientation < 157.5) orientation = 135; else orientation = 0; } // // save orientation // orients[p] = (byte) orientation; } src += (offset + 1); dst += (offset + 1); p++; } // // Step 4 - suppres non maximums // dst = (byte *) dstData.Scan0.ToPointer() + stride; p = width; // // for each line // for (int y = 1; y < heightM1; y ++) { dst++; p++; // // for each pixel // for (int x = 1; x < widthM1; x ++, dst ++, p ++) { // // get two adjacent pixels // switch (orients[p]) { case 0: leftPixel = dst[-1]; rightPixel = dst[1]; break; case 45: leftPixel = dst[width - 1]; rightPixel = dst[-width + 1]; break; case 90: leftPixel = dst[width]; rightPixel = dst[-width]; break; case 135: leftPixel = dst[width + 1]; rightPixel = dst[-width - 1]; break; } // // compare current pixels value with adjacent pixels // if ((*dst < leftPixel) || (*dst < rightPixel)) { *dst = 0; } } dst += (offset + 1); p++; } // // Step 5 - hysteresis // dst = (byte *) dstData.Scan0.ToPointer() + stride; p = width; // // for each line // for (int y = 1; y < heightM1; y ++) { dst++; p++; // // for each pixel // for (int x = 1; x < widthM1; x ++, dst ++, p ++) { if (*dst < highThreshold_m) { if (*dst < lowThreshold_m) { // // non edge // *dst = 0; } else { // // check 8 neighboring pixels // if ((dst[-1] < highThreshold_m) && (dst[1] < highThreshold_m) && (dst[-width] < highThreshold_m) && (dst[width] < highThreshold_m) && (dst[-width] < highThreshold_m) && (dst[-width] < highThreshold_m) && (dst[-width] < highThreshold_m) && (dst[-width] < highThreshold_m)) { *dst = 0; } } } } dst += (offset + 1); p++; } } // // unlock images // dstImg.UnlockBits(dstData); blurredImage.UnlockBits(srcData); // // release temporary objects // blurredImage.Dispose(); if (grayImage != srcImg) grayImage.Dispose(); return dstImg; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; using System.Threading.Tasks; using Proto.Remote.Tests.Messages; namespace Proto.Remote.Tests { [Collection("RemoteTests"), Trait("Category", "Remote")] public class RemoteTests { private readonly RemoteManager _remoteManager; public RemoteTests(RemoteManager remoteManager) { _remoteManager = remoteManager; } [Fact, DisplayTestMethodName] public void CanSerializeAndDeserializeJsonPID() { var typeName = "actor.PID"; var json = new JsonMessage(typeName, "{ \"Address\":\"123\", \"Id\":\"456\"}"); var bytes = Serialization.Serialize(json, 1); var deserialized = Serialization.Deserialize(typeName, bytes, 1) as PID; Assert.Equal("123", deserialized.Address); Assert.Equal("456", deserialized.Id); } [Fact, DisplayTestMethodName] public void CanSerializeAndDeserializeJson() { var typeName = "remote_test_messages.Ping"; var json = new JsonMessage(typeName, "{ \"message\":\"Hello\"}"); var bytes = Serialization.Serialize(json, 1); var deserialized = Serialization.Deserialize(typeName, bytes, 1) as Ping; Assert.Equal("Hello",deserialized.Message); } [Fact, DisplayTestMethodName] public async void CanSendJsonAndReceiveToExistingRemote() { var remoteActor = new PID(_remoteManager.DefaultNode.Address, "EchoActorInstance"); var ct = new CancellationTokenSource(3000); var tcs = new TaskCompletionSource<bool>(); ct.Token.Register(() => { tcs.TrySetCanceled(); }); var localActor = Actor.Spawn(Actor.FromFunc(ctx => { if (ctx.Message is Pong) { tcs.SetResult(true); ctx.Self.Stop(); } return Actor.Done; })); var json = new JsonMessage("remote_test_messages.Ping", "{ \"message\":\"Hello\"}"); var envelope = new Proto.MessageEnvelope(json, localActor, MessageHeader.EmptyHeader); Remote.SendMessage(remoteActor, envelope, 1); await tcs.Task; } [Fact, DisplayTestMethodName] public async void CanSendAndReceiveToExistingRemote() { var remoteActor = new PID(_remoteManager.DefaultNode.Address, "EchoActorInstance"); var pong = await remoteActor.RequestAsync<Pong>(new Ping { Message = "Hello" }, TimeSpan.FromMilliseconds(5000)); Assert.Equal($"{_remoteManager.DefaultNode.Address} Hello", pong.Message); } [Fact, DisplayTestMethodName] public async void WhenRemoteActorNotFound_RequestAsyncTimesout() { var unknownRemoteActor = new PID(_remoteManager.DefaultNode.Address, "doesn't exist"); await Assert.ThrowsAsync<TimeoutException>(async () => { await unknownRemoteActor.RequestAsync<Pong>(new Ping { Message = "Hello" }, TimeSpan.FromMilliseconds(2000)); }); } [Fact, DisplayTestMethodName] public async void CanSpawnRemoteActor() { var remoteActorName = Guid.NewGuid().ToString(); var remoteActor = await Remote.SpawnNamedAsync(_remoteManager.DefaultNode.Address, remoteActorName, "EchoActor", TimeSpan.FromSeconds(5)); var pong = await remoteActor.RequestAsync<Pong>(new Ping{Message="Hello"}, TimeSpan.FromMilliseconds(5000)); Assert.Equal($"{_remoteManager.DefaultNode.Address} Hello", pong.Message); } [Fact, DisplayTestMethodName] public async void CanWatchRemoteActor() { var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor = await SpawnLocalActorAndWatch(remoteActor); remoteActor.Stop(); Assert.True(await PollUntilTrue(() => localActor.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); } [Fact, DisplayTestMethodName] public async void CanWatchMultipleRemoteActors() { var remoteActor1 = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var remoteActor2 = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor = await SpawnLocalActorAndWatch(remoteActor1, remoteActor2); remoteActor1.Stop(); remoteActor2.Stop(); Assert.True(await PollUntilTrue(() => localActor.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor1.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); Assert.True(await PollUntilTrue(() => localActor.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor2.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); } [Fact, DisplayTestMethodName] public async void MultipleLocalActorsCanWatchRemoteActor() { var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor1 = await SpawnLocalActorAndWatch(remoteActor); var localActor2 = await SpawnLocalActorAndWatch(remoteActor); remoteActor.Stop(); Assert.True(await PollUntilTrue(() => localActor1.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); Assert.True(await PollUntilTrue(() => localActor2.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); } [Fact, DisplayTestMethodName] public async void CanUnwatchRemoteActor() { var remoteActor = await SpawnRemoteActor(_remoteManager.DefaultNode.Address); var localActor1 = await SpawnLocalActorAndWatch(remoteActor); var localActor2 = await SpawnLocalActorAndWatch(remoteActor); localActor2.Tell(new Unwatch(remoteActor)); await Task.Delay(TimeSpan.FromSeconds(3)); // wait for unwatch to propagate... remoteActor.Stop(); // localActor1 is still watching so should get notified Assert.True(await PollUntilTrue(() => localActor1.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); // localActor2 is NOT watching so should not get notified Assert.False(await localActor2.RequestAsync<bool>(new TerminatedMessageReceived(_remoteManager.DefaultNode.Address, remoteActor.Id), TimeSpan.FromSeconds(5)), "Unwatch did not succeed."); } [Fact, DisplayTestMethodName] public async void WhenRemoteTerminated_LocalWatcherReceivesNotification() { var (address, process) = _remoteManager.ProvisionNode("127.0.0.1", 12002); var remoteActor = await SpawnRemoteActor(address); var localActor = await SpawnLocalActorAndWatch(remoteActor); Console.WriteLine($"Killing remote process {address}!"); process.Kill(); Assert.True(await PollUntilTrue(() => localActor.RequestAsync<bool>(new TerminatedMessageReceived(address, remoteActor.Id), TimeSpan.FromSeconds(5))), "Watching actor did not receive Termination message"); Assert.Equal(1, await localActor.RequestAsync<int>(new GetTerminatedMessagesCount(), TimeSpan.FromSeconds(5))); } private static async Task<PID> SpawnRemoteActor(string address) { var remoteActorName = Guid.NewGuid().ToString(); return await Remote.SpawnNamedAsync(address, remoteActorName, "EchoActor", TimeSpan.FromSeconds(5)); } private async Task<PID> SpawnLocalActorAndWatch(params PID[] remoteActors) { var props = Actor.FromProducer(() => new LocalActor(remoteActors)); var actor = Actor.Spawn(props); // The local actor watches the remote one - we wait here for the RemoteWatch // message to propagate to the remote actor Console.WriteLine("Waiting for RemoteWatch to propagate..."); await Task.Delay(2000); return actor; } private Task<bool> PollUntilTrue(Func<Task<bool>> predicate) { return PollUntilTrue(predicate, 10, TimeSpan.FromMilliseconds(500)); } private async Task<bool> PollUntilTrue(Func<Task<bool>> predicate, int attempts, TimeSpan interval) { var attempt = 1; while (attempt <= attempts) { Console.WriteLine($"Attempting assertion (attempt {attempt} of {attempts})"); if (await predicate()) { Console.WriteLine($"Passed!"); return true; } attempt++; await Task.Delay(interval); } return false; } } public class TerminatedMessageReceived { public TerminatedMessageReceived(string address, string actorId) { Address = address; ActorId = actorId; } public string Address { get; } public string ActorId { get; } } public class GetTerminatedMessagesCount { } public class LocalActor : IActor { private readonly List<PID> _remoteActors = new List<PID>(); private readonly List<Terminated> _terminatedMessages = new List<Terminated>(); public LocalActor(params PID[] remoteActors) { _remoteActors.AddRange(remoteActors); } public Task ReceiveAsync(IContext context) { switch (context.Message) { case Started _: HandleStarted(context); break; case Unwatch msg: HandleUnwatch(context, msg); break; case TerminatedMessageReceived msg: HandleTerminatedMessageReceived(context, msg); break; case GetTerminatedMessagesCount _: HandleCountOfMessagesReceived(context); break; case Terminated msg: HandleTerminated(msg); break; } return Actor.Done; } private void HandleCountOfMessagesReceived(IContext context) { context.Sender.Tell(_terminatedMessages.Count); } private void HandleTerminatedMessageReceived(IContext context, TerminatedMessageReceived msg) { var messageReceived = _terminatedMessages.Any(tm => tm.Who.Address == msg.Address && tm.Who.Id == msg.ActorId); context.Sender.Tell(messageReceived); } private void HandleTerminated(Terminated msg) { Console.WriteLine($"Received Terminated message for {msg.Who.Address}: {msg.Who.Id}. Address terminated? {msg.AddressTerminated}"); _terminatedMessages.Add(msg); } private void HandleUnwatch(IContext context, Unwatch msg) { var remoteActor =_remoteActors.Single(ra => ra.Id == msg.Watcher.Id && ra.Address == msg.Watcher.Address); context.Unwatch(remoteActor); } private void HandleStarted(IContext context) { foreach (var remoteActor in _remoteActors) { context.Watch(remoteActor); } } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnityEngine.UI.Windows.Modules.ImageEffects { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] public class PostEffectsBase : MonoBehaviour { protected bool supportHDRTextures = true; protected bool supportDX11 = false; protected bool isSupported = true; private List<Material> createdMaterials = new List<Material>(); protected Material CheckShaderAndCreateMaterial(Shader s, Material m2Create) { if (!s) { Debug.Log("Missing shader in " + ToString()); enabled = false; return null; } if (s.isSupported && m2Create && m2Create.shader == s) return m2Create; if (!s.isSupported) { NotSupported(); Debug.Log("The shader " + s.ToString() + " on effect " + ToString() + " is not supported on this platform!"); return null; } m2Create = new Material(s); createdMaterials.Add(m2Create); m2Create.hideFlags = HideFlags.DontSave; return m2Create; } protected Material CreateMaterial(Shader s, Material m2Create) { if (!s) { Debug.Log("Missing shader in " + ToString()); return null; } if (m2Create && (m2Create.shader == s) && (s.isSupported)) return m2Create; if (!s.isSupported) { return null; } m2Create = new Material(s); createdMaterials.Add(m2Create); m2Create.hideFlags = HideFlags.DontSave; return m2Create; } void OnEnable() { isSupported = true; } void OnDestroy() { RemoveCreatedMaterials(); } private void RemoveCreatedMaterials() { while (createdMaterials.Count > 0) { Material mat = createdMaterials[0]; createdMaterials.RemoveAt(0); #if UNITY_EDITOR DestroyImmediate(mat); #else Destroy(mat); #endif } } protected bool CheckSupport() { return CheckSupport(false); } public virtual bool CheckResources() { Debug.LogWarning("CheckResources () for " + ToString() + " should be overwritten."); return isSupported; } protected void Start() { CheckResources(); } protected bool CheckSupport(bool needDepth) { isSupported = true; supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; if (!SystemInfo.supportsImageEffects) { NotSupported(); return false; } if (needDepth && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth)) { NotSupported(); return false; } if (needDepth) GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; return true; } protected bool CheckSupport(bool needDepth, bool needHdr) { if (!CheckSupport(needDepth)) return false; if (needHdr && !supportHDRTextures) { NotSupported(); return false; } return true; } public bool Dx11Support() { return supportDX11; } protected void ReportAutoDisable() { Debug.LogWarning("The image effect " + ToString() + " has been disabled as it's not supported on the current platform."); } // deprecated but needed for old effects to survive upgrading bool CheckShader(Shader s) { Debug.Log("The shader " + s.ToString() + " on effect " + ToString() + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package."); if (!s.isSupported) { NotSupported(); return false; } else { return false; } } protected void NotSupported() { enabled = false; isSupported = false; return; } protected void DrawBorder(RenderTexture dest, Material material) { float x1; float x2; float y1; float y2; RenderTexture.active = dest; bool invertY = true; // source.texelSize.y < 0.0ff; // Set up the simple Matrix GL.PushMatrix(); GL.LoadOrtho(); for (int i = 0; i < material.passCount; i++) { material.SetPass(i); float y1_; float y2_; if (invertY) { y1_ = 1.0f; y2_ = 0.0f; } else { y1_ = 0.0f; y2_ = 1.0f; } // left x1 = 0.0f; x2 = 0.0f + 1.0f / (dest.width * 1.0f); y1 = 0.0f; y2 = 1.0f; GL.Begin(GL.QUADS); GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // right x1 = 1.0f - 1.0f / (dest.width * 1.0f); x2 = 1.0f; y1 = 0.0f; y2 = 1.0f; GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // top x1 = 0.0f; x2 = 1.0f; y1 = 0.0f; y2 = 0.0f + 1.0f / (dest.height * 1.0f); GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); // bottom x1 = 0.0f; x2 = 1.0f; y1 = 1.0f - 1.0f / (dest.height * 1.0f); y2 = 1.0f; GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); GL.End(); } GL.PopMatrix(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.WebSites { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for DomainsOperations. /// </summary> public static partial class DomainsOperationsExtensions { /// <summary> /// Checks if a domain is available for registration /// </summary> /// Checks if a domain is available for registration /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='identifier'> /// Name of the domain /// </param> public static DomainAvailablilityCheckResult CheckAvailability(this IDomainsOperations operations, NameIdentifier identifier) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).CheckAvailabilityAsync(identifier), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks if a domain is available for registration /// </summary> /// Checks if a domain is available for registration /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='identifier'> /// Name of the domain /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DomainAvailablilityCheckResult> CheckAvailabilityAsync(this IDomainsOperations operations, NameIdentifier identifier, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckAvailabilityWithHttpMessagesAsync(identifier, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all domains in a subscription /// </summary> /// Lists all domains in a subscription /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Domain> List(this IDomainsOperations operations) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ListAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all domains in a subscription /// </summary> /// Lists all domains in a subscription /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Domain>> ListAsync(this IDomainsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Generates a single sign on request for domain management portal /// </summary> /// Generates a single sign on request for domain management portal /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DomainControlCenterSsoRequest GetControlCenterSsoRequest(this IDomainsOperations operations) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).GetControlCenterSsoRequestAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Generates a single sign on request for domain management portal /// </summary> /// Generates a single sign on request for domain management portal /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DomainControlCenterSsoRequest> GetControlCenterSsoRequestAsync(this IDomainsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetControlCenterSsoRequestWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists domain recommendations based on keywords /// </summary> /// Lists domain recommendations based on keywords /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Domain recommendation search parameters /// </param> public static IPage<NameIdentifier> ListRecommendations(this IDomainsOperations operations, DomainRecommendationSearchParameters parameters) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ListRecommendationsAsync(parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists domain recommendations based on keywords /// </summary> /// Lists domain recommendations based on keywords /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Domain recommendation search parameters /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NameIdentifier>> ListRecommendationsAsync(this IDomainsOperations operations, DomainRecommendationSearchParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRecommendationsWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Validates domain registration information /// </summary> /// Validates domain registration information /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='domainRegistrationInput'> /// Domain registration information /// </param> public static object ValidatePurchaseInformation(this IDomainsOperations operations, DomainRegistrationInput domainRegistrationInput) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ValidatePurchaseInformationAsync(domainRegistrationInput), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Validates domain registration information /// </summary> /// Validates domain registration information /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='domainRegistrationInput'> /// Domain registration information /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> ValidatePurchaseInformationAsync(this IDomainsOperations operations, DomainRegistrationInput domainRegistrationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ValidatePurchaseInformationWithHttpMessagesAsync(domainRegistrationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists domains under a resource group /// </summary> /// Lists domains under a resource group /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> public static IPage<Domain> ListByResourceGroup(this IDomainsOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists domains under a resource group /// </summary> /// Lists domains under a resource group /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Domain>> ListByResourceGroupAsync(this IDomainsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets details of a domain /// </summary> /// Gets details of a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> public static Domain Get(this IDomainsOperations operations, string resourceGroupName, string domainName) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).GetAsync(resourceGroupName, domainName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets details of a domain /// </summary> /// Gets details of a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Domain> GetAsync(this IDomainsOperations operations, string resourceGroupName, string domainName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, domainName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a domain /// </summary> /// Creates a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// &amp;gt;Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='domain'> /// Domain registration information /// </param> public static Domain CreateOrUpdate(this IDomainsOperations operations, string resourceGroupName, string domainName, Domain domain) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).CreateOrUpdateAsync(resourceGroupName, domainName, domain), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a domain /// </summary> /// Creates a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// &amp;gt;Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='domain'> /// Domain registration information /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Domain> CreateOrUpdateAsync(this IDomainsOperations operations, string resourceGroupName, string domainName, Domain domain, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, domainName, domain, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a domain /// </summary> /// Creates a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// &amp;gt;Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='domain'> /// Domain registration information /// </param> public static Domain BeginCreateOrUpdate(this IDomainsOperations operations, string resourceGroupName, string domainName, Domain domain) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, domainName, domain), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a domain /// </summary> /// Creates a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// &amp;gt;Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='domain'> /// Domain registration information /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Domain> BeginCreateOrUpdateAsync(this IDomainsOperations operations, string resourceGroupName, string domainName, Domain domain, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, domainName, domain, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a domain /// </summary> /// Deletes a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='forceHardDeleteDomain'> /// If true then the domain will be deleted immediately instead of after 24 /// hours /// </param> public static object Delete(this IDomainsOperations operations, string resourceGroupName, string domainName, bool? forceHardDeleteDomain = default(bool?)) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).DeleteAsync(resourceGroupName, domainName, forceHardDeleteDomain), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a domain /// </summary> /// Deletes a domain /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='forceHardDeleteDomain'> /// If true then the domain will be deleted immediately instead of after 24 /// hours /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> DeleteAsync(this IDomainsOperations operations, string resourceGroupName, string domainName, bool? forceHardDeleteDomain = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, domainName, forceHardDeleteDomain, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Retrieves the latest status of a domain purchase operation /// </summary> /// Retrieves the latest status of a domain purchase operation /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='operationId'> /// Domain purchase operation Id /// </param> public static Domain GetOperation(this IDomainsOperations operations, string resourceGroupName, string domainName, string operationId) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).GetOperationAsync(resourceGroupName, domainName, operationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieves the latest status of a domain purchase operation /// </summary> /// Retrieves the latest status of a domain purchase operation /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the resource group /// </param> /// <param name='domainName'> /// Name of the domain /// </param> /// <param name='operationId'> /// Domain purchase operation Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Domain> GetOperationAsync(this IDomainsOperations operations, string resourceGroupName, string domainName, string operationId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetOperationWithHttpMessagesAsync(resourceGroupName, domainName, operationId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all domains in a subscription /// </summary> /// Lists all domains in a subscription /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Domain> ListNext(this IDomainsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists all domains in a subscription /// </summary> /// Lists all domains in a subscription /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Domain>> ListNextAsync(this IDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists domain recommendations based on keywords /// </summary> /// Lists domain recommendations based on keywords /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NameIdentifier> ListRecommendationsNext(this IDomainsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ListRecommendationsNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists domain recommendations based on keywords /// </summary> /// Lists domain recommendations based on keywords /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NameIdentifier>> ListRecommendationsNextAsync(this IDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRecommendationsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists domains under a resource group /// </summary> /// Lists domains under a resource group /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Domain> ListByResourceGroupNext(this IDomainsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IDomainsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Lists domains under a resource group /// </summary> /// Lists domains under a resource group /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Domain>> ListByResourceGroupNextAsync(this IDomainsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data.Services.Client; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.Versioning; using System.Windows; using NuGet.Resources; namespace NuGet { public class DataServicePackageRepository : PackageRepositoryBase, IHttpClientEvents, IServiceBasedRepository, ICloneableRepository, ICultureAwareRepository, IOperationAwareRepository, IPackageLookup, ILatestPackageLookup, IWeakEventListener { private const string FindPackagesByIdSvcMethod = "FindPackagesById"; private const string PackageServiceEntitySetName = "Packages"; private const string SearchSvcMethod = "Search"; private const string GetUpdatesSvcMethod = "GetUpdates"; private IDataServiceContext _context; private readonly IHttpClient _httpClient; private readonly PackageDownloader _packageDownloader; private CultureInfo _culture; private Tuple<string, string, string> _currentOperation; private event EventHandler<WebRequestEventArgs> _sendingRequest; public DataServicePackageRepository(Uri serviceRoot) : this(new HttpClient(serviceRoot)) { } public DataServicePackageRepository(IHttpClient client) : this(client, new PackageDownloader()) { } public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader) { if (client == null) { throw new ArgumentNullException("client"); } if (packageDownloader == null) { throw new ArgumentNullException("packageDownloader"); } _httpClient = client; _httpClient.AcceptCompression = true; _packageDownloader = packageDownloader; if (EnvironmentUtility.RunningFromCommandLine || EnvironmentUtility.IsMonoRuntime) { _packageDownloader.SendingRequest += OnPackageDownloaderSendingRequest; } else { // weak event pattern SendingRequestEventManager.AddListener(_packageDownloader, this); } } private void OnPackageDownloaderSendingRequest(object sender, WebRequestEventArgs e) { if (_currentOperation != null) { string operation = _currentOperation.Item1; string mainPackageId = _currentOperation.Item2; string mainPackageVersion = _currentOperation.Item3; if (!String.IsNullOrEmpty(mainPackageId) && !String.IsNullOrEmpty(_packageDownloader.CurrentDownloadPackageId)) { if (!mainPackageId.Equals(_packageDownloader.CurrentDownloadPackageId, StringComparison.OrdinalIgnoreCase)) { operation = operation + "-Dependency"; } } e.Request.Headers[RepositoryOperationNames.OperationHeaderName] = operation; if (!operation.Equals(_currentOperation.Item1, StringComparison.OrdinalIgnoreCase)) { e.Request.Headers[RepositoryOperationNames.DependentPackageHeaderName] = mainPackageId; if (!String.IsNullOrEmpty(mainPackageVersion)) { e.Request.Headers[RepositoryOperationNames.DependentPackageVersionHeaderName] = mainPackageVersion; } } RaiseSendingRequest(e); } } // Just forward calls to the package downloader public event EventHandler<ProgressEventArgs> ProgressAvailable { add { _packageDownloader.ProgressAvailable += value; } remove { _packageDownloader.ProgressAvailable -= value; } } public event EventHandler<WebRequestEventArgs> SendingRequest { add { _packageDownloader.SendingRequest += value; _httpClient.SendingRequest += value; _sendingRequest += value; } remove { _packageDownloader.SendingRequest -= value; _httpClient.SendingRequest -= value; _sendingRequest -= value; } } public CultureInfo Culture { get { if (_culture == null) { // TODO: Technically, if this is a remote server, we have to return the culture of the server // instead of invariant culture. However, there is no trivial way to retrieve the server's culture, // So temporarily use Invariant culture here. _culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture; } return _culture; } } // Do NOT delete this property. It is used by the functional test. public PackageDownloader PackageDownloader { get { return _packageDownloader; } } public override string Source { get { return _httpClient.Uri.OriginalString; } } public override bool SupportsPrereleasePackages { get { return Context.SupportsProperty("IsAbsoluteLatestVersion"); } } // Don't initialize the Context at the constructor time so that // we don't make a web request if we are not going to actually use it // since getting the Uri property of the RedirectedHttpClient will // trigger that functionality. internal IDataServiceContext Context { private get { if (_context == null) { _context = new DataServiceContextWrapper(_httpClient.Uri); _context.SendingRequest += OnSendingRequest; _context.ReadingEntity += OnReadingEntity; _context.IgnoreMissingProperties = true; } return _context; } set { _context = value; } } private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e) { var package = (DataServicePackage)e.Entity; // REVIEW: This is the only way (I know) to download the package on demand // GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage package.Context = Context; package.Downloader = _packageDownloader; } private void OnSendingRequest(object sender, SendingRequestEventArgs e) { // Initialize the request _httpClient.InitializeRequest(e.Request); RaiseSendingRequest(new WebRequestEventArgs(e.Request)); } private void RaiseSendingRequest(WebRequestEventArgs e) { if (_sendingRequest != null) { _sendingRequest(this, e); } } public override IQueryable<IPackage> GetPackages() { // REVIEW: Is it ok to assume that the package entity set is called packages? return new SmartDataServiceQuery<DataServicePackage>(Context, PackageServiceEntitySetName); } public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions) { if (!Context.SupportsServiceMethod(SearchSvcMethod)) { // If there's no search method then we can't filter by target framework return GetPackages().Find(searchTerm) .FilterByPrerelease(allowPrereleaseVersions) .AsQueryable(); } // Convert the list of framework names into short names var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name)) .Select(VersionUtility.GetShortFrameworkName); // Create a '|' separated string of framework names string targetFrameworkString = String.Join("|", shortFrameworkNames); var searchParameters = new Dictionary<string, object> { { "searchTerm", "'" + UrlEncodeOdataParameter(searchTerm) + "'" }, { "targetFramework", "'" + UrlEncodeOdataParameter(targetFrameworkString) + "'" }, }; if (SupportsPrereleasePackages) { searchParameters.Add("includePrerelease", ToLowerCaseString(allowPrereleaseVersions)); } // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(SearchSvcMethod, searchParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query); } public bool Exists(string packageId, SemanticVersion version) { IQueryable<DataServicePackage> query = Context.CreateQuery<DataServicePackage>(PackageServiceEntitySetName).AsQueryable(); foreach (string versionString in version.GetComparableVersionStrings()) { try { var packages = query.Where(p => p.Id == packageId && p.Version == versionString) .Select(p => p.Id) // since we only want to check for existence, no need to get all attributes .ToArray(); if (packages.Length == 1) { return true; } } catch (DataServiceQueryException) { // DataServiceQuery exception will occur when the (id, version) // combination doesn't exist. } } return false; } public IPackage FindPackage(string packageId, SemanticVersion version) { IQueryable<DataServicePackage> query = Context.CreateQuery<DataServicePackage>(PackageServiceEntitySetName).AsQueryable(); foreach (string versionString in version.GetComparableVersionStrings()) { try { var packages = query.Where(p => p.Id == packageId && p.Version == versionString).ToArray(); Debug.Assert(packages == null || packages.Length <= 1); if (packages.Length != 0) { return packages[0]; } } catch (DataServiceQueryException) { // DataServiceQuery exception will occur when the (id, version) // combination doesn't exist. } } return null; } public IEnumerable<IPackage> FindPackagesById(string packageId) { try { if (!Context.SupportsServiceMethod(FindPackagesByIdSvcMethod)) { // If there's no search method then we can't filter by target framework return PackageRepositoryExtensions.FindPackagesByIdCore(this, packageId); } var serviceParameters = new Dictionary<string, object> { { "id", "'" + UrlEncodeOdataParameter(packageId) + "'" } }; // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query); } catch (Exception ex) { var message = string.Format( CultureInfo.CurrentCulture, NuGetResources.ErrorLoadingPackages, _httpClient.OriginalUri, ex.Message); throw new InvalidOperationException(message, ex); } } public IEnumerable<IPackage> GetUpdates( IEnumerable<IPackageName> packages, bool includePrerelease, bool includeAllVersions, IEnumerable<FrameworkName> targetFrameworks, IEnumerable<IVersionSpec> versionConstraints) { if (!Context.SupportsServiceMethod(GetUpdatesSvcMethod)) { // If there's no search method then we can't filter by target framework return PackageRepositoryExtensions.GetUpdatesCore(this, packages, includePrerelease, includeAllVersions, targetFrameworks, versionConstraints); } // Pipe all the things! string ids = String.Join("|", packages.Select(p => p.Id)); string versions = String.Join("|", packages.Select(p => p.Version.ToString())); string targetFrameworksValue = targetFrameworks.IsEmpty() ? "" : String.Join("|", targetFrameworks.Select(VersionUtility.GetShortFrameworkName)); string versionConstraintsValue = versionConstraints.IsEmpty() ? "" : String.Join("|", versionConstraints.Select(v => v == null ? "" : v.ToString())); var serviceParameters = new Dictionary<string, object> { { "packageIds", "'" + ids + "'" }, { "versions", "'" + versions + "'" }, { "includePrerelease", ToLowerCaseString(includePrerelease) }, { "includeAllVersions", ToLowerCaseString(includeAllVersions) }, { "targetFrameworks", "'" + UrlEncodeOdataParameter(targetFrameworksValue) + "'" }, { "versionConstraints", "'" + UrlEncodeOdataParameter(versionConstraintsValue) + "'" } }; var query = Context.CreateQuery<DataServicePackage>(GetUpdatesSvcMethod, serviceParameters); return new SmartDataServiceQuery<DataServicePackage>(Context, query); } public IPackageRepository Clone() { return new DataServicePackageRepository(_httpClient, _packageDownloader); } public IDisposable StartOperation(string operation, string mainPackageId, string mainPackageVersion) { Tuple<string, string, string> oldOperation = _currentOperation; _currentOperation = Tuple.Create(operation, mainPackageId, mainPackageVersion); return new DisposableAction(() => { _currentOperation = oldOperation; }); } public bool TryFindLatestPackageById(string id, out SemanticVersion latestVersion) { latestVersion = null; try { var serviceParameters = new Dictionary<string, object> { { "id", "'" + UrlEncodeOdataParameter(id) + "'" } }; // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters); var packages = (IQueryable<DataServicePackage>)query.AsQueryable(); var latestPackage = packages.Where(p => p.IsLatestVersion) .Select(p => new { p.Id, p.Version }) .FirstOrDefault(); if (latestPackage != null) { latestVersion = new SemanticVersion(latestPackage.Version); return true; } } catch (DataServiceQueryException) { } return false; } public bool TryFindLatestPackageById(string id, bool includePrerelease, out IPackage package) { try { var serviceParameters = new Dictionary<string, object> { { "id", "'" + UrlEncodeOdataParameter(id) + "'" } }; // Create a query for the search service method var query = Context.CreateQuery<DataServicePackage>(FindPackagesByIdSvcMethod, serviceParameters); var packages = (IQueryable<DataServicePackage>)query.AsQueryable(); if (includePrerelease) { package = packages.Where(p => p.IsAbsoluteLatestVersion).OrderByDescending(p => p.Version).FirstOrDefault(); } else { package = packages.Where(p => p.IsLatestVersion).OrderByDescending(p => p.Version).FirstOrDefault(); } return package != null; } catch (DataServiceQueryException) { package = null; return false; } } private static string UrlEncodeOdataParameter(string value) { if (!String.IsNullOrEmpty(value)) { // OData requires that a single quote MUST be escaped as 2 single quotes. // In .NET 4.5, Uri.EscapeDataString() escapes single quote as %27. Thus we must replace %27 with 2 single quotes. // In .NET 4.0, Uri.EscapeDataString() doesn't escape single quote. Thus we must replace it with 2 single quotes. return Uri.EscapeDataString(value).Replace("'", "''").Replace("%27", "''"); } return value; } [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")] private static string ToLowerCaseString(bool value) { return value.ToString().ToLowerInvariant(); } public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { if (managerType == typeof(SendingRequestEventManager)) { OnPackageDownloaderSendingRequest(sender, (WebRequestEventArgs)e); return true; } else { return false; } } } }
// // ImportManager.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using Mono.Unix; using Hyena; using Hyena.Jobs; using Hyena.Collections; using Banshee.IO; using Banshee.Base; using Banshee.ServiceStack; namespace Banshee.Collection { public class ImportManager : QueuePipeline<string> { #region Importing Pipeline Element private class ImportElement : QueuePipelineElement<string> { private ImportManager manager; public ImportElement (ImportManager manager) { this.manager = manager; } public override void Enqueue (string item) { base.Enqueue (item); manager.UpdateScannerProgress (); } protected override string ProcessItem (string item) { try { if (manager.Debug) Log.InformationFormat ("ImportElement processing {0}", item); manager.OnImportRequested (item); } catch (Exception e) { Hyena.Log.Error (e); } return null; } } #endregion public bool Debug { get { return scanner_element.Debug; } set { scanner_element.Debug = value; } } private static NumberFormatInfo number_format = new NumberFormatInfo (); private DirectoryScannerPipelineElement scanner_element; private ImportElement import_element; private readonly object user_job_mutex = new object (); private UserJob user_job; private uint timer_id; public event ImportEventHandler ImportRequested; public ImportManager () { AddElement (scanner_element = new DirectoryScannerPipelineElement ()); AddElement (import_element = new ImportElement (this)); } #region Public API public override void Enqueue (string path) { CreateUserJob (); base.Enqueue (path); } public void Enqueue (string [] paths) { CreateUserJob (); foreach (string path in paths) { base.Enqueue (path); } } public bool IsImportInProgress { get { return import_element.Processing; } } private bool keep_user_job_hidden = false; public bool KeepUserJobHidden { get { return keep_user_job_hidden; } set { keep_user_job_hidden = value; } } #endregion #region User Job / Interaction private void CreateUserJob () { lock (user_job_mutex) { if (user_job != null || KeepUserJobHidden) { return; } timer_id = Log.DebugTimerStart (); user_job = new UserJob (Title, Catalog.GetString ("Scanning for media")); user_job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database); user_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped; user_job.IconNames = new string [] { "system-search", "gtk-find" }; user_job.CancelMessage = CancelMessage; user_job.CanCancel = true; user_job.CancelRequested += OnCancelRequested; if (!KeepUserJobHidden) { user_job.Register (); } } } private void DestroyUserJob () { lock (user_job_mutex) { if (user_job == null) { return; } if (!KeepUserJobHidden) { Log.DebugTimerPrint (timer_id, Title + " duration: {0}"); } user_job.CancelRequested -= OnCancelRequested; user_job.Finish (); user_job = null; } } private void OnCancelRequested (object o, EventArgs args) { scanner_element.Cancel (); } protected void UpdateProgress (string message) { CreateUserJob (); if (user_job != null) { double new_progress = (double)import_element.ProcessedCount / (double)import_element.TotalCount; double old_progress = user_job.Progress; if (new_progress >= 0.0 && new_progress <= 1.0 && Math.Abs (new_progress - old_progress) > 0.001) { lock (number_format) { string disp_progress = String.Format (ProgressMessage, import_element.ProcessedCount, import_element.TotalCount); user_job.Title = disp_progress; user_job.Status = String.IsNullOrEmpty (message) ? Catalog.GetString ("Scanning...") : message; user_job.Progress = new_progress; } } } } private DateTime last_enqueue_display = DateTime.Now; private void UpdateScannerProgress () { CreateUserJob (); if (user_job != null) { if (DateTime.Now - last_enqueue_display > TimeSpan.FromMilliseconds (400)) { lock (number_format) { number_format.NumberDecimalDigits = 0; user_job.Status = String.Format (Catalog.GetString ("Scanning ({0} files)..."), import_element.TotalCount.ToString ("N", number_format)); last_enqueue_display = DateTime.Now; } } } } #endregion #region Protected Import Hooks protected virtual void OnImportRequested (string path) { ImportEventHandler handler = ImportRequested; if (handler != null && path != null) { ImportEventArgs args = new ImportEventArgs (path); handler (this, args); UpdateProgress (args.ReturnMessage); } else { UpdateProgress (null); } } protected override void OnFinished () { DestroyUserJob (); base.OnFinished (); } #endregion #region Properties private string title = Catalog.GetString ("Importing Media"); public string Title { get { return title; } set { title = value; } } private string cancel_message = Catalog.GetString ( "The import process is currently running. Would you like to stop it?"); public string CancelMessage { get { return cancel_message; } set { cancel_message = value; } } private string progress_message = Catalog.GetString ("Importing {0} of {1}"); public string ProgressMessage { get { return progress_message; } set { progress_message = value; } } public bool Threaded { set { import_element.Threaded = scanner_element.Threaded = value; } } public bool SkipHiddenChildren { set { scanner_element.SkipHiddenChildren = value; } } protected int TotalCount { get { return import_element == null ? 0 : import_element.TotalCount; } } #endregion } }
using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Util; using System; using System.Collections.Generic; using System.IO; namespace Lucene.Net.Classification { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A simplistic Lucene based NaiveBayes classifier, see <code>http://en.wikipedia.org/wiki/Naive_Bayes_classifier</code> /// /// @lucene.experimental /// </summary> public class SimpleNaiveBayesClassifier : IClassifier<BytesRef> { private AtomicReader _atomicReader; private string[] _textFieldNames; private string _classFieldName; private int _docsWithClassSize; private Analyzer _analyzer; private IndexSearcher _indexSearcher; private Query _query; /// <summary> /// Creates a new NaiveBayes classifier. /// Note that you must call <see cref="Train(AtomicReader, string, string, Analyzer)"/> before you can /// classify any documents. /// </summary> public SimpleNaiveBayesClassifier() { } /// <summary> /// Train the classifier using the underlying Lucene index /// </summary> /// <param name="analyzer"> the analyzer used to tokenize / filter the unseen text</param> /// <param name="atomicReader">the reader to use to access the Lucene index</param> /// <param name="classFieldName">the name of the field containing the class assigned to documents</param> /// <param name="textFieldName">the name of the field used to compare documents</param> public virtual void Train(AtomicReader atomicReader, string textFieldName, string classFieldName, Analyzer analyzer) { Train(atomicReader, textFieldName, classFieldName, analyzer, null); } /// <summary>Train the classifier using the underlying Lucene index</summary> /// <param name="analyzer">the analyzer used to tokenize / filter the unseen text</param> /// <param name="atomicReader">the reader to use to access the Lucene index</param> /// <param name="classFieldName">the name of the field containing the class assigned to documents</param> /// <param name="query">the query to filter which documents use for training</param> /// <param name="textFieldName">the name of the field used to compare documents</param> public virtual void Train(AtomicReader atomicReader, string textFieldName, string classFieldName, Analyzer analyzer, Query query) { Train(atomicReader, new string[]{textFieldName}, classFieldName, analyzer, query); } /// <summary>Train the classifier using the underlying Lucene index</summary> /// <param name="analyzer">the analyzer used to tokenize / filter the unseen text</param> /// <param name="atomicReader">the reader to use to access the Lucene index</param> /// <param name="classFieldName">the name of the field containing the class assigned to documents</param> /// <param name="query">the query to filter which documents use for training</param> /// <param name="textFieldNames">the names of the fields to be used to compare documents</param> public virtual void Train(AtomicReader atomicReader, string[] textFieldNames, string classFieldName, Analyzer analyzer, Query query) { _atomicReader = atomicReader; _indexSearcher = new IndexSearcher(_atomicReader); _textFieldNames = textFieldNames; _classFieldName = classFieldName; _analyzer = analyzer; _query = query; _docsWithClassSize = CountDocsWithClass(); } private int CountDocsWithClass() { int docCount = MultiFields.GetTerms(_atomicReader, _classFieldName).DocCount; if (docCount == -1) { // in case codec doesn't support getDocCount TotalHitCountCollector totalHitCountCollector = new TotalHitCountCollector(); BooleanQuery q = new BooleanQuery(); q.Add(new BooleanClause(new WildcardQuery(new Term(_classFieldName, WildcardQuery.WILDCARD_STRING.ToString())), Occur.MUST)); if (_query != null) { q.Add(_query, Occur.MUST); } _indexSearcher.Search(q, totalHitCountCollector); docCount = totalHitCountCollector.TotalHits; } return docCount; } private string[] TokenizeDoc(string doc) { ICollection<string> result = new LinkedList<string>(); foreach (string textFieldName in _textFieldNames) { TokenStream tokenStream = _analyzer.GetTokenStream(textFieldName, new StringReader(doc)); try { ICharTermAttribute charTermAttribute = tokenStream.AddAttribute<ICharTermAttribute>(); tokenStream.Reset(); while (tokenStream.IncrementToken()) { result.Add(charTermAttribute.ToString()); } tokenStream.End(); } finally { IOUtils.DisposeWhileHandlingException(tokenStream); } } var ret = new string[result.Count]; result.CopyTo(ret, 0); return ret; } /// <summary> /// Assign a class (with score) to the given text string /// </summary> /// <param name="inputDocument">a string containing text to be classified</param> /// <returns>a <see cref="ClassificationResult{BytesRef}"/> holding assigned class of type <see cref="BytesRef"/> and score</returns> public virtual ClassificationResult<BytesRef> AssignClass(string inputDocument) { if (_atomicReader == null) { throw new IOException("You must first call Classifier#train"); } double max = - double.MaxValue; BytesRef foundClass = new BytesRef(); Terms terms = MultiFields.GetTerms(_atomicReader, _classFieldName); TermsEnum termsEnum = terms.GetEnumerator(); BytesRef next; string[] tokenizedDoc = TokenizeDoc(inputDocument); while (termsEnum.MoveNext()) { next = termsEnum.Term; double clVal = CalculateLogPrior(next) + CalculateLogLikelihood(tokenizedDoc, next); if (clVal > max) { max = clVal; foundClass = BytesRef.DeepCopyOf(next); } } double score = 10 / Math.Abs(max); return new ClassificationResult<BytesRef>(foundClass, score); } private double CalculateLogLikelihood(string[] tokenizedDoc, BytesRef c) { // for each word double result = 0d; foreach (string word in tokenizedDoc) { // search with text:word AND class:c int hits = GetWordFreqForClass(word, c); // num : count the no of times the word appears in documents of class c (+1) double num = hits + 1; // +1 is added because of add 1 smoothing // den : for the whole dictionary, count the no of times a word appears in documents of class c (+|V|) double den = GetTextTermFreqForClass(c) + _docsWithClassSize; // P(w|c) = num/den double wordProbability = num / den; result += Math.Log(wordProbability); } // log(P(d|c)) = log(P(w1|c))+...+log(P(wn|c)) return result; } private double GetTextTermFreqForClass(BytesRef c) { double avgNumberOfUniqueTerms = 0; foreach (string textFieldName in _textFieldNames) { Terms terms = MultiFields.GetTerms(_atomicReader, textFieldName); long numPostings = terms.SumDocFreq; // number of term/doc pairs avgNumberOfUniqueTerms += numPostings / (double) terms.DocCount; // avg # of unique terms per doc } int docsWithC = _atomicReader.DocFreq(new Term(_classFieldName, c)); return avgNumberOfUniqueTerms * docsWithC; // avg # of unique terms in text fields per doc * # docs with c } private int GetWordFreqForClass(string word, BytesRef c) { BooleanQuery booleanQuery = new BooleanQuery(); BooleanQuery subQuery = new BooleanQuery(); foreach (string textFieldName in _textFieldNames) { subQuery.Add(new BooleanClause(new TermQuery(new Term(textFieldName, word)), Occur.SHOULD)); } booleanQuery.Add(new BooleanClause(subQuery, Occur.MUST)); booleanQuery.Add(new BooleanClause(new TermQuery(new Term(_classFieldName, c)), Occur.MUST)); if (_query != null) { booleanQuery.Add(_query, Occur.MUST); } TotalHitCountCollector totalHitCountCollector = new TotalHitCountCollector(); _indexSearcher.Search(booleanQuery, totalHitCountCollector); return totalHitCountCollector.TotalHits; } private double CalculateLogPrior(BytesRef currentClass) { return Math.Log((double) DocCount(currentClass)) - Math.Log(_docsWithClassSize); } private int DocCount(BytesRef countedClass) { return _atomicReader.DocFreq(new Term(_classFieldName, countedClass)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MinScalarDouble() { var test = new SimpleBinaryOpTest__MinScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinScalarDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinScalarDouble testClass) { var result = Sse2.MinScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinScalarDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MinScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinScalarDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__MinScalarDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.MinScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.MinScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.MinScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MinScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MinScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.MinScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.MinScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.MinScalar( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.MinScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.MinScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.MinScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinScalarDouble(); var result = Sse2.MinScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MinScalarDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.MinScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.MinScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.MinScalar( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.MinScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.MinScalar( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(Math.Min(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.MinScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests { public class Vector3Tests { [Fact] public void Vector3MarshalSizeTest() { Assert.Equal(12, Marshal.SizeOf<Vector3>()); Assert.Equal(12, Marshal.SizeOf<Vector3>(new Vector3())); } [Fact] public void Vector3CopyToTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); float[] a = new float[4]; float[] b = new float[3]; Assert.Throws<NullReferenceException>(() => v1.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => v1.CopyTo(a, a.Length)); Assert.Throws<ArgumentException>(() => v1.CopyTo(a, a.Length - 2)); v1.CopyTo(a, 1); v1.CopyTo(b); Assert.Equal(0.0f, a[0]); Assert.Equal(2.0f, a[1]); Assert.Equal(3.0f, a[2]); Assert.Equal(3.3f, a[3]); Assert.Equal(2.0f, b[0]); Assert.Equal(3.0f, b[1]); Assert.Equal(3.3f, b[2]); } [Fact] public void Vector3GetHashCodeTest() { Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); Vector3 v2 = new Vector3(4.5f, 6.5f, 7.5f); Vector3 v3 = new Vector3(2.0f, 3.0f, 3.3f); Vector3 v5 = new Vector3(3.0f, 2.0f, 3.3f); Assert.True(v1.GetHashCode() == v1.GetHashCode()); Assert.False(v1.GetHashCode() == v5.GetHashCode()); Assert.True(v1.GetHashCode() == v3.GetHashCode()); Vector3 v4 = new Vector3(0.0f, 0.0f, 0.0f); Vector3 v6 = new Vector3(1.0f, 0.0f, 0.0f); Vector3 v7 = new Vector3(0.0f, 1.0f, 0.0f); Vector3 v8 = new Vector3(1.0f, 1.0f, 1.0f); Vector3 v9 = new Vector3(1.0f, 1.0f, 0.0f); Assert.False(v4.GetHashCode() == v6.GetHashCode()); Assert.False(v4.GetHashCode() == v7.GetHashCode()); Assert.False(v4.GetHashCode() == v8.GetHashCode()); Assert.False(v7.GetHashCode() == v6.GetHashCode()); Assert.False(v8.GetHashCode() == v6.GetHashCode()); Assert.True(v8.GetHashCode() == v7.GetHashCode()); Assert.False(v8.GetHashCode() == v9.GetHashCode()); Assert.False(v7.GetHashCode() == v9.GetHashCode()); } [Fact] public void Vector3ToStringTest() { string separator = CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator; CultureInfo enUsCultureInfo = new CultureInfo("en-US"); Vector3 v1 = new Vector3(2.0f, 3.0f, 3.3f); string v1str = v1.ToString(); string expectedv1 = string.Format(CultureInfo.CurrentCulture , "<{1:G}{0} {2:G}{0} {3:G}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv1, v1str); string v1strformatted = v1.ToString("c", CultureInfo.CurrentCulture); string expectedv1formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}{0} {3:c}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv1formatted, v1strformatted); string v2strformatted = v1.ToString("c", enUsCultureInfo); string expectedv2formatted = string.Format(enUsCultureInfo , "<{1:c}{0} {2:c}{0} {3:c}>" , enUsCultureInfo.NumberFormat.NumberGroupSeparator, 2, 3, 3.3); Assert.Equal(expectedv2formatted, v2strformatted); string v3strformatted = v1.ToString("c"); string expectedv3formatted = string.Format(CultureInfo.CurrentCulture , "<{1:c}{0} {2:c}{0} {3:c}>" , separator, 2, 3, 3.3); Assert.Equal(expectedv3formatted, v3strformatted); } // A test for Cross (Vector3f, Vector3f) [Fact] public void Vector3CrossTest() { Vector3 a = new Vector3(1.0f, 0.0f, 0.0f); Vector3 b = new Vector3(0.0f, 1.0f, 0.0f); Vector3 expected = new Vector3(0.0f, 0.0f, 1.0f); Vector3 actual; actual = Vector3.Cross(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value."); } // A test for Cross (Vector3f, Vector3f) // Cross test of the same vector [Fact] public void Vector3CrossTest1() { Vector3 a = new Vector3(0.0f, 1.0f, 0.0f); Vector3 b = new Vector3(0.0f, 1.0f, 0.0f); Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f); Vector3 actual = Vector3.Cross(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Cross did not return the expected value."); } // A test for Distance (Vector3f, Vector3f) [Fact] public void Vector3DistanceTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float expected = (float)System.Math.Sqrt(27); float actual; actual = Vector3.Distance(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Distance did not return the expected value."); } // A test for Distance (Vector3f, Vector3f) // Distance from the same point [Fact] public void Vector3DistanceTest1() { Vector3 a = new Vector3(1.051f, 2.05f, 3.478f); Vector3 b = new Vector3(new Vector2(1.051f, 0.0f), 1); b.Y = 2.05f; b.Z = 3.478f; float actual = Vector3.Distance(a, b); Assert.Equal(0.0f, actual); } // A test for DistanceSquared (Vector3f, Vector3f) [Fact] public void Vector3DistanceSquaredTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float expected = 27.0f; float actual; actual = Vector3.DistanceSquared(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.DistanceSquared did not return the expected value."); } // A test for Dot (Vector3f, Vector3f) [Fact] public void Vector3DotTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float expected = 32.0f; float actual; actual = Vector3.Dot(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Dot did not return the expected value."); } // A test for Dot (Vector3f, Vector3f) // Dot test for perpendicular vector [Fact] public void Vector3DotTest1() { Vector3 a = new Vector3(1.55f, 1.55f, 1); Vector3 b = new Vector3(2.5f, 3, 1.5f); Vector3 c = Vector3.Cross(a, b); float expected = 0.0f; float actual1 = Vector3.Dot(a, c); float actual2 = Vector3.Dot(b, c); Assert.True(MathHelper.Equal(expected, actual1), "Vector3f.Dot did not return the expected value."); Assert.True(MathHelper.Equal(expected, actual2), "Vector3f.Dot did not return the expected value."); } // A test for Length () [Fact] public void Vector3LengthTest() { Vector2 a = new Vector2(1.0f, 2.0f); float z = 3.0f; Vector3 target = new Vector3(a, z); float expected = (float)System.Math.Sqrt(14.0f); float actual; actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value."); } // A test for Length () // Length test where length is zero [Fact] public void Vector3LengthTest1() { Vector3 target = new Vector3(); float expected = 0.0f; float actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Length did not return the expected value."); } // A test for LengthSquared () [Fact] public void Vector3LengthSquaredTest() { Vector2 a = new Vector2(1.0f, 2.0f); float z = 3.0f; Vector3 target = new Vector3(a, z); float expected = 14.0f; float actual; actual = target.LengthSquared(); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.LengthSquared did not return the expected value."); } // A test for Min (Vector3f, Vector3f) [Fact] public void Vector3MinTest() { Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f); Vector3 b = new Vector3(2.0f, 1.0f, -1.0f); Vector3 expected = new Vector3(-1.0f, 1.0f, -3.0f); Vector3 actual; actual = Vector3.Min(a, b); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Min did not return the expected value."); } // A test for Max (Vector3f, Vector3f) [Fact] public void Vector3MaxTest() { Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f); Vector3 b = new Vector3(2.0f, 1.0f, -1.0f); Vector3 expected = new Vector3(2.0f, 4.0f, -1.0f); Vector3 actual; actual = Vector3.Max(a, b); Assert.True(MathHelper.Equal(expected, actual), "vector3.Max did not return the expected value."); } [Fact] public void Vector3MinMaxCodeCoverageTest() { Vector3 min = Vector3.Zero; Vector3 max = Vector3.One; Vector3 actual; // Min. actual = Vector3.Min(min, max); Assert.Equal(actual, min); actual = Vector3.Min(max, min); Assert.Equal(actual, min); // Max. actual = Vector3.Max(min, max); Assert.Equal(actual, max); actual = Vector3.Max(max, min); Assert.Equal(actual, max); } // A test for Lerp (Vector3f, Vector3f, float) [Fact] public void Vector3LerpTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 0.5f; Vector3 expected = new Vector3(2.5f, 3.5f, 4.5f); Vector3 actual; actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor zero [Fact] public void Vector3LerpTest1() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 0.0f; Vector3 expected = new Vector3(1.0f, 2.0f, 3.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor one [Fact] public void Vector3LerpTest2() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 1.0f; Vector3 expected = new Vector3(4.0f, 5.0f, 6.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor > 1 [Fact] public void Vector3LerpTest3() { Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = 2.0f; Vector3 expected = new Vector3(8.0f, 10.0f, 12.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test with factor < 0 [Fact] public void Vector3LerpTest4() { Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); float t = -2.0f; Vector3 expected = new Vector3(-8.0f, -10.0f, -12.0f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Lerp (Vector3f, Vector3f, float) // Lerp test from the same point [Fact] public void Vector3LerpTest5() { Vector3 a = new Vector3(1.68f, 2.34f, 5.43f); Vector3 b = a; float t = 0.18f; Vector3 expected = new Vector3(1.68f, 2.34f, 5.43f); Vector3 actual = Vector3.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Lerp did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) [Fact] public void Vector3ReflectTest() { Vector3 a = Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f)); // Reflect on XZ plane. Vector3 n = new Vector3(0.0f, 1.0f, 0.0f); Vector3 expected = new Vector3(a.X, -a.Y, a.Z); Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); // Reflect on XY plane. n = new Vector3(0.0f, 0.0f, 1.0f); expected = new Vector3(a.X, a.Y, -a.Z); actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); // Reflect on YZ plane. n = new Vector3(1.0f, 0.0f, 0.0f); expected = new Vector3(-a.X, a.Y, a.Z); actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) // Reflection when normal and source are the same [Fact] public void Vector3ReflectTest1() { Vector3 n = new Vector3(0.45f, 1.28f, 0.86f); n = Vector3.Normalize(n); Vector3 a = n; Vector3 expected = -n; Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) // Reflection when normal and source are negation [Fact] public void Vector3ReflectTest2() { Vector3 n = new Vector3(0.45f, 1.28f, 0.86f); n = Vector3.Normalize(n); Vector3 a = -n; Vector3 expected = n; Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Reflect (Vector3f, Vector3f) // Reflection when normal and source are perpendicular (a dot n = 0) [Fact] public void Vector3ReflectTest3() { Vector3 n = new Vector3(0.45f, 1.28f, 0.86f); Vector3 temp = new Vector3(1.28f, 0.45f, 0.01f); // find a perpendicular vector of n Vector3 a = Vector3.Cross(temp, n); Vector3 expected = a; Vector3 actual = Vector3.Reflect(a, n); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Reflect did not return the expected value."); } // A test for Transform(Vector3f, Matrix4x4) [Fact] public void Vector3TransformTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Vector3 expected = new Vector3(12.191987f, 21.533493f, 32.616024f); Vector3 actual; actual = Vector3.Transform(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Clamp (Vector3f, Vector3f, Vector3f) [Fact] public void Vector3ClampTest() { Vector3 a = new Vector3(0.5f, 0.3f, 0.33f); Vector3 min = new Vector3(0.0f, 0.1f, 0.13f); Vector3 max = new Vector3(1.0f, 1.1f, 1.13f); // Normal case. // Case N1: specified value is in the range. Vector3 expected = new Vector3(0.5f, 0.3f, 0.33f); Vector3 actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Normal case. // Case N2: specified value is bigger than max value. a = new Vector3(2.0f, 3.0f, 4.0f); expected = max; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Case N3: specified value is smaller than max value. a = new Vector3(-2.0f, -3.0f, -4.0f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Case N4: combination case. a = new Vector3(-2.0f, 0.5f, 4.0f); expected = new Vector3(min.X, a.Y, max.Z); actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // User specified min value is bigger than max value. max = new Vector3(0.0f, 0.1f, 0.13f); min = new Vector3(1.0f, 1.1f, 1.13f); // Case W1: specified value is in the range. a = new Vector3(0.5f, 0.3f, 0.33f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Normal case. // Case W2: specified value is bigger than max and min value. a = new Vector3(2.0f, 3.0f, 4.0f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); // Case W3: specified value is smaller than min and max value. a = new Vector3(-2.0f, -3.0f, -4.0f); expected = min; actual = Vector3.Clamp(a, min, max); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Clamp did not return the expected value."); } // A test for TransformNormal (Vector3f, Matrix4x4) [Fact] public void Vector3TransformNormalTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Vector3 expected = new Vector3(2.19198728f, 1.53349364f, 2.61602545f); Vector3 actual; actual = Vector3.TransformNormal(v, m); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.TransformNormal did not return the expected value."); } // A test for Transform (Vector3f, Quaternion) [Fact] public void Vector3TransformByQuaternionTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); Quaternion q = Quaternion.CreateFromRotationMatrix(m); Vector3 expected = Vector3.Transform(v, m); Vector3 actual = Vector3.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Transform (Vector3f, Quaternion) // Transform vector3 with zero quaternion [Fact] public void Vector3TransformByQuaternionTest1() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Quaternion q = new Quaternion(); Vector3 expected = v; Vector3 actual = Vector3.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Transform (Vector3f, Quaternion) // Transform vector3 with identity quaternion [Fact] public void Vector3TransformByQuaternionTest2() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); Quaternion q = Quaternion.Identity; Vector3 expected = v; Vector3 actual = Vector3.Transform(v, q); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Transform did not return the expected value."); } // A test for Normalize (Vector3f) [Fact] public void Vector3NormalizeTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 expected = new Vector3( 0.26726124191242438468455348087975f, 0.53452248382484876936910696175951f, 0.80178372573727315405366044263926f); Vector3 actual; actual = Vector3.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value."); } // A test for Normalize (Vector3f) // Normalize vector of length one [Fact] public void Vector3NormalizeTest1() { Vector3 a = new Vector3(1.0f, 0.0f, 0.0f); Vector3 expected = new Vector3(1.0f, 0.0f, 0.0f); Vector3 actual = Vector3.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Vector3f.Normalize did not return the expected value."); } // A test for Normalize (Vector3f) // Normalize vector of length zero [Fact] public void Vector3NormalizeTest2() { Vector3 a = new Vector3(0.0f, 0.0f, 0.0f); Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f); Vector3 actual = Vector3.Normalize(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z), "Vector3f.Normalize did not return the expected value."); } // A test for operator - (Vector3f) [Fact] public void Vector3UnaryNegationTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f); Vector3 actual; actual = -a; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value."); } [Fact] public void Vector3UnaryNegationTest1() { Vector3 a = -new Vector3(Single.NaN, Single.PositiveInfinity, Single.NegativeInfinity); Vector3 b = -new Vector3(0.0f, 0.0f, 0.0f); Assert.Equal(Single.NaN, a.X); Assert.Equal(Single.NegativeInfinity, a.Y); Assert.Equal(Single.PositiveInfinity, a.Z); Assert.Equal(0.0f, b.X); Assert.Equal(0.0f, b.Y); Assert.Equal(0.0f, b.Z); } // A test for operator - (Vector3f, Vector3f) [Fact] public void Vector3SubtractionTest() { Vector3 a = new Vector3(4.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 5.0f, 7.0f); Vector3 expected = new Vector3(3.0f, -3.0f, -4.0f); Vector3 actual; actual = a - b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator - did not return the expected value."); } // A test for operator * (Vector3f, float) [Fact] public void Vector3MultiplyOperatorTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float factor = 2.0f; Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f); Vector3 actual; actual = a * factor; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value."); } // A test for operator * (float, Vector3f) [Fact] public void Vector3MultiplyOperatorTest2() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); const float factor = 2.0f; Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f); Vector3 actual; actual = factor * a; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value."); } // A test for operator * (Vector3f, Vector3f) [Fact] public void Vector3MultiplyOperatorTest3() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); Vector3 expected = new Vector3(4.0f, 10.0f, 18.0f); Vector3 actual; actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator * did not return the expected value."); } // A test for operator / (Vector3f, float) [Fact] public void Vector3DivisionTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float div = 2.0f; Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f); Vector3 actual; actual = a / div; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value."); } // A test for operator / (Vector3f, Vector3f) [Fact] public void Vector3DivisionTest1() { Vector3 a = new Vector3(4.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 5.0f, 6.0f); Vector3 expected = new Vector3(4.0f, 0.4f, 0.5f); Vector3 actual; actual = a / b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator / did not return the expected value."); } // A test for operator / (Vector3f, Vector3f) // Divide by zero [Fact] public void Vector3DivisionTest2() { Vector3 a = new Vector3(-2.0f, 3.0f, float.MaxValue); float div = 0.0f; Vector3 actual = a / div; Assert.True(float.IsNegativeInfinity(actual.X), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsPositiveInfinity(actual.Y), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsPositiveInfinity(actual.Z), "Vector3f.operator / did not return the expected value."); } // A test for operator / (Vector3f, Vector3f) // Divide by zero [Fact] public void Vector3DivisionTest3() { Vector3 a = new Vector3(0.047f, -3.0f, float.NegativeInfinity); Vector3 b = new Vector3(); Vector3 actual = a / b; Assert.True(float.IsPositiveInfinity(actual.X), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsNegativeInfinity(actual.Y), "Vector3f.operator / did not return the expected value."); Assert.True(float.IsNegativeInfinity(actual.Z), "Vector3f.operator / did not return the expected value."); } // A test for operator + (Vector3f, Vector3f) [Fact] public void Vector3AdditionTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(4.0f, 5.0f, 6.0f); Vector3 expected = new Vector3(5.0f, 7.0f, 9.0f); Vector3 actual; actual = a + b; Assert.True(MathHelper.Equal(expected, actual), "Vector3f.operator + did not return the expected value."); } // A test for Vector3f (float, float, float) [Fact] public void Vector3ConstructorTest() { float x = 1.0f; float y = 2.0f; float z = 3.0f; Vector3 target = new Vector3(x, y, z); Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (x,y,z) did not return the expected value."); } // A test for Vector3f (Vector2f, float) [Fact] public void Vector3ConstructorTest1() { Vector2 a = new Vector2(1.0f, 2.0f); float z = 3.0f; Vector3 target = new Vector3(a, z); Assert.True(MathHelper.Equal(target.X, a.X) && MathHelper.Equal(target.Y, a.Y) && MathHelper.Equal(target.Z, z), "Vector3f.constructor (Vector2f,z) did not return the expected value."); } // A test for Vector3f () // Constructor with no parameter [Fact] public void Vector3ConstructorTest3() { Vector3 a = new Vector3(); Assert.Equal(a.X, 0.0f); Assert.Equal(a.Y, 0.0f); Assert.Equal(a.Z, 0.0f); } // A test for Vector2f (float, float) // Constructor with special floating values [Fact] public void Vector3ConstructorTest4() { Vector3 target = new Vector3(float.NaN, float.MaxValue, float.PositiveInfinity); Assert.True(float.IsNaN(target.X), "Vector3f.constructor (Vector3f) did not return the expected value."); Assert.True(float.Equals(float.MaxValue, target.Y), "Vector3f.constructor (Vector3f) did not return the expected value."); Assert.True(float.IsPositiveInfinity(target.Z), "Vector3f.constructor (Vector3f) did not return the expected value."); } // A test for Add (Vector3f, Vector3f) [Fact] public void Vector3AddTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(5.0f, 6.0f, 7.0f); Vector3 expected = new Vector3(6.0f, 8.0f, 10.0f); Vector3 actual; actual = Vector3.Add(a, b); Assert.Equal(expected, actual); } // A test for Divide (Vector3f, float) [Fact] public void Vector3DivideTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); float div = 2.0f; Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f); Vector3 actual; actual = Vector3.Divide(a, div); Assert.Equal(expected, actual); } // A test for Divide (Vector3f, Vector3f) [Fact] public void Vector3DivideTest1() { Vector3 a = new Vector3(1.0f, 6.0f, 7.0f); Vector3 b = new Vector3(5.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(1.0f / 5.0f, 6.0f / 2.0f, 7.0f / 3.0f); Vector3 actual; actual = Vector3.Divide(a, b); Assert.Equal(expected, actual); } // A test for Equals (object) [Fact] public void Vector3EqualsTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Quaternion(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for Multiply (Vector3f, float) [Fact] public void Vector3MultiplyTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); const float factor = 2.0f; Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f); Vector3 actual = Vector3.Multiply(a, factor); Assert.Equal(expected, actual); } // A test for Multiply (float, Vector3f) [Fact] public static void Vector3MultiplyTest2() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); const float factor = 2.0f; Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f); Vector3 actual = Vector3.Multiply(factor, a); Assert.Equal(expected, actual); } // A test for Multiply (Vector3f, Vector3f) [Fact] public void Vector3MultiplyTest3() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(5.0f, 6.0f, 7.0f); Vector3 expected = new Vector3(5.0f, 12.0f, 21.0f); Vector3 actual; actual = Vector3.Multiply(a, b); Assert.Equal(expected, actual); } // A test for Negate (Vector3f) [Fact] public void Vector3NegateTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f); Vector3 actual; actual = Vector3.Negate(a); Assert.Equal(expected, actual); } // A test for operator != (Vector3f, Vector3f) [Fact] public void Vector3InequalityTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Vector3f, Vector3f) [Fact] public void Vector3EqualityTest() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for Subtract (Vector3f, Vector3f) [Fact] public void Vector3SubtractTest() { Vector3 a = new Vector3(1.0f, 6.0f, 3.0f); Vector3 b = new Vector3(5.0f, 2.0f, 3.0f); Vector3 expected = new Vector3(-4.0f, 4.0f, 0.0f); Vector3 actual; actual = Vector3.Subtract(a, b); Assert.Equal(expected, actual); } // A test for One [Fact] public void Vector3OneTest() { Vector3 val = new Vector3(1.0f, 1.0f, 1.0f); Assert.Equal(val, Vector3.One); } // A test for UnitX [Fact] public void Vector3UnitXTest() { Vector3 val = new Vector3(1.0f, 0.0f, 0.0f); Assert.Equal(val, Vector3.UnitX); } // A test for UnitY [Fact] public void Vector3UnitYTest() { Vector3 val = new Vector3(0.0f, 1.0f, 0.0f); Assert.Equal(val, Vector3.UnitY); } // A test for UnitZ [Fact] public void Vector3UnitZTest() { Vector3 val = new Vector3(0.0f, 0.0f, 1.0f); Assert.Equal(val, Vector3.UnitZ); } // A test for Zero [Fact] public void Vector3ZeroTest() { Vector3 val = new Vector3(0.0f, 0.0f, 0.0f); Assert.Equal(val, Vector3.Zero); } // A test for Equals (Vector3f) [Fact] public void Vector3EqualsTest1() { Vector3 a = new Vector3(1.0f, 2.0f, 3.0f); Vector3 b = new Vector3(1.0f, 2.0f, 3.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for Vector3f (float) [Fact] public void Vector3ConstructorTest5() { float value = 1.0f; Vector3 target = new Vector3(value); Vector3 expected = new Vector3(value, value, value); Assert.Equal(expected, target); value = 2.0f; target = new Vector3(value); expected = new Vector3(value, value, value); Assert.Equal(expected, target); } // A test for Vector3f comparison involving NaN values [Fact] public void Vector3EqualsNanTest() { Vector3 a = new Vector3(float.NaN, 0, 0); Vector3 b = new Vector3(0, float.NaN, 0); Vector3 c = new Vector3(0, 0, float.NaN); Assert.False(a == Vector3.Zero); Assert.False(b == Vector3.Zero); Assert.False(c == Vector3.Zero); Assert.True(a != Vector3.Zero); Assert.True(b != Vector3.Zero); Assert.True(c != Vector3.Zero); Assert.False(a.Equals(Vector3.Zero)); Assert.False(b.Equals(Vector3.Zero)); Assert.False(c.Equals(Vector3.Zero)); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); Assert.False(c.Equals(c)); } [Fact] public void Vector3AbsTest() { Vector3 v1 = new Vector3(-2.5f, 2.0f, 0.5f); Vector3 v3 = Vector3.Abs(new Vector3(0.0f, Single.NegativeInfinity, Single.NaN)); Vector3 v = Vector3.Abs(v1); Assert.Equal(2.5f, v.X); Assert.Equal(2.0f, v.Y); Assert.Equal(0.5f, v.Z); Assert.Equal(0.0f, v3.X); Assert.Equal(Single.PositiveInfinity, v3.Y); Assert.Equal(Single.NaN, v3.Z); } [Fact] public void Vector3SqrtTest() { Vector3 a = new Vector3(-2.5f, 2.0f, 0.5f); Vector3 b = new Vector3(5.5f, 4.5f, 16.5f); Assert.Equal(2, (int)Vector3.SquareRoot(b).X); Assert.Equal(2, (int)Vector3.SquareRoot(b).Y); Assert.Equal(4, (int)Vector3.SquareRoot(b).Z); Assert.Equal(Single.NaN, Vector3.SquareRoot(a).X); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void Vector3SizeofTest() { Assert.Equal(12, sizeof(Vector3)); Assert.Equal(24, sizeof(Vector3_2x)); Assert.Equal(16, sizeof(Vector3PlusFloat)); Assert.Equal(32, sizeof(Vector3PlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Vector3_2x { private Vector3 _a; private Vector3 _b; } [StructLayout(LayoutKind.Sequential)] struct Vector3PlusFloat { private Vector3 _v; private float _f; } [StructLayout(LayoutKind.Sequential)] struct Vector3PlusFloat_2x { private Vector3PlusFloat _a; private Vector3PlusFloat _b; } [Fact] public void SetFieldsTest() { Vector3 v3 = new Vector3(4f, 5f, 6f); v3.X = 1.0f; v3.Y = 2.0f; v3.Z = 3.0f; Assert.Equal(1.0f, v3.X); Assert.Equal(2.0f, v3.Y); Assert.Equal(3.0f, v3.Z); Vector3 v4 = v3; v4.Y = 0.5f; v4.Z = 2.2f; Assert.Equal(1.0f, v4.X); Assert.Equal(0.5f, v4.Y); Assert.Equal(2.2f, v4.Z); Assert.Equal(2.0f, v3.Y); Vector3 before = new Vector3(1f, 2f, 3f); Vector3 after = before; after.X = 500.0f; Assert.NotEqual(before, after); } [Fact] public void EmbeddedVectorSetFields() { EmbeddedVectorObject evo = new EmbeddedVectorObject(); evo.FieldVector.X = 5.0f; evo.FieldVector.Y = 5.0f; evo.FieldVector.Z = 5.0f; Assert.Equal(5.0f, evo.FieldVector.X); Assert.Equal(5.0f, evo.FieldVector.Y); Assert.Equal(5.0f, evo.FieldVector.Z); } private class EmbeddedVectorObject { public Vector3 FieldVector; } } }
// // TreeViewBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using System.Collections.Generic; #if MONOMAC using MonoMac.AppKit; using MonoMac.Foundation; using nint = System.Int32; using nfloat = System.Single; using CGPoint = System.Drawing.PointF; #else using AppKit; using Foundation; using CoreGraphics; #endif namespace Xwt.Mac { public class TreeViewBackend: TableViewBackend<NSOutlineView,ITreeViewEventSink>, ITreeViewBackend { ITreeDataSource source; TreeSource tsource; class TreeDelegate: NSOutlineViewDelegate { public TreeViewBackend Backend; public override void ItemDidExpand (NSNotification notification) { Backend.EventSink.OnRowExpanded (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemWillExpand (NSNotification notification) { Backend.EventSink.OnRowExpanding (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemDidCollapse (NSNotification notification) { Backend.EventSink.OnRowCollapsed (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override void ItemWillCollapse (NSNotification notification) { Backend.EventSink.OnRowCollapsing (((TreeItem)notification.UserInfo["NSObject"]).Position); } public override nfloat GetRowHeight (NSOutlineView outlineView, NSObject item) { var height = outlineView.RowHeight; var row = outlineView.RowForItem (item); for (int i = 0; i < outlineView.ColumnCount; i++) { var cell = outlineView.GetCell (i, row); if (cell != null) height = (nfloat) Math.Max (height, cell.CellSize.Height); } return height; } } NSOutlineView Tree { get { return (NSOutlineView) Table; } } protected override NSTableView CreateView () { var t = new OutlineViewBackend (EventSink, ApplicationContext); t.Delegate = new TreeDelegate () { Backend = this }; return t; } protected override string SelectionChangeEventName { get { return "NSOutlineViewSelectionDidChangeNotification"; } } public TreePosition CurrentEventRow { get; internal set; } public override NSTableColumn AddColumn (ListViewColumn col) { NSTableColumn tcol = base.AddColumn (col); if (Tree.OutlineTableColumn == null) Tree.OutlineTableColumn = tcol; return tcol; } public void SetSource (ITreeDataSource source, IBackend sourceBackend) { this.source = source; tsource = new TreeSource (source); Tree.DataSource = tsource; source.NodeInserted += (sender, e) => Tree.ReloadItem (tsource.GetItem (source.GetParent(e.Node)), true); source.NodeDeleted += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), true); source.NodeChanged += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), false); source.NodesReordered += (sender, e) => Tree.ReloadItem (tsource.GetItem (e.Node), true); } public override object GetValue (object pos, int nField) { return source.GetValue ((TreePosition)pos, nField); } public override void SetValue (object pos, int nField, object value) { source.SetValue ((TreePosition)pos, nField, value); } public TreePosition[] SelectedRows { get { TreePosition[] res = new TreePosition [Table.SelectedRowCount]; int n = 0; if (Table.SelectedRowCount > 0) { foreach (var i in Table.SelectedRows) { res [n] = ((TreeItem)Tree.ItemAtRow ((int)i)).Position; } } return res; } } public TreePosition FocusedRow { get { if (Table.SelectedRowCount > 0) return ((TreeItem)Tree.ItemAtRow ((int)Table.SelectedRows.FirstIndex)).Position; return null; } set { SelectRow (value); } } public override void SetCurrentEventRow (object pos) { CurrentEventRow = (TreePosition)pos; } public void SelectRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Table.SelectRow ((int)Tree.RowForItem (it), Table.AllowsMultipleSelection); } public void UnselectRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Table.DeselectRow (Tree.RowForItem (it)); } public bool IsRowSelected (TreePosition pos) { var it = tsource.GetItem (pos); return it != null && Table.IsRowSelected (Tree.RowForItem (it)); } public bool IsRowExpanded (TreePosition pos) { var it = tsource.GetItem (pos); return it != null && Tree.IsItemExpanded (it); } public void ExpandRow (TreePosition pos, bool expandChildren) { var it = tsource.GetItem (pos); if (it != null) Tree.ExpandItem (it, expandChildren); } public void CollapseRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) Tree.CollapseItem (it); } public void ScrollToRow (TreePosition pos) { var it = tsource.GetItem (pos); if (it != null) ScrollToRow ((int)Tree.RowForItem (it)); } public void ExpandToRow (TreePosition pos) { var p = source.GetParent (pos); while (p != null) { var it = tsource.GetItem (p); if (it == null) break; Tree.ExpandItem (it, false); p = source.GetParent (p); } } public TreePosition GetRowAtPosition (Point p) { var row = Table.GetRow (new CGPoint ((float)p.X, (float)p.Y)); return row >= 0 ? ((TreeItem)Tree.ItemAtRow (row)).Position : null; } public Rectangle GetCellBounds (TreePosition pos, CellView cell, bool includeMargin) { var it = tsource.GetItem (pos); if (it == null) return Rectangle.Zero; var row = (int)Tree.RowForItem (it); return GetCellBounds (row, cell, includeMargin); } public Rectangle GetRowBounds (TreePosition pos, bool includeMargin) { var it = tsource.GetItem (pos); if (it == null) return Rectangle.Zero; var row = (int)Tree.RowForItem (it); return GetRowBounds (row, includeMargin); } public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition) { // Get row nint row = Tree.GetRow(new CGPoint ((nfloat)x, (nfloat)y)); pos = RowDropPosition.Into; nodePosition = null; if (row >= 0) { nodePosition = ((TreeItem)Tree.ItemAtRow (row)).Position; } return nodePosition != null; } /* protected override void OnDragOverCheck (NSDraggingInfo di, DragOverCheckEventArgs args) { base.OnDragOverCheck (di, args); var row = Tree.GetRow (new CGPoint (di.DraggingLocation.X, di.DraggingLocation.Y)); if (row != -1) { var item = Tree.ItemAtRow (row); Tree.SetDropItem (item, row); } } protected override void OnDragOver (NSDraggingInfo di, DragOverEventArgs args) { base.OnDragOver (di, args); var p = Tree.ConvertPointFromView (di.DraggingLocation, null); var row = Tree.GetRow (p); if (row != -1) { Tree.SetDropRowDropOperation (row, NSTableViewDropOperation.On); var item = Tree.ItemAtRow (row); Tree.SetDropItem (item, 0); } }*/ } class TreeItem: NSObject, ITablePosition { public TreePosition Position; public TreeItem () { } public TreeItem (IntPtr p): base (p) { } object ITablePosition.Position { get { return Position; } } public override NSObject Copy () { return new TreeItem { Position = this.Position }; } } class TreeSource: NSOutlineViewDataSource { ITreeDataSource source; // TODO: remove unused positions Dictionary<TreePosition,TreeItem> items = new Dictionary<TreePosition, TreeItem> (); public TreeSource (ITreeDataSource source) { this.source = source; source.NodeInserted += (sender, e) => { if (!items.ContainsKey (e.Node)) items.Add (e.Node, new TreeItem { Position = e.Node }); }; } public TreeItem GetItem (TreePosition pos) { if (pos == null) return null; TreeItem it; items.TryGetValue (pos, out it); return it; } public override bool AcceptDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, nint index) { return false; } public override string[] FilesDropped (NSOutlineView outlineView, NSUrl dropDestination, NSArray items) { throw new NotImplementedException (); } public override NSObject GetChild (NSOutlineView outlineView, nint childIndex, NSObject item) { var treeItem = (TreeItem) item; var pos = source.GetChild (treeItem != null ? treeItem.Position : null, (int) childIndex); if (pos != null) { TreeItem res; if (!items.TryGetValue (pos, out res)) items [pos] = res = new TreeItem () { Position = pos }; return res; } else return null; } public override nint GetChildrenCount (NSOutlineView outlineView, NSObject item) { var it = (TreeItem) item; return source.GetChildrenCount (it != null ? it.Position : null); } public override NSObject GetObjectValue (NSOutlineView outlineView, NSTableColumn forTableColumn, NSObject byItem) { return byItem; } public override void SetObjectValue (NSOutlineView outlineView, NSObject theObject, NSTableColumn tableColumn, NSObject item) { } public override bool ItemExpandable (NSOutlineView outlineView, NSObject item) { return GetChildrenCount (outlineView, item) > 0; } public override NSObject ItemForPersistentObject (NSOutlineView outlineView, NSObject theObject) { return null; } public override bool OutlineViewwriteItemstoPasteboard (NSOutlineView outlineView, NSArray items, NSPasteboard pboard) { return false; } public override NSObject PersistentObjectForItem (NSOutlineView outlineView, NSObject item) { return null; } public override void SortDescriptorsChanged (NSOutlineView outlineView, NSSortDescriptor[] oldDescriptors) { } public override NSDragOperation ValidateDrop (NSOutlineView outlineView, NSDraggingInfo info, NSObject item, nint index) { return NSDragOperation.None; } protected override void Dispose (bool disposing) { base.Dispose (disposing); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ActionBlock.cs // // // A target block that executes an action for each message. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary>Provides a dataflow block that invokes a provided <see cref="System.Action{T}"/> delegate for every data element received.</summary> /// <typeparam name="TInput">Specifies the type of data operated on by this <see cref="ActionBlock{T}"/>.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(ActionBlock<>.DebugView))] public sealed class ActionBlock<TInput> : ITargetBlock<TInput>, IDebuggerDisplay { /// <summary>The core implementation of this message block when in default mode.</summary> private readonly TargetCore<TInput> _defaultTarget; /// <summary>The core implementation of this message block when in SPSC mode.</summary> private readonly SpscTargetCore<TInput> _spscTarget; /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Action{T}"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Action<TInput> action) : this((Delegate)action, ExecutionDataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Action{T}"/> and <see cref="ExecutionDataflowBlockOptions"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="ActionBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Action<TInput> action, ExecutionDataflowBlockOptions dataflowBlockOptions) : this((Delegate)action, dataflowBlockOptions) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Func{T,Task}"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Func<TInput, Task> action) : this((Delegate)action, ExecutionDataflowBlockOptions.Default) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified <see cref="System.Func{T,Task}"/> and <see cref="ExecutionDataflowBlockOptions"/>.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="ActionBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public ActionBlock(Func<TInput, Task> action, ExecutionDataflowBlockOptions dataflowBlockOptions) : this((Delegate)action, dataflowBlockOptions) { } /// <summary>Initializes the <see cref="ActionBlock{T}"/> with the specified delegate and options.</summary> /// <param name="action">The action to invoke with each data element received.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="ActionBlock{T}"/>.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="action"/> is null (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> private ActionBlock(Delegate action, ExecutionDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (action == null) throw new ArgumentNullException("action"); if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions"); Contract.Ensures((_spscTarget != null) ^ (_defaultTarget != null), "One and only one of the two targets must be non-null after construction"); Contract.EndContractBlock(); // Ensure we have options that can't be changed by the caller dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Based on the mode, initialize the target. If the user specifies SingleProducerConstrained, // we'll try to employ an optimized mode under a limited set of circumstances. var syncAction = action as Action<TInput>; if (syncAction != null && dataflowBlockOptions.SingleProducerConstrained && dataflowBlockOptions.MaxDegreeOfParallelism == 1 && !dataflowBlockOptions.CancellationToken.CanBeCanceled && dataflowBlockOptions.BoundedCapacity == DataflowBlockOptions.Unbounded) { // Initialize the SPSC fast target to handle the bulk of the processing. // The SpscTargetCore is only supported when BoundedCapacity, CancellationToken, // and MaxDOP are all their default values. It's also only supported for sync // delegates and not for async delegates. _spscTarget = new SpscTargetCore<TInput>(this, syncAction, dataflowBlockOptions); } else { // Initialize the TargetCore which handles the bulk of the processing. // The default target core can handle all options and delegate flavors. if (syncAction != null) // sync { _defaultTarget = new TargetCore<TInput>(this, messageWithId => ProcessMessage(syncAction, messageWithId), null, dataflowBlockOptions, TargetCoreOptions.RepresentsBlockCompletion); } else // async { var asyncAction = action as Func<TInput, Task>; Debug.Assert(asyncAction != null, "action is of incorrect delegate type"); _defaultTarget = new TargetCore<TInput>(this, messageWithId => ProcessMessageWithTask(asyncAction, messageWithId), null, dataflowBlockOptions, TargetCoreOptions.RepresentsBlockCompletion | TargetCoreOptions.UsesAsyncCompletion); } // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, Completion, state => ((TargetCore<TInput>)state).Complete(exception: null, dropPendingMessages: true), _defaultTarget); } #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Processes the message with a user-provided action.</summary> /// <param name="action">The action to use to process the message.</param> /// <param name="messageWithId">The message to be processed.</param> private void ProcessMessage(Action<TInput> action, KeyValuePair<TInput, long> messageWithId) { try { action(messageWithId.Key); } catch (Exception exc) { // If this exception represents cancellation, swallow it rather than shutting down the block. if (!Common.IsCooperativeCancellation(exc)) throw; } finally { // We're done synchronously processing an element, so reduce the bounding count // that was incrementing when this element was enqueued. if (_defaultTarget.IsBounded) _defaultTarget.ChangeBoundingCount(-1); } } /// <summary>Processes the message with a user-provided action that returns a task.</summary> /// <param name="action">The action to use to process the message.</param> /// <param name="messageWithId">The message to be processed.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ProcessMessageWithTask(Func<TInput, Task> action, KeyValuePair<TInput, long> messageWithId) { Contract.Requires(action != null, "action needed for processing"); // Run the action to get the task that represents the operation's completion Task task = null; Exception caughtException = null; try { task = action(messageWithId.Key); } catch (Exception exc) { caughtException = exc; } // If no task is available, we're done. if (task == null) { // If we didn't get a task because an exception occurred, // store it (if the exception was cancellation, just ignore it). if (caughtException != null && !Common.IsCooperativeCancellation(caughtException)) { Common.StoreDataflowMessageValueIntoExceptionData(caughtException, messageWithId.Key); _defaultTarget.Complete(caughtException, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false); } // Signal that we're done this async operation. _defaultTarget.SignalOneAsyncMessageCompleted(boundingCountChange: -1); return; } else if (task.IsCompleted) { AsyncCompleteProcessMessageWithTask(task); } else { // Otherwise, join with the asynchronous operation when it completes. task.ContinueWith((completed, state) => { ((ActionBlock<TInput>)state).AsyncCompleteProcessMessageWithTask(completed); }, this, CancellationToken.None, Common.GetContinuationOptions(TaskContinuationOptions.ExecuteSynchronously), TaskScheduler.Default); } } /// <summary>Completes the processing of an asynchronous message.</summary> /// <param name="completed">The completed task.</param> private void AsyncCompleteProcessMessageWithTask(Task completed) { Contract.Requires(completed != null, "Need completed task for processing"); Contract.Requires(completed.IsCompleted, "The task to be processed must be completed by now."); // If the task faulted, store its errors. We must add the exception before declining // and signaling completion, as the exception is part of the operation, and the completion conditions // depend on this. if (completed.IsFaulted) { _defaultTarget.Complete(completed.Exception, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: true); } // Regardless of faults, note that we're done processing. There are // no outputs to keep track of for action block, so we always decrement // the bounding count here (the callee will handle checking whether // we're actually in a bounded mode). _defaultTarget.SignalOneAsyncMessageCompleted(boundingCountChange: -1); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { if (_defaultTarget != null) { _defaultTarget.Complete(exception: null, dropPendingMessages: false); } else { _spscTarget.Complete(exception: null); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Contract.EndContractBlock(); if (_defaultTarget != null) { _defaultTarget.Complete(exception, dropPendingMessages: true); } else { _spscTarget.Complete(exception); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _defaultTarget != null ? _defaultTarget.Completion : _spscTarget.Completion; } } /// <summary>Posts an item to the <see cref="T:System.Threading.Tasks.Dataflow.ITargetBlock`1"/>.</summary> /// <param name="item">The item being offered to the target.</param> /// <returns>true if the item was accepted by the target block; otherwise, false.</returns> /// <remarks> /// This method will return once the target block has decided to accept or decline the item, /// but unless otherwise dictated by special semantics of the target block, it does not wait /// for the item to actually be processed (for example, <see cref="T:System.Threading.Tasks.Dataflow.ActionBlock`1"/> /// will return from Post as soon as it has stored the posted item into its input queue). From the perspective /// of the block's processing, Post is asynchronous. For target blocks that support postponing offered messages, /// or for blocks that may do more processing in their Post implementation, consider using /// <see cref="T:System.Threading.Tasks.Dataflow.DataflowBlock.SendAsync">SendAsync</see>, /// which will return immediately and will enable the target to postpone the posted message and later consume it /// after SendAsync returns. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Post(TInput item) { // Even though this method is available with the exact same functionality as an extension method // on ITargetBlock, using that extension method goes through an interface call on ITargetBlock, // which for very high-throughput scenarios shows up as noticeable overhead on certain architectures. // We can eliminate that call for direct ActionBlock usage by providing the same method as an instance method. return _defaultTarget != null ? _defaultTarget.OfferMessage(Common.SingleMessageHeader, item, null, false) == DataflowMessageStatus.Accepted : _spscTarget.Post(item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> DataflowMessageStatus ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, Boolean consumeToAccept) { return _defaultTarget != null ? _defaultTarget.OfferMessage(messageHeader, messageValue, source, consumeToAccept) : _spscTarget.OfferMessage(messageHeader, messageValue, source, consumeToAccept); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="InputCount"]/*' /> public int InputCount { get { return _defaultTarget != null ? _defaultTarget.InputCount : _spscTarget.InputCount; } } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger.</summary> private int InputCountForDebugger { get { return _defaultTarget != null ? _defaultTarget.GetDebuggingInformation().InputCount : _spscTarget.InputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _defaultTarget != null ? _defaultTarget.DataflowBlockOptions : _spscTarget.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, InputCount={1}", Common.GetNameForDebugger(this, _defaultTarget != null ? _defaultTarget.DataflowBlockOptions : _spscTarget.DataflowBlockOptions), InputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Call.</summary> private sealed class DebugView { /// <summary>The action block being viewed.</summary> private readonly ActionBlock<TInput> _actionBlock; /// <summary>The action block's default target being viewed.</summary> private readonly TargetCore<TInput>.DebuggingInformation _defaultDebugInfo; /// <summary>The action block's SPSC target being viewed.</summary> private readonly SpscTargetCore<TInput>.DebuggingInformation _spscDebugInfo; /// <summary>Initializes the debug view.</summary> /// <param name="actionBlock">The target being debugged.</param> public DebugView(ActionBlock<TInput> actionBlock) { Contract.Requires(actionBlock != null, "Need a block with which to construct the debug view."); _actionBlock = actionBlock; if (_actionBlock._defaultTarget != null) { _defaultDebugInfo = actionBlock._defaultTarget.GetDebuggingInformation(); } else { _spscDebugInfo = actionBlock._spscTarget.GetDebuggingInformation(); } } /// <summary>Gets the messages waiting to be processed.</summary> public IEnumerable<TInput> InputQueue { get { return _defaultDebugInfo != null ? _defaultDebugInfo.InputQueue : _spscDebugInfo.InputQueue; } } /// <summary>Gets any postponed messages.</summary> public QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages { get { return _defaultDebugInfo != null ? _defaultDebugInfo.PostponedMessages : null; } } /// <summary>Gets the number of outstanding input operations.</summary> public Int32 CurrentDegreeOfParallelism { get { return _defaultDebugInfo != null ? _defaultDebugInfo.CurrentDegreeOfParallelism : _spscDebugInfo.CurrentDegreeOfParallelism; } } /// <summary>Gets the ExecutionDataflowBlockOptions used to configure this block.</summary> public ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _defaultDebugInfo != null ? _defaultDebugInfo.DataflowBlockOptions : _spscDebugInfo.DataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _defaultDebugInfo != null ? _defaultDebugInfo.IsDecliningPermanently : _spscDebugInfo.IsDecliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _defaultDebugInfo != null ? _defaultDebugInfo.IsCompleted : _spscDebugInfo.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_actionBlock); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Core; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders { /// <summary> /// An <see cref="IModelBinder"/> which binds models from the request body using an <see cref="IInputFormatter"/> /// when a model has the binding source <see cref="BindingSource.Body"/>. /// </summary> public class BodyModelBinder : IModelBinder { private readonly IList<IInputFormatter> _formatters; private readonly Func<Stream, Encoding, TextReader> _readerFactory; private readonly ILogger _logger; private readonly MvcOptions? _options; /// <summary> /// Creates a new <see cref="BodyModelBinder"/>. /// </summary> /// <param name="formatters">The list of <see cref="IInputFormatter"/>.</param> /// <param name="readerFactory"> /// The <see cref="IHttpRequestStreamReaderFactory"/>, used to create <see cref="System.IO.TextReader"/> /// instances for reading the request body. /// </param> public BodyModelBinder(IList<IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory) : this(formatters, readerFactory, loggerFactory: null) { } /// <summary> /// Creates a new <see cref="BodyModelBinder"/>. /// </summary> /// <param name="formatters">The list of <see cref="IInputFormatter"/>.</param> /// <param name="readerFactory"> /// The <see cref="IHttpRequestStreamReaderFactory"/>, used to create <see cref="System.IO.TextReader"/> /// instances for reading the request body. /// </param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> public BodyModelBinder( IList<IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory? loggerFactory) : this(formatters, readerFactory, loggerFactory, options: null) { } /// <summary> /// Creates a new <see cref="BodyModelBinder"/>. /// </summary> /// <param name="formatters">The list of <see cref="IInputFormatter"/>.</param> /// <param name="readerFactory"> /// The <see cref="IHttpRequestStreamReaderFactory"/>, used to create <see cref="System.IO.TextReader"/> /// instances for reading the request body. /// </param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <param name="options">The <see cref="MvcOptions"/>.</param> public BodyModelBinder( IList<IInputFormatter> formatters, IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory? loggerFactory, MvcOptions? options) { if (formatters == null) { throw new ArgumentNullException(nameof(formatters)); } if (readerFactory == null) { throw new ArgumentNullException(nameof(readerFactory)); } _formatters = formatters; _readerFactory = readerFactory.CreateReader; _logger = loggerFactory?.CreateLogger<BodyModelBinder>() ?? NullLogger<BodyModelBinder>.Instance; _options = options; } internal bool AllowEmptyBody { get; set; } /// <inheritdoc /> public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } _logger.AttemptingToBindModel(bindingContext); // Special logic for body, treat the model name as string.Empty for the top level // object, but allow an override via BinderModelName. The purpose of this is to try // and be similar to the behavior for POCOs bound via traditional model binding. string modelBindingKey; if (bindingContext.IsTopLevelObject) { modelBindingKey = bindingContext.BinderModelName ?? string.Empty; } else { modelBindingKey = bindingContext.ModelName; } var httpContext = bindingContext.HttpContext; var formatterContext = new InputFormatterContext( httpContext, modelBindingKey, bindingContext.ModelState, bindingContext.ModelMetadata, _readerFactory, AllowEmptyBody); var formatter = (IInputFormatter?)null; for (var i = 0; i < _formatters.Count; i++) { if (_formatters[i].CanRead(formatterContext)) { formatter = _formatters[i]; _logger.InputFormatterSelected(formatter, formatterContext); break; } else { _logger.InputFormatterRejected(_formatters[i], formatterContext); } } if (formatter == null) { _logger.NoInputFormatterSelected(formatterContext); var message = Resources.FormatUnsupportedContentType(httpContext.Request.ContentType); var exception = new UnsupportedContentTypeException(message); bindingContext.ModelState.AddModelError(modelBindingKey, exception, bindingContext.ModelMetadata); _logger.DoneAttemptingToBindModel(bindingContext); return; } try { var result = await formatter.ReadAsync(formatterContext); if (result.HasError) { // Formatter encountered an error. Do not use the model it returned. _logger.DoneAttemptingToBindModel(bindingContext); return; } if (result.IsModelSet) { var model = result.Model; bindingContext.Result = ModelBindingResult.Success(model); } else { // If the input formatter gives a "no value" result, that's always a model state error, // because BodyModelBinder implicitly regards input as being required for model binding. // If instead the input formatter wants to treat the input as optional, it must do so by // returning InputFormatterResult.Success(defaultForModelType), because input formatters // are responsible for choosing a default value for the model type. var message = bindingContext .ModelMetadata .ModelBindingMessageProvider .MissingRequestBodyRequiredValueAccessor(); bindingContext.ModelState.AddModelError(modelBindingKey, message); } } catch (Exception exception) when (exception is InputFormatterException || ShouldHandleException(formatter)) { bindingContext.ModelState.AddModelError(modelBindingKey, exception, bindingContext.ModelMetadata); } _logger.DoneAttemptingToBindModel(bindingContext); } private bool ShouldHandleException(IInputFormatter formatter) { // Any explicit policy on the formatters overrides the default. var policy = (formatter as IInputFormatterExceptionPolicy)?.ExceptionPolicy ?? InputFormatterExceptionPolicy.MalformedInputExceptions; return policy == InputFormatterExceptionPolicy.AllExceptions; } } }
using System; namespace Lucene.Net.Util.JunitCompat { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using After = org.junit.After; using AfterClass = org.junit.AfterClass; using Assert = org.junit.Assert; using Before = org.junit.Before; using BeforeClass = org.junit.BeforeClass; using Rule = org.junit.Rule; using Test = org.junit.Test; using TestRule = org.junit.rules.TestRule; using Description = org.junit.runner.Description; using JUnitCore = org.junit.runner.JUnitCore; using Statement = org.junit.runners.model.Statement; /// <summary> /// Test reproduce message is right. /// </summary> public class TestReproduceMessage : WithNestedTests { public static SorePoint @where; public static SoreType Type; public class Nested : AbstractNestedTest { //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @BeforeClass public static void beforeClass() public static void BeforeClass() { if (RunningNested) { TriggerOn(SorePoint.BEFORE_CLASS); } } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Rule public org.junit.rules.TestRule rule = new TestRuleAnonymousInnerClassHelper(); public TestRule rule = new TestRuleAnonymousInnerClassHelper(); private class TestRuleAnonymousInnerClassHelper : TestRule { public TestRuleAnonymousInnerClassHelper() { } public override Statement Apply(Statement @base, Description description) { return new StatementAnonymousInnerClassHelper(this, @base); } private class StatementAnonymousInnerClassHelper : Statement { private readonly TestRuleAnonymousInnerClassHelper OuterInstance; private Statement @base; public StatementAnonymousInnerClassHelper(TestRuleAnonymousInnerClassHelper outerInstance, Statement @base) { this.outerInstance = outerInstance; this.@base = @base; } public override void Evaluate() { TriggerOn(SorePoint.RULE); @base.evaluate(); } } } /// <summary> /// Class initializer block/ default constructor. </summary> public Nested() { TriggerOn(SorePoint.INITIALIZER); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void before() public virtual void Before() { TriggerOn(SorePoint.BEFORE); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void test() public virtual void Test() { TriggerOn(SorePoint.TEST); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @After public void after() public virtual void After() { TriggerOn(SorePoint.AFTER); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @AfterClass public static void afterClass() public static void AfterClass() { if (RunningNested) { TriggerOn(SorePoint.AFTER_CLASS); } } internal static void TriggerOn(SorePoint pt) { if (pt == @where) { switch (Type) { case Lucene.Net.Util.junitcompat.SoreType.ASSUMPTION: LuceneTestCase.assumeTrue(pt.ToString(), false); throw new Exception("unreachable"); case Lucene.Net.Util.junitcompat.SoreType.ERROR: throw new Exception(pt.ToString()); case Lucene.Net.Util.junitcompat.SoreType.FAILURE: Assert.IsTrue(pt.ToString(), false); throw new Exception("unreachable"); } } } } /* * ASSUMPTIONS. */ public TestReproduceMessage() : base(true) { } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeBeforeClass() throws Exception public virtual void TestAssumeBeforeClass() { Type = SoreType.ASSUMPTION; @where = SorePoint.BEFORE_CLASS; Assert.IsTrue(RunAndReturnSyserr().Length == 0); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeInitializer() throws Exception public virtual void TestAssumeInitializer() { Type = SoreType.ASSUMPTION; @where = SorePoint.INITIALIZER; Assert.IsTrue(RunAndReturnSyserr().Length == 0); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeRule() throws Exception public virtual void TestAssumeRule() { Type = SoreType.ASSUMPTION; @where = SorePoint.RULE; Assert.AreEqual("", RunAndReturnSyserr()); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeBefore() throws Exception public virtual void TestAssumeBefore() { Type = SoreType.ASSUMPTION; @where = SorePoint.BEFORE; Assert.IsTrue(RunAndReturnSyserr().Length == 0); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeTest() throws Exception public virtual void TestAssumeTest() { Type = SoreType.ASSUMPTION; @where = SorePoint.TEST; Assert.IsTrue(RunAndReturnSyserr().Length == 0); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeAfter() throws Exception public virtual void TestAssumeAfter() { Type = SoreType.ASSUMPTION; @where = SorePoint.AFTER; Assert.IsTrue(RunAndReturnSyserr().Length == 0); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAssumeAfterClass() throws Exception public virtual void TestAssumeAfterClass() { Type = SoreType.ASSUMPTION; @where = SorePoint.AFTER_CLASS; Assert.IsTrue(RunAndReturnSyserr().Length == 0); } /* * FAILURES */ //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureBeforeClass() throws Exception public virtual void TestFailureBeforeClass() { Type = SoreType.FAILURE; @where = SorePoint.BEFORE_CLASS; Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:")); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureInitializer() throws Exception public virtual void TestFailureInitializer() { Type = SoreType.FAILURE; @where = SorePoint.INITIALIZER; Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:")); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureRule() throws Exception public virtual void TestFailureRule() { Type = SoreType.FAILURE; @where = SorePoint.RULE; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureBefore() throws Exception public virtual void TestFailureBefore() { Type = SoreType.FAILURE; @where = SorePoint.BEFORE; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureTest() throws Exception public virtual void TestFailureTest() { Type = SoreType.FAILURE; @where = SorePoint.TEST; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureAfter() throws Exception public virtual void TestFailureAfter() { Type = SoreType.FAILURE; @where = SorePoint.AFTER; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testFailureAfterClass() throws Exception public virtual void TestFailureAfterClass() { Type = SoreType.FAILURE; @where = SorePoint.AFTER_CLASS; Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:")); } /* * ERRORS */ //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorBeforeClass() throws Exception public virtual void TestErrorBeforeClass() { Type = SoreType.ERROR; @where = SorePoint.BEFORE_CLASS; Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:")); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorInitializer() throws Exception public virtual void TestErrorInitializer() { Type = SoreType.ERROR; @where = SorePoint.INITIALIZER; Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:")); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorRule() throws Exception public virtual void TestErrorRule() { Type = SoreType.ERROR; @where = SorePoint.RULE; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorBefore() throws Exception public virtual void TestErrorBefore() { Type = SoreType.ERROR; @where = SorePoint.BEFORE; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorTest() throws Exception public virtual void TestErrorTest() { Type = SoreType.ERROR; @where = SorePoint.TEST; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorAfter() throws Exception public virtual void TestErrorAfter() { Type = SoreType.ERROR; @where = SorePoint.AFTER; string syserr = RunAndReturnSyserr(); Assert.IsTrue(syserr.Contains("NOTE: reproduce with:")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtests.method=test")); Assert.IsTrue(Arrays.AsList(syserr.Split("\\s", true)).Contains("-Dtestcase=" + typeof(Nested).SimpleName)); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testErrorAfterClass() throws Exception public virtual void TestErrorAfterClass() { Type = SoreType.ERROR; @where = SorePoint.AFTER_CLASS; Assert.IsTrue(RunAndReturnSyserr().Contains("NOTE: reproduce with:")); } private string RunAndReturnSyserr() { JUnitCore.runClasses(typeof(Nested)); string err = SysErr; // super.prevSysErr.println("Type: " + type + ", point: " + where + " resulted in:\n" + err); // super.prevSysErr.println("---"); return err; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace RazorGenerator.Core { public class HostManager : IDisposable { private readonly string _baseDirectory; private readonly bool _loadExtensions; private readonly RazorRuntime _defaultRuntime; private readonly string _assemblyDirectory; private ComposablePartCatalog _catalog; public HostManager(string baseDirectory) : this(baseDirectory, loadExtensions: true, defaultRuntime: RazorRuntime.Version1, assemblyDirectory: GetAssesmblyDirectory()) { } public HostManager(string baseDirectory, bool loadExtensions, RazorRuntime defaultRuntime, string assemblyDirectory) { _loadExtensions = loadExtensions; _baseDirectory = baseDirectory; _defaultRuntime = defaultRuntime; _assemblyDirectory = assemblyDirectory; // Repurposing loadExtensions to mean unit-test scenarios. Don't bind to the AssemblyResolve in unit tests if (_loadExtensions) { AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; } } public IRazorHost CreateHost(string fullPath, string projectRelativePath, string vsNamespace) { CodeLanguageUtil langutil = CodeLanguageUtil.GetLanguageUtilFromFileName(fullPath); using (var codeDomProvider = langutil.GetCodeDomProvider()) { return CreateHost(fullPath, projectRelativePath, codeDomProvider, vsNamespace); } } public IRazorHost CreateHost(string fullPath, string projectRelativePath, CodeDomProvider codeDomProvider, string vsNamespace) { var directives = DirectivesParser.ParseDirectives(_baseDirectory, fullPath); directives["VsNamespace"] = vsNamespace; string guessedHost = null; RazorRuntime runtime = _defaultRuntime; GuessedHost value; if (TryGuessHost(_baseDirectory, projectRelativePath, out value)) { runtime = value.Runtime; guessedHost = value.Host; } string hostName; if (!directives.TryGetValue("Generator", out hostName)) { // Determine the host and runtime from the file \ project hostName = guessedHost; } string razorVersion; if (directives.TryGetValue("RazorVersion", out razorVersion)) { // If the directive explicitly specifies a host, use that. switch (razorVersion) { case "1": runtime = RazorRuntime.Version1; break; case "2": runtime = RazorRuntime.Version2; break; default: runtime = RazorRuntime.Version3; break; } } if (_catalog == null) { _catalog = InitCompositionCatalog(_baseDirectory, _loadExtensions, runtime); } using (var container = new CompositionContainer(_catalog)) { var codeTransformer = GetRazorCodeTransformer(container, projectRelativePath, hostName); var host = container.GetExport<IHostProvider>().Value; return host.GetRazorHost(projectRelativePath, fullPath, codeTransformer, codeDomProvider, directives); } } private IRazorCodeTransformer GetRazorCodeTransformer(CompositionContainer container, string projectRelativePath, string hostName) { IRazorCodeTransformer codeTransformer = null; try { codeTransformer = container.GetExportedValue<IRazorCodeTransformer>(hostName); } catch (Exception exception) { string availableHosts = String.Join(", ", GetAvailableHosts(container)); throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, RazorGeneratorResources.GeneratorFailureMessage, projectRelativePath, availableHosts), exception); } if (codeTransformer == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, RazorGeneratorResources.GeneratorError_UnknownGenerator, hostName)); } return codeTransformer; } private ComposablePartCatalog InitCompositionCatalog(string baseDirectory, bool loadExtensions, RazorRuntime runtime) { // Retrieve available hosts var hostsAssembly = GetAssembly(runtime); var catalog = new AggregateCatalog(new AssemblyCatalog(hostsAssembly)); if (loadExtensions) { // We assume that the baseDirectory points to the project root. Look for the RazorHosts directory under the project root AddCatalogIfHostsDirectoryExists(catalog, baseDirectory); // Look for the Razor Hosts directory up to two directories above the baseDirectory. Hopefully this should cover the solution root. var solutionDirectory = Path.Combine(baseDirectory, @"..\"); AddCatalogIfHostsDirectoryExists(catalog, solutionDirectory); solutionDirectory = Path.Combine(baseDirectory, @"..\..\"); AddCatalogIfHostsDirectoryExists(catalog, solutionDirectory); } return catalog; } private static IEnumerable<string> GetAvailableHosts(CompositionContainer container) { // We need for a way to figure out what the exporting type is. This could return arbitrary exports that are not ISingleFileGenerators return from part in container.Catalog.Parts from export in part.ExportDefinitions where !String.IsNullOrEmpty(export.ContractName) select export.ContractName; } private Assembly GetAssembly(RazorRuntime runtime) { int runtimeValue = (int)runtime; // TODO: Check if we can switch to using CodeBase instead of Location // Look for the assembly at vX\RazorGenerator.vX.dll. If not, assume it is at RazorGenerator.vX.dll string runtimeDirectory = Path.Combine(_assemblyDirectory, "v" + runtimeValue); string assemblyName = "RazorGenerator.Core.v" + runtimeValue + ".dll"; string runtimeDirPath = Path.Combine(runtimeDirectory, assemblyName); if (File.Exists(runtimeDirPath)) { Assembly assembly = Assembly.LoadFrom(runtimeDirPath); return assembly; } else { return Assembly.LoadFrom(Path.Combine(_assemblyDirectory, assemblyName)); } } internal static bool TryGuessHost(string projectRoot, string projectRelativePath, out GuessedHost host) { RazorRuntime runtime; bool isMvcProject = IsMvcProject(projectRoot, out runtime) ?? false; if (isMvcProject) { var mvcHelperRegex = new Regex(@"(^|\\)Views(\\.*)+Helpers?", RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase); if (mvcHelperRegex.IsMatch(projectRelativePath)) { host = new GuessedHost("MvcHelper", runtime); } host = new GuessedHost("MvcView", runtime); return true; } host = default(GuessedHost); return false; } private static bool? IsMvcProject(string projectRoot, out RazorRuntime razorRuntime) { razorRuntime = RazorRuntime.Version1; try { var projectFile = Directory.EnumerateFiles(projectRoot, "*.csproj").FirstOrDefault(); if (projectFile == null) { projectFile = Directory.EnumerateFiles(projectRoot, "*.vbproj").FirstOrDefault(); } if (projectFile != null) { var content = File.ReadAllText(projectFile); if ((content.IndexOf("System.Web.Mvc, Version=4", StringComparison.OrdinalIgnoreCase) != -1) || (content.IndexOf("System.Web.Razor, Version=2", StringComparison.OrdinalIgnoreCase) != -1) || (content.IndexOf("Microsoft.AspNet.Mvc.4", StringComparison.OrdinalIgnoreCase) != -1)) { // The project references Razor v2 razorRuntime = RazorRuntime.Version2; } else if ((content.IndexOf("System.Web.Mvc, Version=5", StringComparison.OrdinalIgnoreCase) != -1) || (content.IndexOf("System.Web.Razor, Version=3", StringComparison.OrdinalIgnoreCase) != -1) || (content.IndexOf("Microsoft.AspNet.Mvc.5", StringComparison.OrdinalIgnoreCase) != -1)) { // The project references Razor v3 razorRuntime = RazorRuntime.Version3; } return content.IndexOf("System.Web.Mvc", StringComparison.OrdinalIgnoreCase) != -1; } } catch { } return null; } private static void AddCatalogIfHostsDirectoryExists(AggregateCatalog catalog, string directory) { var extensionsDirectory = Path.GetFullPath(Path.Combine(directory, "RazorHosts")); if (Directory.Exists(extensionsDirectory)) { catalog.Catalogs.Add(new DirectoryCatalog(extensionsDirectory)); } } private Assembly OnAssemblyResolve(object sender, ResolveEventArgs eventArgs) { var nameToResolve = new AssemblyName(eventArgs.Name); string path = Path.Combine(_assemblyDirectory, "v" + nameToResolve.Version.Major, nameToResolve.Name) + ".dll"; if (File.Exists(path)) { return Assembly.LoadFrom(path); } return null; } /// <remarks> /// Attempts to locate where the RazorGenerator.Core assembly is being loaded from. This allows us to locate the v1 and v2 assemblies and the corresponding /// System.Web.* binaries /// Assembly.CodeBase points to the original location when the file is shadow copied, so we'll attempt to use that first. /// </remarks> private static string GetAssesmblyDirectory() { Assembly assembly = Assembly.GetExecutingAssembly(); Uri uri; if (Uri.TryCreate(assembly.CodeBase, UriKind.Absolute, out uri) && uri.IsFile) { return Path.GetDirectoryName(uri.LocalPath); } return Path.GetDirectoryName(assembly.Location); } public void Dispose() { if (_catalog != null) { _catalog.Dispose(); } if (_loadExtensions) { AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve; } } internal class GuessedHost { public GuessedHost(string host, RazorRuntime runtime) { Host = host; Runtime = runtime; } public string Host { get; private set; } public RazorRuntime Runtime { get; private set; } } } }
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * 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.Diagnostics; using Box2D.Common; using Box2D.Collision.Shapes; using Box2D.Collision; namespace Box2D.Dynamics.Contacts { public enum ContactType { b2CircleContact, b2PolygonAndCircleContact, b2PolygonContact, b2EdgeAndCircleContact, b2EdgeAndPolygonContact, b2ChainAndCircleContact, b2ChainAndPolygonContact } public struct b2ContactRegister { public ContactType contactType; public bool isPrimary; } /// <summary> /// A contact edge is used to connect bodies and contacts together /// in a contact graph where each body is a node and each contact /// is an edge. A contact edge belongs to a doubly linked list /// maintained in each attached body. Each contact has two contact /// nodes, one for each attached body. /// </summary> public class b2ContactEdge { public b2Body Other; //< provides quick access to the other body attached. public b2Contact Contact; //< the contact public bool hasPrev; public b2ContactEdge Prev; //< the previous contact edge in the body's contact list public bool hasNext; public b2ContactEdge Next; //< the next contact edge in the body's contact list } [Flags] public enum b2ContactFlags : uint { // Flags stored in m_flags // Used when crawling contact graph when forming islands. e_islandFlag = 0x0001, // Set when the shapes are touching. e_touchingFlag = 0x0002, // This contact can be disabled (by user) e_enabledFlag = 0x0004, // This contact needs filtering because a fixture filter was changed. e_filterFlag = 0x0008, // This bullet contact had a TOI event e_bulletHitFlag = 0x0010, // This contact has a valid TOI in m_toi e_toiFlag = 0x0020 } public class b2Contact : b2ReusedObject<b2Contact> { public b2ContactFlags Flags; // World pool and list pointers. public b2Contact Prev; public b2Contact Next; // Nodes for connecting bodies. public b2ContactEdge NodeA; public b2ContactEdge NodeB; public b2Fixture FixtureA; public b2Fixture FixtureB; internal int m_indexA; internal int m_indexB; internal b2Manifold m_manifold; public int m_toiCount; public float m_toi; public float Friction; public float Restitution; protected static b2ContactRegister[,] s_registers = new b2ContactRegister[(int)b2ShapeType.e_typeCount, (int)b2ShapeType.e_typeCount]; private ContactType _type; public b2Contact() { m_manifold = new b2Manifold(); NodeA = new b2ContactEdge(); NodeB = new b2ContactEdge(); } static b2Contact() { AddType(ContactType.b2CircleContact, b2ShapeType.e_circle, b2ShapeType.e_circle); AddType(ContactType.b2PolygonAndCircleContact, b2ShapeType.e_polygon, b2ShapeType.e_circle); AddType(ContactType.b2PolygonContact, b2ShapeType.e_polygon, b2ShapeType.e_polygon); AddType(ContactType.b2EdgeAndCircleContact, b2ShapeType.e_edge, b2ShapeType.e_circle); AddType(ContactType.b2EdgeAndPolygonContact, b2ShapeType.e_edge, b2ShapeType.e_polygon); AddType(ContactType.b2ChainAndCircleContact, b2ShapeType.e_chain, b2ShapeType.e_circle); AddType(ContactType.b2ChainAndPolygonContact, b2ShapeType.e_chain, b2ShapeType.e_polygon); } private static void AddType(ContactType createType, b2ShapeType type1, b2ShapeType type2) { Debug.Assert(0 <= type1 && type1 < b2ShapeType.e_typeCount); Debug.Assert(0 <= type2 && type2 < b2ShapeType.e_typeCount); s_registers[(int)type1, (int)type2].contactType = createType; s_registers[(int)type1, (int)type2].isPrimary = true; if (type1 != type2) { s_registers[(int)type2, (int)type1].contactType = createType; s_registers[(int)type2, (int)type1].isPrimary = false; } } /// Evaluate this contact with your own manifold and transforms. public void Evaluate(b2Manifold manifold, ref b2Transform xfA, ref b2Transform xfB) { switch (_type) { case ContactType.b2CircleContact: b2Collision.b2CollideCircles(manifold, (b2CircleShape) FixtureA.Shape, ref xfA, (b2CircleShape) FixtureB.Shape, ref xfB); break; case ContactType.b2PolygonAndCircleContact: b2Collision.b2CollidePolygonAndCircle(manifold, (b2PolygonShape) FixtureA.Shape, ref xfA, (b2CircleShape) FixtureB.Shape, ref xfB); break; case ContactType.b2PolygonContact: b2Collision.b2CollidePolygons(manifold, (b2PolygonShape) FixtureA.Shape, ref xfA, (b2PolygonShape) FixtureB.Shape, ref xfB); break; case ContactType.b2EdgeAndCircleContact: b2Collision.b2CollideEdgeAndCircle(manifold, (b2EdgeShape) FixtureA.Shape, ref xfA, (b2CircleShape) FixtureB.Shape, ref xfB); break; case ContactType.b2EdgeAndPolygonContact: b2Collision.b2CollideEdgeAndPolygon(manifold, (b2EdgeShape) FixtureA.Shape, ref xfA, (b2PolygonShape) FixtureB.Shape, ref xfB); break; case ContactType.b2ChainAndCircleContact: b2ChainShape chain = (b2ChainShape) FixtureA.Shape; b2EdgeShape edge; edge = chain.GetChildEdge(m_indexA); b2Collision.b2CollideEdgeAndCircle(manifold, edge, ref xfA, (b2CircleShape) FixtureB.Shape, ref xfB); break; case ContactType.b2ChainAndPolygonContact: chain = (b2ChainShape) FixtureA.Shape; edge = chain.GetChildEdge(m_indexA); b2Collision.b2CollideEdgeAndPolygon(manifold, edge, ref xfA, (b2PolygonShape) FixtureB.Shape, ref xfB); break; default: throw new ArgumentOutOfRangeException(); } } public static b2Contact Create(b2Fixture fixtureA, int indexA, b2Fixture fixtureB, int indexB) { b2ShapeType type1 = fixtureA.ShapeType; b2ShapeType type2 = fixtureB.ShapeType; Debug.Assert(0 <= type1 && type1 < b2ShapeType.e_typeCount); Debug.Assert(0 <= type2 && type2 < b2ShapeType.e_typeCount); var contact = Create(); //Type createFcn = s_registers[(int)type1, (int)type2].contactType; contact._type = s_registers[(int) type1, (int) type2].contactType; //if (createFcn != null) { if (s_registers[(int)type1, (int)type2].isPrimary) { //return ((b2Contact)Activator.CreateInstance(createFcn, new object[] { fixtureA, indexA, fixtureB, indexB })); contact.Init(fixtureA, indexA, fixtureB, indexB); } else { //return ((b2Contact)Activator.CreateInstance(createFcn, new object[] { fixtureB, indexB, fixtureA, indexA })); contact.Init(fixtureB, indexB, fixtureA, indexA); } } return contact; } public b2Contact(b2Fixture fA, int indexA, b2Fixture fB, int indexB) { Init(fA, indexA, fB, indexB); } protected void Init(b2Fixture fA, int indexA, b2Fixture fB, int indexB) { Flags = b2ContactFlags.e_enabledFlag; FixtureA = fA; FixtureB = fB; m_indexA = indexA; m_indexB = indexB; m_manifold.pointCount = 0; Prev = null; Next = null; NodeA.Contact = null; NodeA.hasPrev = false; NodeA.hasNext = false; NodeA.Other = null; NodeB.Contact = null; NodeB.hasPrev = false; NodeB.hasNext = false; NodeB.Other = null; m_toiCount = 0; Friction = b2Math.b2MixFriction(FixtureA.Friction, FixtureB.Friction); Restitution = b2Math.b2MixRestitution(FixtureA.Restitution, FixtureB.Restitution); } //Memory save private static b2Manifold oldManifold = new b2Manifold(); // Update the contact manifold and touching status. // Note: do not assume the fixture AABBs are overlapping or are valid. public virtual void Update(b2ContactListener listener) { oldManifold.CopyFrom(m_manifold); // Re-enable this contact. Flags |= b2ContactFlags.e_enabledFlag; bool touching = false; bool wasTouching = (Flags & b2ContactFlags.e_touchingFlag) == b2ContactFlags.e_touchingFlag; bool sensor = FixtureA.m_isSensor || FixtureB.m_isSensor; b2Body bodyA = FixtureA.Body; b2Body bodyB = FixtureB.Body; b2Transform xfA = bodyA.Transform; b2Transform xfB = bodyB.Transform; // Is this contact a sensor? if (sensor) { b2Shape shapeA = FixtureA.Shape; b2Shape shapeB = FixtureB.Shape; touching = b2Collision.b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, ref xfA, ref xfB); // Sensors don't generate manifolds. m_manifold.pointCount = 0; } else { Evaluate(m_manifold, ref xfA, ref xfB); touching = m_manifold.pointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. for (int i = 0; i < m_manifold.pointCount; ++i) { b2ManifoldPoint mp2 = m_manifold.points[i]; mp2.normalImpulse = 0.0f; mp2.tangentImpulse = 0.0f; b2ContactFeature id2 = mp2.id; for (int j = 0; j < oldManifold.pointCount; ++j) { b2ManifoldPoint mp1 = oldManifold.points[j]; if (mp1.id.key == id2.key) { mp2.normalImpulse = mp1.normalImpulse; mp2.tangentImpulse = mp1.tangentImpulse; break; } } } if (touching != wasTouching) { bodyA.SetAwake(true); bodyB.SetAwake(true); } } if (touching) { Flags |= b2ContactFlags.e_touchingFlag; } else { Flags &= ~b2ContactFlags.e_touchingFlag; } if (wasTouching == false && touching == true && listener != null) { listener.BeginContact(this); } if (wasTouching == true && touching == false && listener != null) { listener.EndContact(this); } if (sensor == false && touching && listener != null) { listener.PreSolve(this, oldManifold); } } public virtual b2Manifold GetManifold() { return m_manifold; } /* public virtual void SetManifold(ref b2Manifold m) { m_manifold = m; m_manifold.CopyPointsFrom(ref m); } */ public virtual void GetWorldManifold(ref b2WorldManifold worldManifold) { b2Body bodyA = FixtureA.Body; b2Body bodyB = FixtureB.Body; b2Shape shapeA = FixtureA.Shape; b2Shape shapeB = FixtureB.Shape; worldManifold.Initialize(m_manifold, ref bodyA.Transform, shapeA.Radius, ref bodyB.Transform, shapeB.Radius); } public virtual void SetEnabled(bool flag) { if (flag) { Flags |= b2ContactFlags.e_enabledFlag; } else { Flags &= ~b2ContactFlags.e_enabledFlag; } } public virtual bool IsEnabled() { return (Flags & b2ContactFlags.e_enabledFlag) != 0; } public virtual bool IsTouching() { return (Flags & b2ContactFlags.e_touchingFlag) != 0; } public virtual b2Contact GetNext() { return Next; } public virtual b2Contact GetPrev() { return Prev; } public virtual b2Fixture GetFixtureA() { return FixtureA; } public virtual b2Fixture GetFixtureB() { return FixtureB; } public virtual int GetChildIndexA() { return m_indexA; } public virtual int GetChildIndexB() { return m_indexB; } public virtual void FlagForFiltering() { Flags |= b2ContactFlags.e_filterFlag; } public virtual void SetFriction(float friction) { Friction = friction; } public virtual float GetFriction() { return Friction; } public virtual void ResetFriction() { Friction = b2MixFriction(FixtureA.Friction, FixtureB.Friction); } public virtual void SetRestitution(float restitution) { Restitution = restitution; } public virtual float GetRestitution() { return Restitution; } public virtual void ResetRestitution() { Restitution = b2MixRestitution(FixtureA.Restitution, FixtureB.Restitution); } protected virtual float b2MixFriction(float friction1, float friction2) { return (float)Math.Sqrt(friction1 * friction2); } /// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. /// For example, a superball bounces on anything. protected float b2MixRestitution(float restitution1, float restitution2) { return restitution1 > restitution2 ? restitution1 : restitution2; } } }
// // Mono.System.Xml.Schema.XmlSchemaComplexContent.cs // // Author: // Dwivedi, Ajay kumar [email protected] // Atsushi Enomoto [email protected] // // // 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 Mono.System.Xml.Serialization; using Mono.System.Xml; namespace Mono.System.Xml.Schema { /// <summary> /// Summary description for XmlSchemaComplexContent. /// </summary> public class XmlSchemaComplexContent : XmlSchemaContentModel { private XmlSchemaContent content; private bool isMixed; const string xmlname = "complexContent"; public XmlSchemaComplexContent() {} [Mono.System.Xml.Serialization.XmlAttribute("mixed")] public bool IsMixed { get{ return isMixed; } set{ isMixed = value; } } [XmlElement("restriction",typeof(XmlSchemaComplexContentRestriction))] [XmlElement("extension",typeof(XmlSchemaComplexContentExtension))] public override XmlSchemaContent Content { get{ return content; } set{ content = value; } } internal override void SetParent (XmlSchemaObject parent) { base.SetParent (parent); if (Content != null) Content.SetParent (this); } /// <remarks> /// 1. Content must be present /// </remarks> internal override int Compile(ValidationEventHandler h, XmlSchema schema) { // If this is already compiled this time, simply skip. if (CompilationId == schema.CompilationId) return 0; if (isRedefinedComponent) { if (Annotation != null) Annotation.isRedefinedComponent = true; if (Content != null) Content.isRedefinedComponent = true; } if(Content == null) { error(h, "Content must be present in a complexContent"); } else { if(Content is XmlSchemaComplexContentRestriction) { XmlSchemaComplexContentRestriction xscr = (XmlSchemaComplexContentRestriction) Content; errorCount += xscr.Compile(h, schema); } else if(Content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension xsce = (XmlSchemaComplexContentExtension) Content; errorCount += xsce.Compile(h, schema); } else error(h,"complexContent can't have any value other than restriction or extention"); } XmlSchemaUtil.CompileID(Id,this, schema.IDCollection,h); this.CompilationId = schema.CompilationId; return errorCount; } internal override int Validate(ValidationEventHandler h, XmlSchema schema) { if (IsValidated (schema.ValidationId)) return errorCount; errorCount += Content.Validate (h, schema); ValidationId = schema.ValidationId; return errorCount; } //<complexContent // id = ID // mixed = boolean // {any attributes with non-schema namespace . . .}> // Content: (annotation?, (restriction | extension)) //</complexContent> internal static XmlSchemaComplexContent Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaComplexContent complex = new XmlSchemaComplexContent(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h,"Should not happen :1: XmlSchemaComplexContent.Read, name="+reader.Name,null); reader.Skip(); return null; } complex.LineNumber = reader.LineNumber; complex.LinePosition = reader.LinePosition; complex.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "id") { complex.Id = reader.Value; } else if(reader.Name == "mixed") { Exception innerex; complex.isMixed = XmlSchemaUtil.ReadBoolAttribute(reader,out innerex); if(innerex != null) error(h,reader.Value + " is an invalid value for mixed",innerex); } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for complexContent",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,complex); } } reader.MoveToElement(); if(reader.IsEmptyElement) return complex; //Content: (annotation?, (restriction | extension)) int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaComplexContent.Read, name="+reader.Name,null); break; } if(level <= 1 && reader.LocalName == "annotation") { level = 2; //Only one annotation XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h); if(annotation != null) complex.Annotation = annotation; continue; } if(level <=2) { if(reader.LocalName == "restriction") { level = 3; XmlSchemaComplexContentRestriction restriction = XmlSchemaComplexContentRestriction.Read(reader,h); if(restriction != null) complex.content = restriction; continue; } if(reader.LocalName == "extension") { level = 3; XmlSchemaComplexContentExtension extension = XmlSchemaComplexContentExtension.Read(reader,h); if(extension != null) complex.content = extension; continue; } } reader.RaiseInvalidElementError(); } return complex; } } }
using System; using System.Collections; using System.Data; using System.Data.OleDb; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using System.Collections.Specialized; namespace PCSComUtils.Framework.ReportFrame.DS { public class sys_ReportHistoryDS { public sys_ReportHistoryDS() { } private const string THIS = "PCSComUtils.Framework.ReportFrame.DS.DS.sys_ReportHistoryDS"; //************************************************************************** /// <Description> /// This method uses to add data to sys_ReportHistory /// </Description> /// <Inputs> /// sys_ReportHistoryVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { sys_ReportHistoryVO objObject = (sys_ReportHistoryVO) pobjObjectVO; string strSql = String.Empty; strSql = "INSERT INTO " + sys_ReportHistoryTable.TABLE_NAME + "(" + sys_ReportHistoryTable.USERID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + ")" + " VALUES(?,?,?,?)"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.USERID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.USERID_FLD].Value = objObject.UserID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.EXECDATETIME_FLD, OleDbType.Date)); ocmdPCS.Parameters[sys_ReportHistoryTable.EXECDATETIME_FLD].Value = objObject.ExecDateTime; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.REPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.REPORTID_FLD].Value = objObject.ReportID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.TABLENAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.TABLENAME_FLD].Value = objObject.TableName; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportHistory /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { /// UNDONE: Thachnn says: I think this function is useless const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.HISTORYID_FLD + "=" + pintID.ToString().Trim(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportHistory /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 03-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public void DeleteByReportID(string pstrID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.REPORTID_FLD + "= ? ";// + pstrID + "'"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.REPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.REPORTID_FLD].Value = pstrID; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_ReportHistory /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// sys_ReportHistoryVO /// </Outputs> /// <Returns> /// sys_ReportHistoryVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportHistoryTable.HISTORYID_FLD + "," + sys_ReportHistoryTable.USERID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.HISTORYID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); sys_ReportHistoryVO objObject = new sys_ReportHistoryVO(); while (odrPCS.Read()) { objObject.HistoryID = int.Parse(odrPCS[sys_ReportHistoryTable.HISTORYID_FLD].ToString().Trim()); objObject.UserID = odrPCS[sys_ReportHistoryTable.USERID_FLD].ToString().Trim(); objObject.ExecDateTime = DateTime.Parse(odrPCS[sys_ReportHistoryTable.EXECDATETIME_FLD].ToString().Trim()); objObject.ReportID = odrPCS[sys_ReportHistoryTable.REPORTID_FLD].ToString().Trim(); objObject.TableName = odrPCS[sys_ReportHistoryTable.TABLENAME_FLD].ToString().Trim(); } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to sys_ReportHistory /// </Description> /// <Inputs> /// sys_ReportHistoryVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; sys_ReportHistoryVO objObject = (sys_ReportHistoryVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE sys_ReportHistory SET " + sys_ReportHistoryTable.USERID_FLD + "= ?" + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "= ?" + "," + sys_ReportHistoryTable.REPORTID_FLD + "= ?" + "," + sys_ReportHistoryTable.TABLENAME_FLD + "= ?" + " WHERE " + sys_ReportHistoryTable.HISTORYID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.USERID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.USERID_FLD].Value = objObject.UserID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.EXECDATETIME_FLD, OleDbType.Date)); ocmdPCS.Parameters[sys_ReportHistoryTable.EXECDATETIME_FLD].Value = objObject.ExecDateTime; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.REPORTID_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.REPORTID_FLD].Value = objObject.ReportID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.TABLENAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[sys_ReportHistoryTable.TABLENAME_FLD].Value = objObject.TableName; ocmdPCS.Parameters.Add(new OleDbParameter(sys_ReportHistoryTable.HISTORYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_ReportHistoryTable.HISTORYID_FLD].Value = objObject.HistoryID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_ReportHistory /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportHistoryTable.HISTORYID_FLD + "," + sys_ReportHistoryTable.USERID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, sys_ReportHistoryTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Monday, December 27, 2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + sys_ReportHistoryTable.HISTORYID_FLD + "," + sys_ReportHistoryTable.USERID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, sys_ReportHistoryTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_ReportHistory of specified report /// </Description> /// <Inputs> /// ReportID /// </Inputs> /// <Outputs> /// ArrayList /// </Outputs> /// <Returns> /// ArrayList /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 03-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList ListByReport(string pstrReportID) { const string METHOD_NAME = THIS + ".ListByReport()"; ArrayList arrObjects = new ArrayList(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; OleDbDataReader odrPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + sys_ReportHistoryTable.HISTORYID_FLD + "," + sys_ReportHistoryTable.USERID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.REPORTID_FLD + "= ? "; // + pstrReportID + "'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter( sys_ReportHistoryTable.REPORTID_FLD , OleDbType.VarWChar)); ocmdPCS.Parameters[ sys_ReportHistoryTable.REPORTID_FLD ].Value = pstrReportID ; ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while(odrPCS.Read()) { sys_ReportHistoryVO voReportHistory = new sys_ReportHistoryVO(); voReportHistory.HistoryID = int.Parse(odrPCS[sys_ReportHistoryTable.HISTORYID_FLD].ToString().Trim()); voReportHistory.ReportID = odrPCS[sys_ReportHistoryTable.REPORTID_FLD].ToString().Trim(); voReportHistory.ExecDateTime = DateTime.Parse(odrPCS[sys_ReportHistoryTable.EXECDATETIME_FLD].ToString().Trim()); voReportHistory.UserID = odrPCS[sys_ReportHistoryTable.USERID_FLD].ToString().Trim(); voReportHistory.TableName = odrPCS[sys_ReportHistoryTable.TABLENAME_FLD].ToString().Trim(); arrObjects.Add(voReportHistory); } // trim to actual size arrObjects.TrimToSize(); // return return arrObjects; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_ReportHistoryPara /// but keep 10 last report /// </Description> /// <Inputs> /// HistoryID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 09-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public void DeleteButKeep10Last(int pintMaxID, string pstrUserName) { const string METHOD_NAME = THIS + ".DeleteButKeep10Last()"; string strSql = String.Empty; strSql = "DELETE " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.HISTORYID_FLD + "<=" + (pintMaxID - 9).ToString().Trim() + " AND " + sys_ReportHistoryTable.USERID_FLD + "= ? "; // + pstrUserName + "'"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter( sys_ReportHistoryTable.USERID_FLD , OleDbType.VarWChar)); ocmdPCS.Parameters[ sys_ReportHistoryTable.USERID_FLD ].Value = pstrUserName ; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to drop report history table from system /// </Description> /// <Inputs> /// HistoryID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 09-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public void DropHistoryTables(int pintHistoryID) { const string METHOD_NAME = THIS + ".DropHistoryTables()"; string strSql = String.Empty; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; strSql = "DROP TABLE " + Constants.REPORT_HISTORY_PREFIX + pintHistoryID.ToString().Trim(); try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to drop report history table from system /// </Description> /// <Inputs> /// History Table Name /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Thachnn /// </Authors> /// <History> /// 06-Oct-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public void DropHistoryTables(string pstrHistoryTableName) { const string METHOD_NAME = THIS + ".DropHistoryTables()"; string strSql = String.Empty; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; strSql = "DROP TABLE " + pstrHistoryTableName; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to create report history table and insert data /// using SELECT INTO statement. /// </Description> /// <Inputs> /// Sql command /// </Inputs> /// <Outputs> /// DataSet hold records of new table /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 10-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet CreateHistoryTable(string[] parrCommand, int pintMaxID, out string ostrTableName) { /// TODO: Bro. DungLA, I feel bug may be appear here, but I can't resolve /// Please help. Thachnn const string METHOD_NAME = THIS + ".CreateHistoryTable()"; const string WHERE_CLAUSE = "WHERE"; DataSet dstResult = new DataSet(); string strHistoryCommand = string.Empty; ostrTableName = string.Empty; foreach (string strElement in parrCommand) { // create sql statement to create Report History table and insert data to it // i.e: strHistoryCommand = "SELECT * INTO ReportHistory_1 FROM Orders". string strTemp = strElement; if (strElement.Trim().ToUpper().Equals(Constants.FROM_STR.Trim())) { ostrTableName = Constants.REPORT_HISTORY_PREFIX + (pintMaxID + 1).ToString().Trim(); strTemp = Constants.INTO_STR + ostrTableName + Constants.WHITE_SPACE + strElement; } strHistoryCommand += strTemp + Constants.WHITE_SPACE; } strHistoryCommand = strHistoryCommand.Trim(); if (strHistoryCommand.ToUpper().EndsWith(WHERE_CLAUSE)) { // trim the WHERE keyword in case of no where clause strHistoryCommand = strHistoryCommand.ToUpper().Replace(WHERE_CLAUSE, string.Empty).Trim(); } // now we got the sql statement, execute it and return value OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strHistoryCommand, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstResult, ostrTableName); return dstResult; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.MESSAGE_CANT_CREATE_REPORT_HISTORY, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get max report history id /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// Max ID /// </Outputs> /// <Returns> /// int /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 09-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int GetMaxReportHistoryID() { const string METHOD_NAME = THIS + ".GetMaxReportHistoryID()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT ISNULL(MAX(" + sys_ReportHistoryTable.HISTORYID_FLD + "), 0)" + " FROM " + sys_ReportHistoryTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return int.Parse(ocmdPCS.ExecuteScalar().ToString().Trim()); } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// Get last 10 executed report from history /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 20-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetLast10Report(string pstrUserName) { const string METHOD_NAME = THIS + ".GetLast10Report()"; ArrayList arrReports = new ArrayList(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; OleDbDataReader odrPCS = null; try { string strSql = "SELECT TOP 10 " + sys_ReportHistoryTable.HISTORYID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + "," + sys_ReportHistoryTable.USERID_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.USERID_FLD + "= ? " // + pstrUserName + "'" + " ORDER BY " + sys_ReportHistoryTable.HISTORYID_FLD + " DESC"; DataAccess.Utils utils = new DataAccess.Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter( sys_ReportHistoryTable.USERID_FLD , OleDbType.VarWChar)); ocmdPCS.Parameters[ sys_ReportHistoryTable.USERID_FLD ].Value = pstrUserName ; ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while(odrPCS.Read()) { sys_ReportHistoryVO voReportHistory = new sys_ReportHistoryVO(); voReportHistory.HistoryID = int.Parse(odrPCS[sys_ReportHistoryTable.HISTORYID_FLD].ToString().Trim()); voReportHistory.ReportID = odrPCS[sys_ReportHistoryTable.REPORTID_FLD].ToString().Trim(); voReportHistory.ExecDateTime = DateTime.Parse(odrPCS[sys_ReportHistoryTable.EXECDATETIME_FLD].ToString().Trim()); voReportHistory.UserID = odrPCS[sys_ReportHistoryTable.USERID_FLD].ToString().Trim(); voReportHistory.TableName = odrPCS[sys_ReportHistoryTable.TABLENAME_FLD].ToString().Trim(); arrReports.Add(voReportHistory); } // trim to actual size arrReports.TrimToSize(); // return return arrReports; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch(FormatException ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from History Table in order to show /// executed report /// </Description> /// <Inputs> /// History Table Name /// </Inputs> /// <Outputs> /// DataTable /// </Outputs> /// <Returns> /// DataTable /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 20-Jan-2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataTable GetDataFromHistoryTable(string pstrHistoryTableName) { const string METHOD_NAME = THIS + ".GetDataFromHistoryTable()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT * " + " FROM " + pstrHistoryTableName; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, pstrHistoryTableName); return dstPCS.Tables[pstrHistoryTableName]; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// Get last 10 executed report from history /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// DungLA /// </Authors> /// <History> /// 20-Jan-2005 /// 12/Oct/2005 Thachnn: fix bug injection /// </History> /// <Notes> /// </Notes> //************************************************************************** public ArrayList GetHistoryReportByUser(string pstrUsername) { const string METHOD_NAME = THIS + ".GetHistoryReportByUser()"; ArrayList arrReports = new ArrayList(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; OleDbDataReader odrPCS = null; try { string strSql = "SELECT " + sys_ReportHistoryTable.HISTORYID_FLD + "," + sys_ReportHistoryTable.EXECDATETIME_FLD + "," + sys_ReportHistoryTable.REPORTID_FLD + "," + sys_ReportHistoryTable.TABLENAME_FLD + "," + sys_ReportHistoryTable.USERID_FLD + " FROM " + sys_ReportHistoryTable.TABLE_NAME + " WHERE " + sys_ReportHistoryTable.USERID_FLD + "= ? " // + pstrUsername + "'" + " ORDER BY " + sys_ReportHistoryTable.HISTORYID_FLD + " DESC"; DataAccess.Utils utils = new DataAccess.Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter( sys_ReportHistoryTable.USERID_FLD , OleDbType.VarWChar)); ocmdPCS.Parameters[ sys_ReportHistoryTable.USERID_FLD ].Value = pstrUsername ; ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); while(odrPCS.Read()) { sys_ReportHistoryVO voReportHistory = new sys_ReportHistoryVO(); voReportHistory.HistoryID = int.Parse(odrPCS[sys_ReportHistoryTable.HISTORYID_FLD].ToString().Trim()); voReportHistory.ReportID = odrPCS[sys_ReportHistoryTable.REPORTID_FLD].ToString().Trim(); if (odrPCS[sys_ReportHistoryTable.EXECDATETIME_FLD] != DBNull.Value) voReportHistory.ExecDateTime = DateTime.Parse(odrPCS[sys_ReportHistoryTable.EXECDATETIME_FLD].ToString().Trim()); voReportHistory.UserID = odrPCS[sys_ReportHistoryTable.USERID_FLD].ToString().Trim(); voReportHistory.TableName = odrPCS[sys_ReportHistoryTable.TABLENAME_FLD].ToString().Trim(); arrReports.Add(voReportHistory); } // trim to actual size arrReports.TrimToSize(); // return return arrReports; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch(FormatException ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.INVALIDEXCEPTION, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Thachnn: 01/Oct/2005 /// Create a new table (with provided name) in the database from the provided System.Data.DataTable object /// </summary> /// <param name="pdtb">source data table, contain schema and data to create in the database</param> /// <param name="pstrDBNewTableName">new table name to create in the database</param> /// <returns>true if function finish SUCCESSfully</returns> public bool PushDataTableIntoNewDatabaseTable(DataTable pdtb, string pstrDBNewTableName) { bool blnRet = false; string strConnectionString = Utils.Instance.OleDbConnectionString; #region FIRST, create the new table (in the database) string strSQL = GenerateCREATE_QUERY_FromDataTable(pdtb,pstrDBNewTableName); if(strSQL.Equals(string.Empty) || pdtb == null || pstrDBNewTableName.Equals(string.Empty) || strConnectionString.Equals(string.Empty) ) { return false; } /// DO create executeNonQuery OleDbConnection ocon =null; OleDbCommand ocmd =null; try { ocon = new OleDbConnection(strConnectionString); ocmd = new OleDbCommand(strSQL, ocon); ocmd.Connection.Open(); ocmd.ExecuteNonQuery(); if (ocon!=null) { if (ocon.State != ConnectionState.Closed) { ocon.Close(); } } } catch(Exception ex) { //DEBUG: MessageBox.Show (ex.Message); if (ocon!=null) { if (ocon.State != ConnectionState.Closed) { ocon.Close(); } } return false; } #endregion #region SECOND, fill it value into the brand new table (in the database) System.Data.DataSet ods = new System.Data.DataSet(); pdtb.TableName = pstrDBNewTableName; // really need to reassign the table name to avoid exception ods.Tables.Add(pdtb); string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; // builder, auto make the Insert and Update query to update OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT TOP 1 * FROM " + pstrDBNewTableName; oconPCS = new OleDbConnection(strConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); ods.EnforceConstraints = false; odadPCS.Update(ods, pstrDBNewTableName); blnRet = true; } catch (Exception ex) //DEBUG: { //DEBUG: MessageBox.Show(ex.Message); blnRet = false; } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } #endregion return blnRet; } /// <summary> /// Thachnn: 30/Oct/2005 /// Generate CREATE TABLE QUERY From DataTable schema /// </summary> /// <param name="pdtb">DataTable object to get meta-data</param> /// <param name="pstrDBNewTableName">TableName to create in the return CREATE TABLE QUERY string</param> /// <returns></returns> public string GenerateCREATE_QUERY_FromDataTable(DataTable pdtb, string pstrDBNewTableName) { try // any error, pdtb is null, pstrDBNewTableName is empty, we return "string.Empty" immediatelly { #region Mapping setting NameValueCollection nvarrDBType = new NameValueCollection(); nvarrDBType.Add("Int64","bigint"); nvarrDBType.Add("Int32","int"); nvarrDBType.Add("Int16","smallint"); nvarrDBType.Add("Byte","tinyint"); nvarrDBType.Add("Boolean","bit"); nvarrDBType.Add("Object","sql_variant"); nvarrDBType.Add("Guid","uniqueidentifier"); //nvarrDBType.Add("String","char"); //nvarrDBType.Add("String","nchar"); //nvarrDBType.Add("String","ntext"); nvarrDBType.Add("String","nvarchar"); //nvarrDBType.Add("String","text"); //nvarrDBType.Add("String","varchar"); nvarrDBType.Add("DateTime","datetime"); //nvarrDBType.Add("DateTime","smalldatetime"); //nvarrDBType.Add("Decimal","money"); //nvarrDBType.Add("Decimal","numeric"); //nvarrDBType.Add("Decimal","smallmoney"); nvarrDBType.Add("Decimal","decimal"); nvarrDBType.Add("Double","float"); nvarrDBType.Add("Single","real"); //nvarrDBType.Add("Byte[]","image"); //nvarrDBType.Add("Byte[]","timestamp"); nvarrDBType.Add("Byte[]","varbinary"); //nvarrDBType.Add("Byte[]","binary"); //nvarrDBType.Add("Char[]","nchar"); //nvarrDBType.Add("Char[]","ntext"); //nvarrDBType.Add("Char[]","text"); //nvarrDBType.Add("Char[]","varchar"); nvarrDBType.Add("Char[]","nvarchar"); //nvarrDBType.Add("Char[]","char"); #endregion #region SQL query Generate string strCreateSQL = "CREATE TABLE " + pstrDBNewTableName + " ("; string strColName, strColType; foreach (DataColumn col in pdtb.Columns) { strColName = "[" + col.ColumnName + "]"; strColType = nvarrDBType[col.DataType.Name]; if (strColType.Equals("nvarchar")) { strColType += " (4000)"; } strCreateSQL += strColName + " " + strColType + " NULL ,"; } strCreateSQL = strCreateSQL.Substring(0,strCreateSQL.Length - 1); strCreateSQL += ")"; #endregion return strCreateSQL; } catch { return string.Empty; } } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestCaseSourceAttribute indicates the source to be used to /// provide test cases for a test method. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public class TestCaseSourceAttribute : NUnitAttribute, ITestBuilder, IImplyFixture { private NUnitTestCaseBuilder _builder = new NUnitTestCaseBuilder(); #region Constructors /// <summary> /// Construct with the name of the method, property or field that will provide data /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(string sourceName) { this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName, object[] methodParams) { this.MethodParams = methodParams; this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a Type and name /// </summary> /// <param name="sourceType">The Type that will provide data</param> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> public TestCaseSourceAttribute(Type sourceType, string sourceName) { this.SourceType = sourceType; this.SourceName = sourceName; } /// <summary> /// Construct with a name /// </summary> /// <param name="sourceName">The name of a static method, property or field that will provide data.</param> /// <param name="methodParams">A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect.</param> public TestCaseSourceAttribute(string sourceName, object[] methodParams) { this.MethodParams = methodParams; this.SourceName = sourceName; } /// <summary> /// Construct with a Type /// </summary> /// <param name="sourceType">The type that will provide data</param> public TestCaseSourceAttribute(Type sourceType) { this.SourceType = sourceType; } #endregion #region Properties /// <summary> /// A set of parameters passed to the method, works only if the Source Name is a method. /// If the source name is a field or property has no effect. /// </summary> public object[] MethodParams { get; private set; } /// <summary> /// The name of a the method, property or fiend to be used as a source /// </summary> public string SourceName { get; private set; } /// <summary> /// A Type to be used as a source /// </summary> public Type SourceType { get; private set; } /// <summary> /// Gets or sets the category associated with every fixture created from /// this attribute. May be a single category or a comma-separated list. /// </summary> public string Category { get; set; } #endregion #region ITestBuilder Members /// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The IMethod for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { int count = 0; foreach (TestCaseParameters parms in GetTestCasesFor(method)) { count++; yield return _builder.BuildTestMethod(method, suite, parms); } // If count > 0, error messages will be shown for each case // but if it's 0, we need to add an extra "test" to show the message. if (count == 0 && method.GetParameters().Length == 0) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, "TestCaseSourceAttribute may not be used on a method without parameters"); yield return _builder.BuildTestMethod(method, suite, parms); } } #endregion #region Helper Methods /// <summary> /// Returns a set of ITestCaseDataItems for use as arguments /// to a parameterized test method. /// </summary> /// <param name="method">The method for which data is needed.</param> /// <returns></returns> private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable source = GetTestCaseSource(method); if (source != null) { foreach (object item in source) { // First handle two easy cases: // 1. Source is null. This is really an error but if we // throw an exception we simply get an invalid fixture // without good info as to what caused it. Passing a // single null argument will cause an error to be // reported at the test level, in most cases. // 2. User provided an ITestCaseData and we just use it. ITestCaseData parms = item == null ? new TestCaseParameters(new object[] { null }) : item as ITestCaseData; if (parms == null) { object[] args = null; // 3. An array was passed, it may be an object[] // or possibly some other kind of array, which // TestCaseSource can accept. var array = item as Array; if (array != null) { // If array has the same number of elements as parameters // and it does not fit exactly into single existing parameter // we believe that this array contains arguments, not is a bare // argument itself. var parameters = method.GetParameters(); var argsNeeded = parameters.Length; if (argsNeeded > 0 && argsNeeded == array.Length && parameters[0].ParameterType != array.GetType()) { args = new object[array.Length]; for (var i = 0; i < array.Length; i++) args[i] = array.GetValue(i); } } if (args == null) { args = new object[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } else { data.Clear(); data.Add(new TestCaseParameters(new Exception("The test case source could not be found."))); } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; } private IEnumerable GetTestCaseSource(IMethodInfo method) { Type sourceType = SourceType ?? method.TypeInfo.Type; // Handle Type implementing IEnumerable separately if (SourceName == null) return Reflect.Construct(sourceType, null) as IEnumerable; MemberInfo[] members = sourceType.GetMember(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) return field.IsStatic ? (MethodParams == null ? (IEnumerable)field.GetValue(null) : ReturnErrorAsParameter(ParamGivenToField)) : ReturnErrorAsParameter(SourceMustBeStatic); var property = member as PropertyInfo; if (property != null) return property.GetGetMethod(true).IsStatic ? (MethodParams == null ? (IEnumerable)property.GetValue(null, null) : ReturnErrorAsParameter(ParamGivenToProperty)) : ReturnErrorAsParameter(SourceMustBeStatic); var m = member as MethodInfo; if (m != null) return m.IsStatic ? (MethodParams == null || m.GetParameters().Length == MethodParams.Length ? (IEnumerable)m.Invoke(null, MethodParams) : ReturnErrorAsParameter(NumberOfArgsDoesNotMatch)) : ReturnErrorAsParameter(SourceMustBeStatic); } return null; } private static IEnumerable ReturnErrorAsParameter(string errorMessage) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, errorMessage); return new TestCaseParameters[] { parms }; } private const string SourceMustBeStatic = "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method."; private const string ParamGivenToField = "You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " + "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " + "it or specify a method."; private const string ParamGivenToProperty = "You have specified a data source property but also given a set of parameters. " + "Properties cannot take parameters, please revise the 3rd parameter passed to the " + "TestCaseSource attribute and either remove it or specify a method."; private const string NumberOfArgsDoesNotMatch = "You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" + ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " + "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again."; #endregion } }
using System; using Foundation; using OpenGLES; using CoreGraphics; using CoreVideo; using OpenTK.Graphics.ES20; namespace AVCustomEdit { public class CrossDissolveRenderer : OpenGLRenderer { public CrossDissolveRenderer () : base() { } public override void RenderPixelBuffer (CoreVideo.CVPixelBuffer destinationPixelBuffer, CoreVideo.CVPixelBuffer foregroundPixelBuffer, CoreVideo.CVPixelBuffer backgroundPixelBuffer, float tween) { EAGLContext.SetCurrentContext (CurrentContext); if (foregroundPixelBuffer != null || backgroundPixelBuffer != null) { CVOpenGLESTexture foregroundLumaTexture = LumaTextureForPixelBuffer (foregroundPixelBuffer); CVOpenGLESTexture foregroundChromaTexture = ChromaTextureForPixelBuffer (foregroundPixelBuffer); CVOpenGLESTexture backgroundLumaTexture = LumaTextureForPixelBuffer (backgroundPixelBuffer); CVOpenGLESTexture backgroundChromaTexture = ChromaTextureForPixelBuffer (backgroundPixelBuffer); CVOpenGLESTexture destLumaTexture = LumaTextureForPixelBuffer (destinationPixelBuffer); CVOpenGLESTexture destChromaTexture = ChromaTextureForPixelBuffer (destinationPixelBuffer); GL.UseProgram (ProgramY); // Set the render transform float[] preferredRenderTransform = { (float)RenderTransform.xx, (float)RenderTransform.xy, (float)RenderTransform.x0, 0.0f, (float)RenderTransform.yx, (float)RenderTransform.yy,(float)RenderTransform.y0, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; GL.UniformMatrix4 (Uniforms [(int)Uniform.Render_Transform_Y], 1, false, preferredRenderTransform); GL.BindFramebuffer (FramebufferTarget.Framebuffer, OffscreenBufferHandle); GL.Viewport (0, 0, (int)destinationPixelBuffer.Width, (int)destinationPixelBuffer.Height); GL.ActiveTexture (TextureUnit.Texture0); GL.BindTexture (foregroundLumaTexture.Target, foregroundLumaTexture.Name); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); GL.ActiveTexture (TextureUnit.Texture1); GL.BindTexture (backgroundLumaTexture.Target, backgroundLumaTexture.Name); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); // Attach the destination texture as a color attachment to the off screen frame buffer GL.FramebufferTexture2D (FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, destLumaTexture.Target, destLumaTexture.Name, 0); if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { Console.Error.WriteLine ("Failed to make complete framebuffer object " + GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer)); foregroundLumaTexture.Dispose (); foregroundChromaTexture.Dispose (); backgroundLumaTexture.Dispose (); backgroundChromaTexture.Dispose (); destLumaTexture.Dispose (); destChromaTexture.Dispose (); VideoTextureCache.Flush (0); EAGLContext.SetCurrentContext (null); return; } GL.ClearColor (0.0f, 0.0f, 0.0f, 1.0f); GL.Clear (ClearBufferMask.ColorBufferBit); float[] quadVertexData1 = { -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, }; // texture data varies from 0 -> 1, whereas vertex data varies from -1 -> 1 float[] quadTextureData1 = { 0.5f + quadVertexData1 [0] / 2, 0.5f + quadVertexData1 [1] / 2, 0.5f + quadVertexData1 [2] / 2, 0.5f + quadVertexData1 [3] / 2, 0.5f + quadVertexData1 [4] / 2, 0.5f + quadVertexData1 [5] / 2, 0.5f + quadVertexData1 [6] / 2, 0.5f + quadVertexData1 [7] / 2, }; GL.Uniform1 (Uniforms [(int)Uniform.Y], 0); GL.VertexAttribPointer ((int)Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); GL.EnableVertexAttribArray ((int)Attrib.Vertex_Y); GL.VertexAttribPointer ((int)Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); GL.EnableVertexAttribArray ((int)Attrib.TexCoord_Y); // Blend function to draw the foreground frame GL.Enable (EnableCap.Blend); GL.BlendFunc (BlendingFactorSrc.One, BlendingFactorDest.Zero); // Draw the foreground frame GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); GL.Uniform1 (Uniforms [(int)Uniform.Y], 1); GL.VertexAttribPointer ((int)Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); GL.EnableVertexAttribArray ((int)Attrib.Vertex_Y); GL.VertexAttribPointer ((int)Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); GL.EnableVertexAttribArray ((int)Attrib.TexCoord_Y); // Blend function to draw the background frame GL.BlendColor (0, 0, 0, tween); GL.BlendFunc (BlendingFactorSrc.ConstantAlpha, BlendingFactorDest.OneMinusConstantAlpha); // Draw the background frame GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); // Perform similar operations as above for the UV plane GL.UseProgram (ProgramUV); GL.UniformMatrix4 (Uniforms [(int)Uniform.Render_Transform_UV], 1, false, preferredRenderTransform); GL.ActiveTexture (TextureUnit.Texture2); GL.BindTexture (foregroundChromaTexture.Target, foregroundChromaTexture.Name); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); GL.ActiveTexture (TextureUnit.Texture3); GL.BindTexture (backgroundChromaTexture.Target, backgroundChromaTexture.Name); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); GL.Viewport (0, 0, (int)destinationPixelBuffer.Width, (int)destinationPixelBuffer.Height); // Attach the destination texture as a color attachment to the off screen frame buffer GL.FramebufferTexture2D (FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, destChromaTexture.Target, destChromaTexture.Name, 0); if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { Console.Error.WriteLine ("Failed to make complete framebuffer object " + GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer)); foregroundLumaTexture.Dispose (); foregroundChromaTexture.Dispose (); backgroundLumaTexture.Dispose (); backgroundChromaTexture.Dispose (); destLumaTexture.Dispose (); destChromaTexture.Dispose (); this.VideoTextureCache.Flush (0); EAGLContext.SetCurrentContext (null); return; } GL.ClearColor (0.0f, 0.0f, 0.0f, 1.0f); GL.Clear (ClearBufferMask.ColorBufferBit); GL.Uniform1 (Uniforms [(int)Uniform.UV], 2); GL.VertexAttribPointer ((int)Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); GL.EnableVertexAttribArray ((int)Attrib.Vertex_UV); GL.VertexAttribPointer ((int)Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); GL.EnableVertexAttribArray ((int)Attrib.TexCoord_UV); // Blend function to draw the foreground frame GL.BlendFunc (BlendingFactorSrc.One, BlendingFactorDest.Zero); // Draw the foreground frame GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); GL.Uniform1 (Uniforms [(int)Uniform.UV], 3); GL.VertexAttribPointer ((int)Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); GL.EnableVertexAttribArray ((int)Attrib.Vertex_UV); GL.VertexAttribPointer ((int)Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); GL.EnableVertexAttribArray ((int)Attrib.TexCoord_UV); // Blend function to draw the background frame GL.BlendColor (0, 0, 0, tween); GL.BlendFunc (BlendingFactorSrc.ConstantAlpha, BlendingFactorDest.OneMinusConstantAlpha); // Draw the background frame GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); GL.Flush (); foregroundLumaTexture.Dispose (); foregroundChromaTexture.Dispose (); backgroundLumaTexture.Dispose (); backgroundChromaTexture.Dispose (); destLumaTexture.Dispose (); destChromaTexture.Dispose (); this.VideoTextureCache.Flush (0); EAGLContext.SetCurrentContext (null); } } } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// The ModalPopup extender allows you to display content in an element that mimics a modal dialog box, /// which prevents a user from interacting with the rest of pages. The modal content can contain any /// hierarchy of controls. It is displayed above background (in z-order) that can have a custom style applied to it. /// /// Clicking OK or Cancel in the modal popup dismisses the content and optionally runs a custom script. /// The custom script is typically used to apply changes that were made in the modal popup. If a postback /// is required, you can allow the OK or Cancel control to perform a postback. /// /// By default, the modal content is centered on the page. However, you can set absolute positiniong and /// set only X or Y to center the content vertically or horizontally. /// </summary> [Designer(typeof(ModalPopupExtenderDesigner))] [ClientScriptResource("Sys.Extended.UI.ModalPopupBehavior", Constants.ModalPopup)] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(DragPanelExtender))] [RequiredScript(typeof(DropShadowExtender))] [RequiredScript(typeof(AnimationExtender))] [TargetControlType(typeof(WebControl))] [TargetControlType(typeof(HtmlControl))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.ModalPopup + Constants.IconPostfix)] public class ModalPopupExtender : DynamicPopulateExtenderControlBase { // Desired visibility state: true, false or none bool? _show; Animation _onHidden, _onShown, _onHiding, _onShowing; /// <summary> /// ID of an element to display as a modal popup /// </summary> [ExtenderControlProperty] [DefaultValue("")] [IDReferenceProperty(typeof(WebControl))] [RequiredProperty] [ClientPropertyName("popupControlID")] public string PopupControlID { get { return GetPropertyValue("PopupControlID", String.Empty); } set { SetPropertyValue("PopupControlID", value); } } /// <summary> /// A CSS class to apply to the background when the modal popup is displayed /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("backgroundCssClass")] public string BackgroundCssClass { get { return GetPropertyValue("BackgroundCssClass", String.Empty); } set { SetPropertyValue("BackgroundCssClass", value); } } /// <summary> /// ID of an element that dismisses the modal popup /// </summary> [ExtenderControlProperty] [DefaultValue("")] [IDReferenceProperty(typeof(WebControl))] [ClientPropertyName("okControlID")] public string OkControlID { get { return GetPropertyValue("OkControlID", String.Empty); } set { SetPropertyValue("OkControlID", value); } } /// <summary> /// ID of an element that cancels the modal popup /// </summary> [ExtenderControlProperty] [DefaultValue("")] [IDReferenceProperty(typeof(WebControl))] [ClientPropertyName("cancelControlID")] public string CancelControlID { get { return GetPropertyValue("CancelControlID", String.Empty); } set { SetPropertyValue("CancelControlID", value); } } /// <summary> /// A script to run when the modal popup is dismissed using the element specified in OkControlID /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("onOkScript")] public string OnOkScript { get { return GetPropertyValue("OnOkScript", String.Empty); } set { SetPropertyValue("OnOkScript", value); } } /// <summary> /// A script to run when the modal popup is dismissed using the element specified in CancelControlID /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("onCancelScript")] public string OnCancelScript { get { return GetPropertyValue("OnCancelScript", String.Empty); } set { SetPropertyValue("OnCancelScript", value); } } /// <summary> /// The X coordinate of the top/left corner of the modal popup /// </summary> /// <remarks> /// If this value is not specified, the popup will be centered horizontally /// </remarks> [ExtenderControlProperty] [DefaultValue(-1)] [ClientPropertyName("x")] public int X { get { return GetPropertyValue("X", -1); } set { SetPropertyValue("X", value); } } /// <summary> /// The Y coordinate of the top/left corner of the modal popup /// </summary> /// <remarks> /// If this value is not specified, the popup will be centered vertically /// </remarks> [ExtenderControlProperty] [DefaultValue(-1)] [ClientPropertyName("y")] public int Y { get { return GetPropertyValue("Y", -1); } set { SetPropertyValue("Y", value); } } /// <summary> /// A Boolean value that specifies whether or not the modal popup can be dragged /// </summary> /// <remarks> /// This property is obsolete /// </remarks> [ExtenderControlProperty] [DefaultValue(false)] [Obsolete("The drag feature on modal popup will be automatically turned on if you specify the PopupDragHandleControlID property. Setting the Drag property is a noop")] [ClientPropertyName("drag")] public bool Drag { get { return GetPropertyValue("stringDrag", false); } set { SetPropertyValue("stringDrag", value); } } /// <summary> /// ID of the embedded element that contains a popup header and title that will /// be used as a drag handle /// </summary> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [DefaultValue("")] [ClientPropertyName("popupDragHandleControlID")] public string PopupDragHandleControlID { get { return GetPropertyValue("PopupDragHandleControlID", String.Empty); } set { SetPropertyValue("PopupDragHandleControlID", value); } } /// <summary> /// Set to True to automatically add a drop shadow to the modal popup /// </summary> [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("dropShadow")] public bool DropShadow { get { return GetPropertyValue("stringDropShadow", false); } set { SetPropertyValue("stringDropShadow", value); } } /// <summary> /// A value that determines if the popup must be repositioned when the window /// is resized or scrolled /// </summary> [ExtenderControlProperty] [DefaultValue(ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll)] [ClientPropertyName("repositionMode")] public ModalPopupRepositionMode RepositionMode { get { return GetPropertyValue("RepositionMode", ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll); } set { SetPropertyValue("RepositionMode", value); } } /// <summary> /// Animation to perform once the modal popup is shown /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onShown")] public Animation OnShown { get { return GetAnimation(ref _onShown, "OnShown"); } set { SetAnimation(ref _onShown, "OnShown", value); } } /// <summary> /// Animation to perform once the modal popup is hidden /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onHidden")] public Animation OnHidden { get { return GetAnimation(ref _onHidden, "OnHidden"); } set { SetAnimation(ref _onHidden, "OnHidden", value); } } /// <summary> /// Animation to perform just before the modal popup is shown /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onShowing")] public Animation OnShowing { get { return GetAnimation(ref _onShowing, "OnShowing"); } set { SetAnimation(ref _onShowing, "OnShowing", value); } } /// <summary> /// Animation to perform just before the modal popup is hidden. /// The popup closes only after animation completes /// </summary> [Browsable(false)] [ExtenderControlProperty] [ClientPropertyName("onHiding")] public Animation OnHiding { get { return GetAnimation(ref _onHiding, "OnHiding"); } set { SetAnimation(ref _onHiding, "OnHiding", value); } } public void Show() { _show = true; } public void Hide() { _show = false; } protected override void OnPreRender(EventArgs e) { // If Show() or Hide() were called during the request, change the visibility now if(_show.HasValue) ChangeVisibility(_show.Value); ResolveControlIDs(_onShown); ResolveControlIDs(_onHidden); ResolveControlIDs(_onShowing); ResolveControlIDs(_onHiding); base.OnPreRender(e); } // Emit script to the client that will cause the modal popup behavior // to be shown or hidden private void ChangeVisibility(bool show) { if(TargetControl == null) throw new ArgumentNullException("TargetControl", "TargetControl property cannot be null"); var operation = show ? "show" : "hide"; if(ScriptManager.GetCurrent(Page).IsInAsyncPostBack) // RegisterDataItem is more elegant, but we can only call it during an async postback ScriptManager.GetCurrent(Page).RegisterDataItem(TargetControl, operation); else { // Add a load handler to show the popup and then remove itself var script = string.Format(CultureInfo.InvariantCulture, "(function() {{" + "var fn = function() {{" + "Sys.Extended.UI.ModalPopupBehavior.invokeViaServer('{0}', {1}); " + "Sys.Application.remove_load(fn);" + "}};" + "Sys.Application.add_load(fn);" + "}})();", BehaviorID, show ? "true" : "false"); ScriptManager.RegisterStartupScript(this, typeof(ModalPopupExtender), operation + BehaviorID, script, true); } } } } #pragma warning restore 1591
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Globalization { // List of calendar data // Note the we cache overrides. // Note that localized names (resource names) aren't available from here. // // NOTE: Calendars depend on the locale name that creates it. Only a few // properties are available without locales using CalendarData.GetCalendar(CalendarData) internal partial class CalendarData { // Max calendars internal const int MAX_CALENDARS = 23; // Identity internal String sNativeName; // Calendar Name for the locale // Formats internal String[] saShortDates; // Short Data format, default first internal String[] saYearMonths; // Year/Month Data format, default first internal String[] saLongDates; // Long Data format, default first internal String sMonthDay; // Month/Day format // Calendar Parts Names internal String[] saEraNames; // Names of Eras internal String[] saAbbrevEraNames; // Abbreviated Era Names internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday internal String[] saSuperShortDayNames; // Super short Day of week names internal String[] saMonthNames; // Month Names (13) internal String[] saAbbrevMonthNames; // Abbrev Month Names (13) internal String[] saMonthGenitiveNames; // Genitive Month Names (13) internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13) internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year. // Integers at end to make marshaller happier internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) internal int iCurrentEra = 0; // current era # (usually 1) // Use overrides? internal bool bUseUserOverrides; // True if we want user overrides. // Static invariant for the invariant locale internal static CalendarData Invariant; // Private constructor private CalendarData() { } // Invariant constructor static CalendarData() { // Set our default/gregorian US calendar data // Calendar IDs are 1-based, arrays are 0 based. CalendarData invariant = new CalendarData(); // Set default data for calendar // Note that we don't load resources since this IS NOT supposed to change (by definition) invariant.sNativeName = "Gregorian Calendar"; // Calendar Name // Year invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry) invariant.iCurrentEra = 1; // Current era # // Formats invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format invariant.sMonthDay = "MMMM dd"; // Month day pattern // Calendar Parts Names invariant.saEraNames = new String[] { "A.D." }; // Era names invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", String.Empty}; // month names invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant) invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant) invariant.bUseUserOverrides = false; // Calendar was built, go ahead and assign it... Invariant = invariant; } // // Get a bunch of data for a calendar // internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides) { this.bUseUserOverrides = bUseUserOverrides; if (!LoadCalendarDataFromSystem(localeName, calendarId)) { Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName); // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale. // Formats if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format // Calendar Parts Names if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13) if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13) // Genitive and Leap names can follow the fallback below } if (calendarId == CalendarId.TAIWAN) { if (SystemSupportsTaiwaneseCalendar()) { // We got the month/day names from the OS (same as gregorian), but the native name is wrong this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6"; } else { this.sNativeName = String.Empty; } } // Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc) if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0])) this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant) if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0])) this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant) if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0])) this.saLeapYearMonthNames = this.saMonthNames; InitializeEraNames(localeName, calendarId); InitializeAbbreviatedEraNames(localeName, calendarId); // Abbreviated English Era Names are only used for the Japanese calendar. if (calendarId == CalendarId.JAPAN) { this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames(); } else { // For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars) this.saAbbrevEnglishEraNames = new String[] { "" }; } // Japanese is the only thing with > 1 era. Its current era # is how many ever // eras are in the array. (And the others all have 1 string in the array) this.iCurrentEra = this.saEraNames.Length; } private void InitializeEraNames(string localeName, CalendarId calendarId) { // Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows switch (calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new String[] { "A.D." }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saEraNames = new String[] { "A.D." }; break; case CalendarId.HEBREW: this.saEraNames = new String[] { "C.E." }; break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" }; } else { this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" }; } break; case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: // These are all the same: this.saEraNames = new String[] { "\x0645" }; break; case CalendarId.GREGORIAN_ME_FRENCH: this.saEraNames = new String[] { "ap. J.-C." }; break; case CalendarId.TAIWAN: if (SystemSupportsTaiwaneseCalendar()) { this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" }; } else { this.saEraNames = new String[] { String.Empty }; } break; case CalendarId.KOREA: this.saEraNames = new String[] { "\xb2e8\xae30" }; break; case CalendarId.THAI: this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saEraNames = JapaneseCalendar.EraNames(); break; case CalendarId.PERSIAN: if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0])) { this.saEraNames = new String[] { "\x0647\x002e\x0634" }; } break; default: // Most calendars are just "A.D." this.saEraNames = Invariant.saEraNames; break; } } private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId) { // Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows switch (calendarId) { // For Localized Gregorian we really expect the data from the OS. case CalendarId.GREGORIAN: // Fallback for CoreCLR < Win7 or culture.dll missing if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = new String[] { "AD" }; } break; // The rest of the calendars have constant data, so we'll just use that case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: this.saAbbrevEraNames = new String[] { "AD" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames(); break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { // Special case for Divehi this.saAbbrevEraNames = new String[] { "\x0780\x002e" }; } else { this.saAbbrevEraNames = new String[] { "\x0647\x0640" }; } break; case CalendarId.TAIWAN: // Get era name and abbreviate it this.saAbbrevEraNames = new String[1]; if (this.saEraNames[0].Length == 4) { this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2); } else { this.saAbbrevEraNames[0] = this.saEraNames[0]; } break; case CalendarId.PERSIAN: if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0])) { this.saAbbrevEraNames = this.saEraNames; } break; default: // Most calendars just use the full name this.saAbbrevEraNames = this.saEraNames; break; } } internal static CalendarData GetCalendarData(CalendarId calendarId) { // // Get a calendar. // Unfortunately we depend on the locale in the OS, so we need a locale // no matter what. So just get the appropriate calendar from the // appropriate locale here // // Get a culture name // TODO: Note that this doesn't handle the new calendars (lunisolar, etc) String culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture)._cultureData.GetCalendar(calendarId); } private static String CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN_US: return "fa-IR"; // "fa-IR" Iran case CalendarId.JAPAN: return "ja-JP"; // "ja-JP" Japan case CalendarId.TAIWAN: return "zh-TW"; // zh-TW Taiwan case CalendarId.KOREA: return "ko-KR"; // "ko-KR" Korea case CalendarId.HIJRI: case CalendarId.GREGORIAN_ARABIC: case CalendarId.UMALQURA: return "ar-SA"; // "ar-SA" Saudi Arabia case CalendarId.THAI: return "th-TH"; // "th-TH" Thailand case CalendarId.HEBREW: return "he-IL"; // "he-IL" Israel case CalendarId.GREGORIAN_ME_FRENCH: return "ar-DZ"; // "ar-DZ" Algeria case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return "ar-IQ"; // "ar-IQ"; Iraq default: // Default to gregorian en-US break; } return "en-US"; } } }
/* * 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.Linq; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.TimeInForces; using QuantConnect.Securities; using QuantConnect.Securities.Forex; namespace QuantConnect.Brokerages { /// <summary> /// Provides properties specific to interactive brokers /// </summary> public class InteractiveBrokersBrokerageModel : DefaultBrokerageModel { private readonly Type[] _supportedTimeInForces = { typeof(GoodTilCanceledTimeInForce), typeof(DayTimeInForce), typeof(GoodTilDateTimeInForce) }; /// <summary> /// Initializes a new instance of the <see cref="InteractiveBrokersBrokerageModel"/> class /// </summary> /// <param name="accountType">The type of account to be modelled, defaults to /// <see cref="AccountType.Margin"/></param> public InteractiveBrokersBrokerageModel(AccountType accountType = AccountType.Margin) : base(accountType) { } /// <summary> /// Gets a new fee model that represents this brokerage's fee structure /// </summary> /// <param name="security">The security to get a fee model for</param> /// <returns>The new fee model for this brokerage</returns> public override IFeeModel GetFeeModel(Security security) { return new InteractiveBrokersFeeModel(); } /// <summary> /// Returns true if the brokerage could accept this order. This takes into account /// order type, security type, and order size limits. /// </summary> /// <remarks> /// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit /// </remarks> /// <param name="security">The security being ordered</param> /// <param name="order">The order to be processed</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param> /// <returns>True if the brokerage could process the order, false otherwise</returns> public override bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { message = null; // validate security type if (security.Type != SecurityType.Equity && security.Type != SecurityType.Forex && security.Type != SecurityType.Option && security.Type != SecurityType.Future) { message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported", $"The {nameof(InteractiveBrokersBrokerageModel)} does not support {security.Type} security type." ); return false; } // validate order quantity //https://www.interactivebrokers.com/en/?f=%2Fen%2Ftrading%2FforexOrderSize.php if (security.Type == SecurityType.Forex && !IsForexWithinOrderSizeLimits(order.Symbol.Value, order.Quantity, out message)) { return false; } // validate time in force if (!_supportedTimeInForces.Contains(order.TimeInForce.GetType())) { message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "NotSupported", $"The {nameof(InteractiveBrokersBrokerageModel)} does not support {order.TimeInForce.GetType().Name} time in force." ); return false; } return true; } /// <summary> /// Returns true if the brokerage would allow updating the order as specified by the request /// </summary> /// <param name="security">The security of the order</param> /// <param name="order">The order to be updated</param> /// <param name="request">The requested update to be made to the order</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param> /// <returns>True if the brokerage would allow updating the order, false otherwise</returns> public override bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { message = null; if (order.SecurityType == SecurityType.Forex && request.Quantity != null) { return IsForexWithinOrderSizeLimits(order.Symbol.Value, request.Quantity.Value, out message); } return true; } /// <summary> /// Returns true if the brokerage would be able to execute this order at this time assuming /// market prices are sufficient for the fill to take place. This is used to emulate the /// brokerage fills in backtesting and paper trading. For example some brokerages may not perform /// executions during extended market hours. This is not intended to be checking whether or not /// the exchange is open, that is handled in the Security.Exchange property. /// </summary> /// <param name="security"></param> /// <param name="order">The order to test for execution</param> /// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns> public override bool CanExecuteOrder(Security security, Order order) { return order.SecurityType != SecurityType.Base; } /// <summary> /// Returns true if the specified order is within IB's order size limits /// </summary> private bool IsForexWithinOrderSizeLimits(string currencyPair, decimal quantity, out BrokerageMessageEvent message) { /* https://www.interactivebrokers.com/en/?f=%2Fen%2Ftrading%2FforexOrderSize.php Currency Currency Description Minimum Order Size Maximum Order Size USD US Dollar 25,000 7,000,000 AUD Australian Dollar 25,000 6,000,000 CAD Canadian Dollar 25,000 6,000,000 CHF Swiss Franc 25,000 6,000,000 CNH China Renminbi (offshore) 160,000 40,000,000 CZK Czech Koruna USD 25,000(1) USD 7,000,000(1) DKK Danish Krone 150,000 35,000,000 EUR Euro 20,000 5,000,000 GBP British Pound Sterling 17,000 4,000,000 HKD Hong Kong Dollar 200,000 50,000,000 HUF Hungarian Forint USD 25,000(1) USD 7,000,000(1) ILS Israeli Shekel USD 25,000(1) USD 7,000,000(1) KRW Korean Won 50,000,000 750,000,000 JPY Japanese Yen 2,500,000 550,000,000 MXN Mexican Peso 300,000 70,000,000 NOK Norwegian Krone 150,000 35,000,000 NZD New Zealand Dollar 35,000 8,000,000 RUB Russian Ruble 750,000 30,000,000 SEK Swedish Krona 175,000 40,000,000 SGD Singapore Dollar 35,000 8,000,000 */ message = null; // switch on the currency being bought string baseCurrency, quoteCurrency; Forex.DecomposeCurrencyPair(currencyPair, out baseCurrency, out quoteCurrency); decimal max; ForexCurrencyLimits.TryGetValue(baseCurrency, out max); var orderIsWithinForexSizeLimits = quantity < max; if (!orderIsWithinForexSizeLimits) { message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "OrderSizeLimit", $"The maximum allowable order size is {max}{baseCurrency}." ); } return orderIsWithinForexSizeLimits; } private static readonly IReadOnlyDictionary<string, decimal> ForexCurrencyLimits = new Dictionary<string, decimal>() { {"USD", 7000000m}, {"AUD", 6000000m}, {"CAD", 6000000m}, {"CHF", 6000000m}, {"CNH", 40000000m}, {"CZK", 0m}, // need market price in USD or EUR -- do later when we support {"DKK", 35000000m}, {"EUR", 5000000m}, {"GBP", 4000000m}, {"HKD", 50000000m}, {"HUF", 0m}, // need market price in USD or EUR -- do later when we support {"ILS", 0m}, // need market price in USD or EUR -- do later when we support {"KRW", 750000000m}, {"JPY", 550000000m}, {"MXN", 70000000m}, {"NOK", 35000000m}, {"NZD", 8000000m}, {"RUB", 30000000m}, {"SEK", 40000000m}, {"SGD", 8000000m} }; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler { public class WorkCoordinatorTests { private const string SolutionCrawler = "SolutionCrawler"; [Fact] public void RegisterService() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var registrationService = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), AggregateAsynchronousOperationListener.EmptyListeners); // register and unregister workspace to the service registrationService.Register(workspace); registrationService.Unregister(workspace); } } [Fact, WorkItem(747226)] public void SolutionAdded_Simple() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public void SolutionAdded_Complex() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); var worker = ExecuteOperation(workspace, w => w.OnSolutionAdded(solution)); Assert.Equal(10, worker.SyntaxDocumentIds.Count); } } [Fact] public void Solution_Remove() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var worker = ExecuteOperation(workspace, w => w.OnSolutionRemoved()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public void Solution_Clear() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var worker = ExecuteOperation(workspace, w => w.ClearSolution()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public void Solution_Reload() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var worker = ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public void Solution_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); WaitWaiter(workspace.ExportProvider); var solution = workspace.CurrentSolution; var documentId = solution.Projects.First().DocumentIds[0]; solution = solution.RemoveDocument(documentId); var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution; var worker = ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public void Project_Add() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List<DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } } [Fact] public void Project_Remove() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var projectid = workspace.CurrentSolution.ProjectIds[0]; var worker = ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.InvalidateDocumentIds.Count); } } [Fact] public void Project_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); WaitWaiter(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(); var documentId = project.DocumentIds[0]; var solution = workspace.CurrentSolution.RemoveDocument(documentId); var worker = ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public void Project_Reload() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var project = solution.Projects[0]; var worker = ExecuteOperation(workspace, w => w.OnProjectReloaded(project)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public void Document_Add() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var project = solution.Projects[0]; var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(6, worker.DocumentIds.Count); } } [Fact] public void Document_Remove() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = ExecuteOperation(workspace, w => w.OnDocumentRemoved(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public void Document_Reload() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = solution.Projects[0].Documents[0]; var worker = ExecuteOperation(workspace, w => w.OnDocumentReloaded(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public void Document_Reanalyze() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var info = solution.Projects[0].Documents[0]; var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. TouchEverything(workspace.CurrentSolution); service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id)); TouchEverything(workspace.CurrentSolution); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.DocumentIds.Count); } } [WorkItem(670335)] public void Document_Change() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//"))); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public void Document_AdditionalFileChange() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var project = solution.Projects[0]; var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//"))); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WorkItem(670335)] public void Document_Cancellation() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335)] public void Document_Cancellation_MultipleTimes() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); analyzer.RunningEvent.Reset(); workspace.ChangeDocument(id, SourceText.From("// ")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335)] public void Document_InvocationReasons() { using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(blockedRun: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // first invocation will block worker workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); var openReady = new ManualResetEventSlim(initialState: false); var closeReady = new ManualResetEventSlim(initialState: false); workspace.DocumentOpened += (o, e) => openReady.Set(); workspace.DocumentClosed += (o, e) => closeReady.Set(); // cause several different request to queue up workspace.ChangeDocument(id, SourceText.From("// ")); workspace.OpenDocument(id); workspace.CloseDocument(id); openReady.Set(); closeReady.Set(); analyzer.BlockEvent.Set(); Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [Fact] public void Document_TopLevelType_Whitespace() { var code = @"class C { $$ }"; var textToInsert = " "; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelType_Character() { var code = @"class C { $$ }"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelType_NewLine() { var code = @"class C { $$ }"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelType_NewLine2() { var code = @"class C { $$"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_EmptyFile() { var code = @"$$"; var textToInsert = "class"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevel1() { var code = @"class C { public void Test($$"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevel2() { var code = @"class C { public void Test(int $$"; var textToInsert = " "; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevel3() { var code = @"class C { public void Test(int i,$$"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_InteriorNode1() { var code = @"class C { public void Test() {$$"; var textToInsert = "\r\n"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode2() { var code = @"class C { public void Test() { $$ }"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode_Field() { var code = @"class C { int i = $$ }"; var textToInsert = "1"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode_Field1() { var code = @"class C { int i = 1 + $$ }"; var textToInsert = "1"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_InteriorNode_Accessor() { var code = @"class C { public int A { get { $$ } } }"; var textToInsert = "return"; InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public void Document_TopLevelWhitespace() { var code = @"class C { /// $$ public int A() { } }"; var textToInsert = "return"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_TopLevelWhitespace2() { var code = @"/// $$ class C { public int A() { } }"; var textToInsert = "return"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void Document_InteriorNode_Malformed() { var code = @"class C { public void Test() { $$"; var textToInsert = "int"; InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; int position; string code; MarkupTestFile.GetPosition(markup, out code, out position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); } [Fact, WorkItem(739943)] public void SemanticChange_Propagation() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { workspace.OnSolutionAdded(solution); WaitWaiter(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); #if false Assert.True(1 == worker.SyntaxDocumentIds.Count, string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); Assert.True(4 == worker.DocumentIds.Count, string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); #endif } } [Fact] public void ProgressReporterTest() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new TestWorkspace(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), SolutionCrawler)) { WaitWaiter(workspace.ExportProvider); var service = workspace.Services.GetService<ISolutionCrawlerService>(); var reporter = service.GetProgressReporter(workspace); Assert.False(reporter.InProgress); // set up events bool started = false; reporter.Started += (o, a) => { started = true; }; bool stopped = false; reporter.Stopped += (o, a) => { stopped = true; }; var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); // first mutation workspace.OnSolutionAdded(solution); Wait((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); // reset started = false; stopped = false; // second mutation workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6")); Wait((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); registrationService.Unregister(workspace); } } private void InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp) { using (var workspace = TestWorkspaceFactory.CreateWorkspaceFromLines( SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: new string[] { code })) { var analyzer = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); var testDocument = workspace.Documents.First(); var insertPosition = testDocument.CursorPosition; var textBuffer = testDocument.GetTextBuffer(); using (var edit = textBuffer.CreateEdit()) { edit.Insert(insertPosition.Value, text); edit.Apply(); } Wait(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count); } } private Analyzer ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation) { var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. TouchEverything(workspace.CurrentSolution); operation(workspace); TouchEverything(workspace.CurrentSolution); Wait(service, workspace); service.Unregister(workspace); return worker; } private void TouchEverything(Solution solution) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { document.GetTextAsync().PumpingWait(); document.GetSyntaxRootAsync().PumpingWait(); document.GetSemanticModelAsync().PumpingWait(); } } } private void Wait(SolutionCrawlerRegistrationService service, TestWorkspace workspace) { WaitWaiter(workspace.ExportProvider); service.WaitUntilCompletion_ForTestingPurposesOnly(workspace); } private void WaitWaiter(ExportProvider provider) { var workspasceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; workspasceWaiter.CreateWaitTask().PumpingWait(); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; solutionCrawlerWaiter.CreateWaitTask().PumpingWait(); } private static SolutionInfo GetInitialSolutionInfoWithP2P() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); var projectId4 = ProjectId.CreateNewId(); var projectId5 = ProjectId.CreateNewId(); var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") }, projectReferences: new[] { new ProjectReference(projectId1) }), ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") }, projectReferences: new[] { new ProjectReference(projectId2) }), ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }), ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") }, projectReferences: new[] { new ProjectReference(projectId4) }), }); return solution; } private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace) { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5") }) }); } private IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); } [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.SolutionCrawler)] private class SolutionCrawlerWaiter : AsynchronousOperationListener { } [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.Workspace)] private class WorkspaceWaiter : AsynchronousOperationListener { } private class AnalyzerProvider : IIncrementalAnalyzerProvider { private readonly Analyzer _analyzer; public AnalyzerProvider(Analyzer analyzer) { _analyzer = analyzer; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return _analyzer; } } internal class Metadata : IncrementalAnalyzerProviderMetadata { public Metadata(params string[] workspaceKinds) : base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } }) { } public static readonly Metadata Crawler = new Metadata(SolutionCrawler); } private class Analyzer : IIncrementalAnalyzer { private readonly bool _waitForCancellation; private readonly bool _blockedRun; public readonly ManualResetEventSlim BlockEvent; public readonly ManualResetEventSlim RunningEvent; public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>(); public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>(); public Analyzer(bool waitForCancellation = false, bool blockedRun = false) { _waitForCancellation = waitForCancellation; _blockedRun = blockedRun; this.BlockEvent = new ManualResetEventSlim(initialState: false); this.RunningEvent = new ManualResetEventSlim(initialState: false); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { this.ProjectIds.Add(project.Id); return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { if (bodyOpt == null) { this.DocumentIds.Add(document.Id); } return SpecializedTasks.EmptyTask; } public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { this.SyntaxDocumentIds.Add(document.Id); Process(document.Id, cancellationToken); return SpecializedTasks.EmptyTask; } public void RemoveDocument(DocumentId documentId) { InvalidateDocumentIds.Add(documentId); } public void RemoveProject(ProjectId projectId) { InvalidateProjectIds.Add(projectId); } private void Process(DocumentId documentId, CancellationToken cancellationToken) { if (_blockedRun && !RunningEvent.IsSet) { this.RunningEvent.Set(); // Wait until unblocked this.BlockEvent.Wait(); } if (_waitForCancellation && !RunningEvent.IsSet) { this.RunningEvent.Set(); cancellationToken.WaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } } #region unused public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return false; } #endregion } #if false private string GetListenerTrace(ExportProvider provider) { var sb = new StringBuilder(); var workspasceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener; sb.AppendLine("workspace"); sb.AppendLine(workspasceWaiter.Trace()); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener; sb.AppendLine("solutionCrawler"); sb.AppendLine(solutionCrawlerWaiter.Trace()); return sb.ToString(); } internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly object gate = new object(); private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>(); private readonly StringBuilder sb = new StringBuilder(); private int counter; public TestAsynchronousOperationListener() { } public IAsyncToken BeginAsyncOperation(string name, object tag = null) { lock (gate) { return new AsyncToken(this, name); } } private void Increment(string name) { lock (gate) { sb.AppendLine("i -> " + name + ":" + counter++); } } private void Decrement(string name) { lock (gate) { counter--; if (counter == 0) { foreach (var task in pendingTasks) { task.SetResult(true); } pendingTasks.Clear(); } sb.AppendLine("d -> " + name + ":" + counter); } } public virtual Task CreateWaitTask() { lock (gate) { var source = new TaskCompletionSource<bool>(); if (counter == 0) { // There is nothing to wait for, so we are immediately done source.SetResult(true); } else { pendingTasks.Add(source); } return source.Task; } } public bool TrackActiveTokens { get; set; } public bool HasPendingWork { get { return counter != 0; } } private class AsyncToken : IAsyncToken { private readonly TestAsynchronousOperationListener listener; private readonly string name; private bool disposed; public AsyncToken(TestAsynchronousOperationListener listener, string name) { this.listener = listener; this.name = name; listener.Increment(name); } public void Dispose() { lock (listener.gate) { if (disposed) { throw new InvalidOperationException("Double disposing of an async token"); } disposed = true; listener.Decrement(this.name); } } } public string Trace() { return sb.ToString(); } } #endif } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, 2003 // // File: PathMatrixAnimation.cs //------------------------------------------------------------------------------ using MS.Internal; using System; using System.IO; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Composition; namespace System.Windows.Media.Animation { /// <summary> /// This animation can be used inside of a MatrixAnimationCollection to move /// a visual object along a path. /// </summary> public class MatrixAnimationUsingPath : MatrixAnimationBase { #region Data private bool _isValid; /// <summary> /// If IsCumulative is set to true, these values represents the values /// that are accumulated with each repeat. They are the end values of /// the path. /// </summary> private Vector _accumulatingOffset = new Vector(); private double _accumulatingAngle; #endregion #region Constructors /// <summary> /// Creates a new PathMatrixAnimation class. /// </summary> /// <remarks> /// There is no default PathGeometry so the user must specify one. /// </remarks> public MatrixAnimationUsingPath() : base() { } #endregion #region Freezable /// <summary> /// Creates a copy of this PathMatrixAnimation. /// </summary> /// <returns>The copy.</returns> public new MatrixAnimationUsingPath Clone() { return (MatrixAnimationUsingPath)base.Clone(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new MatrixAnimationUsingPath(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. /// </summary> protected override void OnChanged() { _isValid = false; base.OnChanged(); } #endregion #region Public /// <summary> /// DoesRotateWithTangent Property /// </summary> public static readonly DependencyProperty DoesRotateWithTangentProperty = DependencyProperty.Register( "DoesRotateWithTangent", typeof(bool), typeof(MatrixAnimationUsingPath), new PropertyMetadata(false)); /// <summary> /// If this is set to true, the object will rotate along with the /// tangent to the path. /// </summary> public bool DoesRotateWithTangent { get { return (bool)GetValue(DoesRotateWithTangentProperty); } set { SetValue(DoesRotateWithTangentProperty, value); } } /// <summary> /// IsAdditive /// </summary> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValue(IsAdditiveProperty, value); } } /// <summary> /// IsAngleCumulative Property /// </summary> public static readonly DependencyProperty IsAngleCumulativeProperty = DependencyProperty.Register( "IsAngleCumulative", typeof(bool), typeof(MatrixAnimationUsingPath), new PropertyMetadata(false)); /// <summary> /// If this property is set to true, the rotation angle of the animated matrix /// will accumulate over repeats of the animation. For instance if /// your path is a small arc a cumulative angle will cause your object /// to continuously rotate with each repeat instead of restarting the /// rotation. When combined with IsOffsetCumulative, your object may /// appear to tumble while it bounces depending on your path. /// See <seealso cref="System.Windows.Media.Animation.MatrixAnimationUsingPath.IsOffsetCumulative">PathMatrixAnimation.IsOffsetCumulative</seealso> /// for related information. /// </summary> /// <value>default value: false</value> public bool IsAngleCumulative { get { return (bool)GetValue(IsAngleCumulativeProperty); } set { SetValue(IsAngleCumulativeProperty, value); } } /// <summary> /// IsOffsetCumulative Property /// </summary> public static readonly DependencyProperty IsOffsetCumulativeProperty = DependencyProperty.Register( "IsOffsetCumulative", typeof(bool), typeof(MatrixAnimationUsingPath), new PropertyMetadata(false)); /// <summary> /// If this property is set to true, the offset of the animated matrix /// will accumulate over repeats of the animation. For instance if /// your path is a small arc a cumulative offset will cause your object /// to appear to bounce once for each repeat. /// See <seealso cref="System.Windows.Media.Animation.MatrixAnimationUsingPath.IsAngleCumulative">PathMatrixAnimation.IsAngleCumulative</seealso> /// for related information. /// </summary> /// <value>default value: false</value> public bool IsOffsetCumulative { get { return (bool)GetValue(IsOffsetCumulativeProperty); } set { SetValue(IsOffsetCumulativeProperty, value); } } /// <summary> /// PathGeometry Property /// </summary> public static readonly DependencyProperty PathGeometryProperty = DependencyProperty.Register( "PathGeometry", typeof(PathGeometry), typeof(MatrixAnimationUsingPath), new PropertyMetadata( (PathGeometry)null)); /// <summary> /// This geometry specifies the path. /// </summary> public PathGeometry PathGeometry { get { return (PathGeometry)GetValue(PathGeometryProperty); } set { SetValue(PathGeometryProperty, value); } } #endregion #region MatrixAnimationBase /// <summary> /// Calculates the value this animation believes should be the current value for the property. /// </summary> /// <param name="defaultOriginValue"> /// This value is the suggested origin value provided to the animation /// to be used if the animation does not have its own concept of a /// start value. If this animation is the first in a composition chain /// this value will be the snapshot value if one is available or the /// base property value if it is not; otherise this value will be the /// value returned by the previous animation in the chain with an /// animationClock that is not Stopped. /// </param> /// <param name="defaultDestinationValue"> /// This value is the suggested destination value provided to the animation /// to be used if the animation does not have its own concept of an /// end value. This value will be the base value if the animation is /// in the first composition layer of animations on a property; /// otherwise this value will be the output value from the previous /// composition layer of animations for the property. /// </param> /// <param name="animationClock"> /// This is the animationClock which can generate the CurrentTime or /// CurrentProgress value to be used by the animation to generate its /// output value. /// </param> /// <returns> /// The value this animation believes should be the current value for the property. /// </returns> protected override Matrix GetCurrentValueCore(Matrix defaultOriginValue, Matrix defaultDestinationValue, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); PathGeometry pathGeometry = PathGeometry; if (pathGeometry == null) { return defaultDestinationValue; } if (!_isValid) { Validate(); } Point pathPoint; Point pathTangent; pathGeometry.GetPointAtFractionLength(animationClock.CurrentProgress.Value, out pathPoint, out pathTangent); double angle = 0.0; if (DoesRotateWithTangent) { angle = DoubleAnimationUsingPath.CalculateAngleFromTangentVector(pathTangent.X, pathTangent.Y); } Matrix matrix = new Matrix(); double currentRepeat = (double)(animationClock.CurrentIteration - 1); if (currentRepeat > 0) { if (IsOffsetCumulative) { pathPoint = pathPoint + (_accumulatingOffset * currentRepeat); } if ( DoesRotateWithTangent && IsAngleCumulative) { angle = angle + (_accumulatingAngle * currentRepeat); } } matrix.Rotate(angle); matrix.Translate(pathPoint.X, pathPoint.Y); if (IsAdditive) { return Matrix.Multiply(matrix, defaultOriginValue); } else { return matrix; } } #endregion #region Private Methods private void Validate() { Debug.Assert(!_isValid); if ( IsOffsetCumulative || IsAngleCumulative) { Point startPoint; Point startTangent; Point endPoint; Point endTangent; PathGeometry pathGeometry = PathGeometry; // Get values at the beginning of the path. pathGeometry.GetPointAtFractionLength(0.0, out startPoint, out startTangent); // Get values at the end of the path. pathGeometry.GetPointAtFractionLength(1.0, out endPoint, out endTangent); // Calculate difference. _accumulatingAngle = DoubleAnimationUsingPath.CalculateAngleFromTangentVector(endTangent.X, endTangent.Y) - DoubleAnimationUsingPath.CalculateAngleFromTangentVector(startTangent.X, startTangent.Y); _accumulatingOffset.X = endPoint.X - startPoint.X; _accumulatingOffset.Y = endPoint.Y - startPoint.Y; } _isValid = true; } #endregion } }
#pragma warning disable 109, 114, 219, 429, 168, 162 public class StringBuf : global::haxe.lang.HxObject { public StringBuf(global::haxe.lang.EmptyObject empty) { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" { } } #line default } public StringBuf() { unchecked { #line 29 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" global::StringBuf.__hx_ctor__StringBuf(this); } #line default } public static void __hx_ctor__StringBuf(global::StringBuf __temp_me10) { unchecked { #line 30 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" __temp_me10.b = new global::System.Text.StringBuilder(); } #line default } public static new object __hx_createEmpty() { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return new global::StringBuf(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return new global::StringBuf(); } #line default } public global::System.Text.StringBuilder b; public virtual void addSub(string s, int pos, global::haxe.lang.Null<int> len) { unchecked { #line 42 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" int l = default(int); #line 42 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" if (global::haxe.lang.Runtime.eq((len).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) { #line 42 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" l = ( s.Length - pos ); } else { #line 42 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" l = len.@value; } this.b.Append(global::haxe.lang.Runtime.toString(s), ((int) (pos) ), ((int) (l) )); } #line default } public virtual string toString() { unchecked { #line 51 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return this.b.ToString(); } #line default } public override object __hx_setField(string field, int hash, object @value, bool handleProperties) { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" switch (hash) { case 98: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" this.b = ((global::System.Text.StringBuilder) (@value) ); #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return @value; } default: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return base.__hx_setField(field, hash, @value, handleProperties); } } } #line default } public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties) { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" switch (hash) { case 946786476: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("toString"), ((int) (946786476) ))) ); } case 520665567: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("addSub"), ((int) (520665567) ))) ); } case 98: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return this.b; } default: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties); } } } #line default } public override object __hx_invokeField(string field, int hash, global::Array dynargs) { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" switch (hash) { case 946786476: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return this.toString(); } case 520665567: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" this.addSub(global::haxe.lang.Runtime.toString(dynargs[0]), ((int) (global::haxe.lang.Runtime.toInt(dynargs[1])) ), global::haxe.lang.Null<object>.ofDynamic<int>(dynargs[2])); #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" break; } default: { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return base.__hx_invokeField(field, hash, dynargs); } } #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" return default(object); } #line default } public override void __hx_getFields(global::Array<object> baseArr) { unchecked { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" baseArr.push("b"); #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" { #line 23 "C:\\HaxeToolkit\\haxe\\std/cs/_std/StringBuf.hx" base.__hx_getFields(baseArr); } } #line default } public override string ToString() { return this.toString(); } }