context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Build.Tasks.Xaml { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using XamlBuildTask; [Fx.Tag.XamlVisible(true)] public class CompilationPass2Task : Task { List<ITaskItem> generatedCodeFiles = new List<ITaskItem>(); // We will do Dev10 behavior if NONE of the new required properties are specified. This can happen // if a Dev10 version of the Microsoft.Xaml.Targets file is being used with Dev11 installed. // The new required properties for Dev11 are: // Language // OutputPath // MSBuildProjectDirectory // ApplicationMarkupWithTypeName // // If ANY of these are specified, then ALL must be specified. bool supportExtensions = false; string language; string outputPath; string msBuildProjectDirectory; ITaskItem[] applicationMarkupWithTypeName; public CompilationPass2Task() { } [Fx.Tag.KnownXamlExternal] public ITaskItem[] ApplicationMarkup { get; set; } public string AssemblyName { get; set; } [Fx.Tag.KnownXamlExternal] public ITaskItem[] References { get; set; } // Required in Dev11, but for backward compatibility with a Dev10 targets file, not marking as required. public string Language { get { return this.language; } set { this.language = value; this.supportExtensions = true; } } // Required in Dev11, but for backward compatibility with a Dev10 targets file, not marking as required. public string OutputPath { get { return this.outputPath; } set { this.outputPath = value; this.supportExtensions = true; } } // Required in Dev11, but for backward compatibility with a Dev10 targets file, not marking as required. public string MSBuildProjectDirectory { get { return this.msBuildProjectDirectory; } set { this.msBuildProjectDirectory = value; this.supportExtensions = true; } } public bool IsInProcessXamlMarkupCompile { get; set; } [Fx.Tag.KnownXamlExternal] public ITaskItem[] SourceCodeFiles { get; set; } public ITaskItem[] XamlBuildTypeInspectionExtensionNames { get; set; } // Required in Dev11, but for backward compatibility with a Dev10 targets file, not marking as required. public ITaskItem[] ApplicationMarkupWithTypeName { get { return this.applicationMarkupWithTypeName; } set { this.applicationMarkupWithTypeName = value; this.supportExtensions = true; } } public string LocalAssemblyReference { get; set; } public string RootNamespace { get; set; } public string BuildTaskPath { get; set; } [Output] public ITaskItem[] ExtensionGeneratedCodeFiles { get { return generatedCodeFiles.ToArray(); } set { generatedCodeFiles = new List<ITaskItem>(value); } } public override bool Execute() { AppDomain appDomain = null; try { ValidateRequiredDev11Properties(); appDomain = XamlBuildTaskServices.CreateAppDomain("CompilationPass2AppDomain_" + Guid.NewGuid(), BuildTaskPath); CompilationPass2TaskInternal wrapper = (CompilationPass2TaskInternal)appDomain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, typeof(CompilationPass2TaskInternal).FullName); PopulateBuildArtifacts(wrapper); bool ret = wrapper.Execute(); ExtractBuiltArtifacts(wrapper); if (!ret) { foreach (LogData logData in wrapper.LogData) { XamlBuildTaskServices.LogException( this.Log, logData.Message, logData.FileName, logData.LineNumber, logData.LinePosition); } } return ret; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } XamlBuildTaskServices.LogException(this.Log, e.Message); return false; } finally { if (appDomain != null) { AppDomain.Unload(appDomain); } } } string SeparateWithComma(string originalString, string stringToAppend) { if (!String.IsNullOrEmpty(originalString)) { return String.Join(", ", originalString, stringToAppend); } else { return stringToAppend; } } void ValidateRequiredDev11Properties() { if (this.supportExtensions) { string requiredPropertiesNotSpecified = ""; if (this.language == null) { requiredPropertiesNotSpecified = SeparateWithComma(requiredPropertiesNotSpecified, "Language"); } if (this.outputPath == null) { requiredPropertiesNotSpecified = SeparateWithComma(requiredPropertiesNotSpecified, "OutputPath"); } if (this.msBuildProjectDirectory == null) { requiredPropertiesNotSpecified = SeparateWithComma(requiredPropertiesNotSpecified, "MSBuildProjectDirectory"); } if (this.applicationMarkupWithTypeName == null) { requiredPropertiesNotSpecified = SeparateWithComma(requiredPropertiesNotSpecified, "ApplicationMarkupWithTypeName"); } if (!String.IsNullOrEmpty(requiredPropertiesNotSpecified)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.MissingRequiredParametersCompilationPass2Task(requiredPropertiesNotSpecified))); } } } void PopulateBuildArtifacts(CompilationPass2TaskInternal wrapper) { if (!this.supportExtensions) { IList<string> applicationMarkup = new List<string>(this.ApplicationMarkup.Length); foreach (ITaskItem taskItem in this.ApplicationMarkup) { applicationMarkup.Add(taskItem.ItemSpec); } wrapper.ApplicationMarkup = applicationMarkup; } wrapper.SupportExtensions = this.supportExtensions; wrapper.BuildLogger = this.Log; wrapper.References = this.References .Select(i => new DelegatingTaskItem(i) as ITaskItem).ToList(); wrapper.LocalAssemblyReference = this.LocalAssemblyReference; wrapper.AssemblyName = this.AssemblyName; wrapper.RootNamespace = this.RootNamespace; wrapper.Language = this.Language; wrapper.OutputPath = this.OutputPath; wrapper.IsInProcessXamlMarkupCompile = this.IsInProcessXamlMarkupCompile; wrapper.MSBuildProjectDirectory = this.MSBuildProjectDirectory; IList<string> sourceCodeFiles = null; if (this.SourceCodeFiles != null) { sourceCodeFiles = new List<string>(this.SourceCodeFiles.Length); foreach (ITaskItem taskItem in this.SourceCodeFiles) { sourceCodeFiles.Add(taskItem.ItemSpec); } } wrapper.SourceCodeFiles = sourceCodeFiles; if (this.supportExtensions) { wrapper.XamlBuildTaskTypeInspectionExtensionNames = XamlBuildTaskServices.GetXamlBuildTaskExtensionNames(this.XamlBuildTypeInspectionExtensionNames); // Here we create a Dictionary of Type Full Name and corresponding TaskItem // This is passed to the extensions which enables them to look up // metadata about a type like file name. IDictionary<string, ITaskItem> applicationMarkupWithTypeName = null; if (this.ApplicationMarkupWithTypeName != null) { applicationMarkupWithTypeName = new Dictionary<string, ITaskItem>(); } foreach (ITaskItem taskItem in this.ApplicationMarkupWithTypeName) { string typeName = taskItem.GetMetadata("typeName"); if (!String.IsNullOrWhiteSpace(typeName)) { applicationMarkupWithTypeName.Add(typeName, new DelegatingTaskItem(taskItem)); } } wrapper.ApplicationMarkupWithTypeName = applicationMarkupWithTypeName; } } void ExtractBuiltArtifacts(CompilationPass2TaskInternal wrapper) { if (wrapper.GeneratedCodeFiles == null) { return; } foreach (string code in wrapper.GeneratedCodeFiles) { this.generatedCodeFiles.Add(new TaskItem(code)); } } } }
using System; using System.Runtime.InteropServices; using System.IO; using System.ComponentModel; namespace Vulkan { public static partial class VK { public const string VulkanLibrary = "vulkan-1.dll"; static DllLoader theDll; static VK() { theDll = new DllLoader(VulkanLibrary); } #region allocation callback functions [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr AllocationFunction(IntPtr userData, UInt64 size, UInt64 alignment, SystemAllocationScope allocationScope); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr ReallocationFunction(IntPtr userData, IntPtr original, UInt64 size, UInt64 alignment, SystemAllocationScope allocationScope); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr FreeFunction(IntPtr userData, IntPtr memory); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr InternalAllocationNotification(IntPtr userData, UInt64 size, InternalAllocationType allocationType, SystemAllocationScope allocationScope); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr InternalFreeNotification(IntPtr userData, UInt64 size, InternalAllocationType allocationType, SystemAllocationScope allocationScope); #endregion #region defines public static Semaphore NULL_SEMAPHORE = new Semaphore(); public static Fence NULL_FENCE = new Fence(); public static int NULL_HANDLE = 0; public const float LOD_CLAMP_NONE = 1000.0f; public const UInt32 REMAINING_MIP_LEVELS = (~0U); public const UInt32 REMAINING_ARRAY_LAYERS = (~0U); public const UInt64 WHOLE_SIZE = (~0UL); public const UInt32 ATTACHMENT_UNUSED = (~0U); public const UInt32 TRUE = 1; public const UInt32 FALSE = 0; public const UInt32 QUEUE_FAMILY_IGNORED = (~0U); public const UInt32 SUBPASS_EXTERNAL = (~0U); public const UInt32 MAX_PHYSICAL_DEVICE_NAME_SIZE = 256; public const UInt32 UUID_SIZE = 16; public const UInt32 MAX_MEMORY_TYPES = 32; public const UInt32 MAX_MEMORY_HEAPS = 16; public const UInt32 MAX_EXTENSION_NAME_SIZE = 256; public const UInt32 MAX_DESCRIPTION_SIZE = 256; //vulkan 1.1 public const UInt32 MAX_DEVICE_GROUP_SIZE = 32; public const UInt32 LUID_SIZE = 8; public const UInt32 QUEUE_FAMILY_EXTERNAL = (~0U - 1); #endregion } #region Extension and Layer Names public partial class InstanceExtensions { //these are populated by the extensions in the extensions folder } public partial class InstanceLayers { public const string VK_LAYER_LUNARG_standard_validation = "VK_LAYER_LUNARG_standard_validation"; } public partial class DeviceExtensions { //these are populated by the extensions in the extensions folder } #endregion #region Helper classes public class Version { public static uint Make(uint major, uint minor, uint patch) { return (major << 22) | (minor << 12) | patch; } public static string ToString(uint version) { return string.Format("{0}.{1}.{2}", version >> 22, (version >> 12) & 0x3ff, version & 0xfff); } } [StructLayout(LayoutKind.Sequential)] public struct Bool32 { UInt32 value; public Bool32(bool bValue) { value = bValue ? 1u : 0; } public static implicit operator Bool32(bool bValue) { return new Bool32(bValue); } public static implicit operator bool(Bool32 bValue) { return bValue.value == 0 ? false : true; } public override string ToString() { bool b = value == 1 ? true : false; return b.ToString(); } } [StructLayout(LayoutKind.Sequential)] public struct DeviceSize { UInt64 value; public static implicit operator DeviceSize(UInt64 iValue) { return new DeviceSize { value = iValue }; } public static implicit operator DeviceSize(uint iValue) { return new DeviceSize { value = iValue }; } public static implicit operator DeviceSize(int iValue) { return new DeviceSize { value = (ulong)iValue }; } public static implicit operator UInt64(DeviceSize size) { return size.value; } } [StructLayout(LayoutKind.Sequential)] public struct DeviceAddress { UInt64 value; public static implicit operator DeviceAddress(UInt64 iValue) { return new DeviceAddress { value = iValue }; } public static implicit operator DeviceAddress(uint iValue) { return new DeviceAddress { value = iValue }; } public static implicit operator DeviceAddress(int iValue) { return new DeviceAddress { value = (ulong)iValue }; } public static implicit operator UInt64(DeviceAddress size) { return size.value; } } #endregion #region DLL Loading public class DllLoader { IntPtr myDllPtr { get; set; } public DllLoader(String dllName) { loadSystemDll(dllName); } /// <summary> /// Loads a dll into process memory. /// </summary> /// <param name="lpFileName">Filename to load.</param> /// <returns>Pointer to the loaded library.</returns> /// <remarks> /// This method is used to load a dll into memory, before calling any of it's DllImported methods. /// /// This is done to allow loading an x86 version of a dllfor an x86 process, or an x64 version of it /// for an x64 process. /// </remarks> [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)] public static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]String lpFileName); /// <summary> /// Frees a previously loaded dll, from process memory. /// </summary> /// <param name="hModule">Pointer to the previously loaded library (This pointer comes from a call to LoadLibrary).</param> /// <returns>Returns true if the library was successfully freed.</returns> [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FreeLibrary(IntPtr hModule); /// <summary> /// This method is used to load the dll into memory, before calling any of it's DllImported methods. /// /// This is done to allow loading an x86 or x64 version of the dll depending on the process /// </summary> private IntPtr loadDll(String dllName) { if (myDllPtr == IntPtr.Zero) { // Retrieve the folder of the OculusWrap.dll. string executingAssemblyFolder = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string subfolder; if (Environment.Is64BitProcess) subfolder = "x64"; else subfolder = "x32"; string filename = Path.Combine(executingAssemblyFolder, subfolder, dllName); // Check that the dll file exists. bool exists = File.Exists(filename); if (!exists) throw new DllNotFoundException("Unable to load the file \"" + filename + "\", the file wasn't found."); myDllPtr = LoadLibrary(filename); if (myDllPtr == IntPtr.Zero) { int win32Error = Marshal.GetLastWin32Error(); throw new Win32Exception(win32Error, "Unable to load the file \"" + filename + "\", LoadLibrary reported error code: " + win32Error + "."); } } return myDllPtr; } private IntPtr loadSystemDll(String dllName) { myDllPtr = LoadLibrary(dllName); return myDllPtr; } /// <summary> /// Frees previously loaded dll, from process memory. /// </summary> private IntPtr UnloadDll() { if (myDllPtr != IntPtr.Zero) { bool success = FreeLibrary(myDllPtr); if (success) myDllPtr = IntPtr.Zero; } return IntPtr.Zero; } }; #endregion }
using UnityEngine; using System; using System.Collections; using System.Reflection; using System.Collections.Generic; using UnityEditor; using UMA; [CustomEditor(typeof(DynamicDNAConverterBehaviour), true)] public class DynamicDNAConverterBehaviourEditor : Editor { private DynamicDNAConverterBehaviour thisDDCB; private SkeletonModifierPropertyDrawer _skelModPropDrawer = null; private List<string> hashNames = new List<string>(); private List<int> hashes = new List<int>(); private string newHashName = ""; private int selectedAddHash = 0; private string addSkelBoneName = ""; private int addSkelBoneHash = 0; private int selectedAddProp = 0; bool canAddSkel = false; bool alreadyExistedSkel = false; private Dictionary<string, Vector3> skelAddDefaults = new Dictionary<string, Vector3> { {"Position", new Vector3(0f,-0.1f, 0.1f) }, {"Rotation", new Vector3(0f,-360f, 360f) }, {"Scale", new Vector3(1f,0f, 5f) } }; private string boneHashFilter = ""; private string skeletonModifiersFilter = ""; private int skeletonModifiersFilterType = 0; private string[] skeletonModifiersFilterTypeList = new string[] { "Bone Name", "Position Modifiers", "Rotation Modifiers", "Scale Modifiers", "DNA", "Adjust Bones", "Non-Adjust Bones" }; public bool enableSkelModValueEditing = false; //minimalMode is the mode that is used when a DynamicDnaConverterBehaviour is shown in a DynamicDnaConverterCustomizer rather than when its inspected directly public bool minimalMode = false; // //Optional component refrences public UMAData umaData = null; //DynamicDNAConverterCustomizer public DynamicDNAConverterCustomizer thisDDCC = null; //UMABonePose Editor private Editor thisUBP = null; public string createBonePoseAssetName = ""; //DynamicUMADNAAsset Editor private Editor thisDUDA = null; public string createDnaAssetName = ""; // [System.NonSerialized] public bool initialized = false; private void Init() { thisDDCB = target as DynamicDNAConverterBehaviour; if (_skelModPropDrawer == null) _skelModPropDrawer = new SkeletonModifierPropertyDrawer(); if (minimalMode == false) { bool doUpdate = thisDDCB.SetCurrentAssetPath(); if (doUpdate) { EditorUtility.SetDirty(target); AssetDatabase.SaveAssets(); } } // hashNames.Clear(); hashes.Clear(); SerializedProperty hashList = serializedObject.FindProperty("hashList"); for (int i = 0; i < hashList.arraySize; i++) { hashNames.Add(hashList.GetArrayElementAtIndex(i).FindPropertyRelative("hashName").stringValue); hashes.Add(hashList.GetArrayElementAtIndex(i).FindPropertyRelative("hash").intValue); } UpdateDnaNames(); initialized = true; } void UpdateHashNames() { hashNames.Clear(); hashes.Clear(); SerializedProperty hashList = serializedObject.FindProperty("hashList"); for (int i = 0; i < hashList.arraySize; i++) { hashNames.Add(hashList.GetArrayElementAtIndex(i).FindPropertyRelative("hashName").stringValue); hashes.Add(hashList.GetArrayElementAtIndex(i).FindPropertyRelative("hash").intValue); } _skelModPropDrawer.UpdateHashNames(hashNames, hashes); } void UpdateDnaNames() { string[] dnaNames = null; SerializedProperty dnaAssetProp = serializedObject.FindProperty("dnaAsset"); if (dnaAssetProp != null) { DynamicUMADnaAsset dnaAsset = dnaAssetProp.objectReferenceValue as DynamicUMADnaAsset; if (dnaAsset != null) _skelModPropDrawer.Init(hashNames, hashes, dnaAsset.Names); else _skelModPropDrawer.Init(hashNames, hashes, dnaNames); } else { _skelModPropDrawer.Init(hashNames, hashes, dnaNames); } } public override void OnInspectorGUI() { serializedObject.Update(); if (!initialized) this.Init(); EditorGUI.BeginDisabledGroup(true); //REMOVE FOR RELEASE- this currently outputs the hidden fields used to check the DNATypeHash is being set correctly- the methods in the converter make it so the typehash only changes if the asset is duplicated if (!minimalMode) Editor.DrawPropertiesExcluding(serializedObject, new string[] { "dnaAsset", "startingPose", "startingPoseWeight", "hashList", "skeletonModifiers", "overallModifiersEnabled", "overallScale", "heightModifiers", "radiusModifier", "massModifiers" }); EditorGUI.EndDisabledGroup(); //Style for Tips var foldoutTipStyle = new GUIStyle(EditorStyles.foldout); foldoutTipStyle.fontStyle = FontStyle.Bold; //=============================================// //===========BONEPOSE ASSET AND EDITOR===========// serializedObject.FindProperty("startingPoseWeight").isExpanded = EditorGUILayout.Foldout(serializedObject.FindProperty("startingPoseWeight").isExpanded, "Starting Pose", foldoutTipStyle); if (serializedObject.FindProperty("startingPoseWeight").isExpanded) { EditorGUILayout.HelpBox("The 'Starting Pose'is the initial position/rotation/scale of all the bones in this Avatar's skeleton. Use this to completely transform the mesh of your character. You could (for example) transform standard UMA characters into a backwards compatible 'Short Squat Dwarf' or a 'Bobble- headded Toon'. Optionally, you can create an UMABonePose asset from an FBX model using the UMA > Pose Tools > Bone Pose Builder and add the resulting asset here. After you have added or created a UMABonePose asset, you can add and edit the position, rotation and scale settings for any bone in the active character's skeleton in the 'Bone Poses' section. You can also create bone poses automatically from the Avatar's current dna modified state using the 'Create poses from Current DNA state button'.", MessageType.Info); } EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPose"), new GUIContent("Starting UMABonePose", "Define an asset that will set the starting bone poses of any Avatar using this converter")); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } //Draw the poses array from the Asset if set or show controls to create a new asset. SerializedProperty bonePoseAsset = serializedObject.FindProperty("startingPose"); EditorGUI.indentLevel++; if (bonePoseAsset.objectReferenceValue != null) { EditorGUILayout.PropertyField(serializedObject.FindProperty("startingPoseWeight")); if (thisUBP == null) { thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePoseAsset.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor)); ((UMA.PoseTools.UMABonePoseEditor)thisUBP).Init(); ((UMA.PoseTools.UMABonePoseEditor)thisUBP).minimalMode = true; if (umaData != null) ((UMA.PoseTools.UMABonePoseEditor)thisUBP).umaData = umaData; } else if (thisUBP.target != (UMA.PoseTools.UMABonePose)bonePoseAsset.objectReferenceValue) { thisUBP = Editor.CreateEditor((UMA.PoseTools.UMABonePose)bonePoseAsset.objectReferenceValue, typeof(UMA.PoseTools.UMABonePoseEditor)); ((UMA.PoseTools.UMABonePoseEditor)thisUBP).Init(); ((UMA.PoseTools.UMABonePoseEditor)thisUBP).minimalMode = true; if (umaData != null) ((UMA.PoseTools.UMABonePoseEditor)thisUBP).umaData = umaData; } EditorGUI.BeginChangeCheck(); thisUBP.OnInspectorGUI(); if (EditorGUI.EndChangeCheck()) { //Currently we dont need to do anything here as the change is picked up by DynamicDNAConverterCustomizer an this triggers an UMA update //this may change though if we have a method in future for modifying the TPose } } else { if (thisDDCC != null) { var createPoseAssetR = EditorGUILayout.GetControlRect(false); var createPoseAssetRLabel = createPoseAssetR; var createPoseAssetRField = createPoseAssetR; var createPoseAssetRButton = createPoseAssetR; createPoseAssetRLabel.width = createPoseAssetRLabel.width / 3 + 7; createPoseAssetRButton.width = 70f; createPoseAssetRField.width = ((createPoseAssetRField.width / 3) * 2) - 82; createPoseAssetRField.x = createPoseAssetRLabel.xMax; createPoseAssetRButton.x = createPoseAssetRField.xMax + 5; EditorGUI.LabelField(createPoseAssetRLabel, new GUIContent("Create BonePose Asset", "Create a new empty UMABonePose with the name of your choosing.")); createBonePoseAssetName = EditorGUI.TextField(createPoseAssetRField, createBonePoseAssetName); if (GUI.Button(createPoseAssetRButton, "Create It"))//need to do the button enabled thing here { var newDnaAsset = thisDDCC.CreatePoseAsset("", createBonePoseAssetName); if (newDnaAsset != null) { //set this asset as the used asset bonePoseAsset.objectReferenceValue = newDnaAsset; serializedObject.ApplyModifiedProperties(); createBonePoseAssetName = ""; } } } else { EditorGUILayout.HelpBox("Edit a character that uses this converter in the 'DynamicDna Converter Behaviour Customizer' scene and you can create a StartingPoseAsset automatically here", MessageType.Info); } } if (minimalMode && umaData.skeleton != null) { var createFromDnaButR = EditorGUILayout.GetControlRect(false); if (GUI.Button(createFromDnaButR, "Create poses from Current DNA state")) { if (thisDDCC != null) { if (thisDDCC.CreateBonePosesFromCurrentDna(createBonePoseAssetName)) { serializedObject.Update(); } } } } EditorGUI.indentLevel--; serializedObject.ApplyModifiedProperties(); //=============END BONEPOSE ASSET AND EDITOR============// // EditorGUILayout.Space(); // //=============DNA ASSET AND EDITOR============// serializedObject.FindProperty("dnaAsset").isExpanded = EditorGUILayout.Foldout(serializedObject.FindProperty("dnaAsset").isExpanded, "Dynamic DNA", foldoutTipStyle); if (serializedObject.FindProperty("dnaAsset").isExpanded) { EditorGUILayout.HelpBox("The DynmicDNAAsset specifies what dna sliders will be shown for this Avatar. How the values from these sliders affect the UMA's skelton is defined in the 'DNA Converter Settings' section below. You can create, assign and edit a DynamicDNAAsset here and edit the list of names which will show as sliders using the 'DNA Slider Names' section below. This gives you the power to add any extra DNA sliders you want, like a 'fingerLength' slider or an 'Eye Symetry' slider.", MessageType.Info); } EditorGUILayout.PropertyField(serializedObject.FindProperty("dnaAsset"), new GUIContent("Dynamic UMA DNA Asset", "A DynamicUMADnaAsset contains a list of names that define the dna sliders that an Avatar has.")); serializedObject.ApplyModifiedProperties(); SerializedProperty dnaAsset = serializedObject.FindProperty("dnaAsset"); EditorGUI.indentLevel++; if (dnaAsset.objectReferenceValue != null) { if (thisDUDA == null) { thisDUDA = Editor.CreateEditor((DynamicUMADnaAsset)dnaAsset.objectReferenceValue, typeof(UMAEditor.DynamicUMADnaAssetEditor)); } else if (thisDUDA.target != (DynamicUMADnaAsset)dnaAsset.objectReferenceValue) { thisDUDA = Editor.CreateEditor((DynamicUMADnaAsset)dnaAsset.objectReferenceValue, typeof(UMAEditor.DynamicUMADnaAssetEditor)); } EditorGUI.BeginChangeCheck(); thisDUDA.OnInspectorGUI(); if (EditorGUI.EndChangeCheck()) { UpdateDnaNames(); } } else { if (thisDDCC != null) { var createDnaAssetR = EditorGUILayout.GetControlRect(false); var createDnaAssetRLabel = createDnaAssetR; var createDnaAssetRField = createDnaAssetR; var createDnaAssetRButton = createDnaAssetR; createDnaAssetRLabel.width = createDnaAssetRLabel.width / 3 + 7; createDnaAssetRButton.width = 70f; createDnaAssetRField.width = ((createDnaAssetRField.width / 3) * 2) - 82; createDnaAssetRField.x = createDnaAssetRLabel.xMax; createDnaAssetRButton.x = createDnaAssetRField.xMax + 5; EditorGUI.LabelField(createDnaAssetRLabel, new GUIContent("Create DNA Asset", "Create a new DynamicUMADnaAsset with the name of your choosing and default UMADnaHumanoid sliders.")); createDnaAssetName = EditorGUI.TextField(createDnaAssetRField, createDnaAssetName); if (GUI.Button(createDnaAssetRButton, "Create It"))//need to do the button enabled thing here { var newDnaAsset = thisDDCC.CreateDNAAsset("", createDnaAssetName); if (newDnaAsset != null) { //set this asset as the used asset dnaAsset.objectReferenceValue = newDnaAsset; serializedObject.ApplyModifiedProperties(); createDnaAssetName = ""; } UpdateDnaNames(); } } else { EditorGUILayout.HelpBox("Edit a character that uses in the 'DynamicDna Converter Behaviour Customizer' scene and you can create a DynamicDNAAsset automatically here", MessageType.Info); } } EditorGUI.indentLevel--; serializedObject.ApplyModifiedProperties(); //===========END DNA ASSET AND EDITOR============// // EditorGUILayout.Space(); // //=============CONVERTER VALUES AND EDITOR=============// SerializedProperty hashList = serializedObject.FindProperty("hashList"); SerializedProperty skeletonModifiers = serializedObject.FindProperty("skeletonModifiers"); EditorGUI.indentLevel++; string converterTips = ""; if (minimalMode) { converterTips = "Skeleton Modifiers control how the values of any DNA Sliders are applied to the skeleton. So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. The best way to edit these modifiers is to set the DNA slider you want to adjust in the game view, to either its minimum or maximum position. Then add or edit the skeleton modifiers in the list below that use that value to modify the skeleton by the Min and Max values on the bone as a whole and how the incoming is multiplied. Avoid changing the starting 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this edit the starting pose above) instead."; } else { converterTips = "In this section you can control how the values of any DNA Sliders are applied to the skeleton. So for example 'Upper Weight' affects the scale of the Spine, breast, belly and shoulder bones in different ways. Add bones you wish to make available to modify in the 'BoneHashes' section. Then add or edit the skeleton modifiers in the 'Skeleton Modifiers' list to adjust how the bones are affected by that dna setting. Avoid changing the 'Value' as changes to this will persist even if the dna is not itself applied (if you want to do this edit the starting pose above) instead edit what the the Min and Max values an what any added dna is multiplied by."; } EditorGUI.indentLevel--; serializedObject.FindProperty("heightModifiers").isExpanded = EditorGUILayout.Foldout(serializedObject.FindProperty("heightModifiers").isExpanded, "DNA Converter Settings", foldoutTipStyle); if (serializedObject.FindProperty("heightModifiers").isExpanded) { EditorGUILayout.HelpBox(converterTips, MessageType.Info); } EditorGUI.indentLevel++; if (!minimalMode)//in minimal mode we dont need to show these because we will have a skeleton that we can get the bonehash list from { int hashListCount = hashList.arraySize; hashList.isExpanded = EditorGUILayout.Foldout(hashList.isExpanded, "Bone Hash List (" + hashListCount + ")"); if (hashList.isExpanded) { EditorGUI.indentLevel++; //Search Bone Hashes Controls boneHashFilter = EditorGUILayout.TextField("Search Bones", boneHashFilter); for (int i = 0; i < hashList.arraySize; i++) { var thisHashEl = hashList.GetArrayElementAtIndex(i); //Search Bone Hashes Method if (boneHashFilter.Length >= 3) { if (thisHashEl.displayName.IndexOf(boneHashFilter, StringComparison.CurrentCultureIgnoreCase) == -1) continue; } EditorGUILayout.BeginHorizontal(); thisHashEl.isExpanded = EditorGUILayout.Foldout(thisHashEl.isExpanded, thisHashEl.displayName); //DeleteButton Rect hDelButR = EditorGUILayout.GetControlRect(false); hDelButR.x = hDelButR.x + hDelButR.width - 100f; hDelButR.width = 100f; if (GUI.Button(hDelButR, "Delete")) { hashList.DeleteArrayElementAtIndex(i); continue; } EditorGUILayout.EndHorizontal(); if (thisHashEl.isExpanded) { EditorGUI.indentLevel++; string origName = thisHashEl.FindPropertyRelative("hashName").stringValue; string newName = origName; EditorGUI.BeginChangeCheck(); newName = EditorGUILayout.TextField("Hash Name", origName); if (EditorGUI.EndChangeCheck()) { if (newName != origName && newName != "") { thisHashEl.FindPropertyRelative("hashName").stringValue = newName; int newHash = UMAUtils.StringToHash(newName); thisHashEl.FindPropertyRelative("hash").intValue = newHash; serializedObject.ApplyModifiedProperties(); } } EditorGUI.BeginDisabledGroup(true); EditorGUILayout.IntField("Hash", thisHashEl.FindPropertyRelative("hash").intValue); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; } } hashList.serializedObject.ApplyModifiedProperties(); EditorGUILayout.Space(); //create an add field for adding new hashes EditorGUILayout.BeginHorizontal(); var buttonDisabled = newHashName == ""; bool canAdd = true; bool notFoundInSkeleton = false; bool didAdd = false; EditorGUI.BeginChangeCheck(); newHashName = EditorGUILayout.TextField(newHashName); if (EditorGUI.EndChangeCheck()) { if (newHashName != "" && canAdd) { buttonDisabled = false; } } if (newHashName != "") { for (int ni = 0; ni < hashList.arraySize; ni++) { if (hashList.GetArrayElementAtIndex(ni).FindPropertyRelative("hashName").stringValue == newHashName) { canAdd = false; buttonDisabled = true; } } //if we have a skeleton available we can also check that the bone the user is trying to add exists if (umaData.skeleton != null) { if (umaData.skeleton.HasBone(UMAUtils.StringToHash(newHashName)) == false) { canAdd = false; buttonDisabled = true; notFoundInSkeleton = true; } } } if (buttonDisabled) { EditorGUI.BeginDisabledGroup(true); } if (GUILayout.Button("Add Bone Hash")) { if (canAdd) { var newHash = UMAUtils.StringToHash(newHashName); var numhashes = hashList.arraySize; hashList.InsertArrayElementAtIndex(numhashes); hashList.serializedObject.ApplyModifiedProperties(); hashList.GetArrayElementAtIndex(numhashes).FindPropertyRelative("hashName").stringValue = newHashName; hashList.GetArrayElementAtIndex(numhashes).FindPropertyRelative("hash").intValue = newHash; hashList.serializedObject.ApplyModifiedProperties(); didAdd = true; UpdateHashNames(); } } if (buttonDisabled) { EditorGUI.EndDisabledGroup(); } EditorGUILayout.EndHorizontal(); if (canAdd == false) { if (notFoundInSkeleton == true) { EditorGUILayout.HelpBox("That name was not found in the skeleton. (Standard Bone names start with a capital letter in CamelCase)", MessageType.Warning); } else { EditorGUILayout.HelpBox("That name is already in use.", MessageType.Warning); } } if (didAdd) { newHashName = ""; } EditorGUI.indentLevel--; } } int skeletonModifiersCount = skeletonModifiers.arraySize; skeletonModifiers.isExpanded = EditorGUILayout.Foldout(skeletonModifiers.isExpanded, "Skeleton Modifiers (" + skeletonModifiersCount + ")"); if (skeletonModifiers.isExpanded) { EditorGUI.indentLevel++; //Search Filters Controls Rect searchR = EditorGUILayout.GetControlRect(); var searchL = searchR; var searchF = searchR; var searchTL = searchR; var searchTF = searchR; searchL.width = 130; searchF.width = (searchR.width / 3) * 2 - searchL.width; searchF.x = searchR.x + searchL.width; searchTL.width = 35; searchTL.x = searchF.xMax; searchTF.width = (searchR.width / 3) - searchTL.width - 5; searchTF.x = searchTL.xMax; EditorGUI.LabelField(searchL, "Search Modifiers"); EditorGUI.indentLevel--; skeletonModifiersFilter = EditorGUI.TextField(searchF, skeletonModifiersFilter); EditorGUI.LabelField(searchTL, "By"); skeletonModifiersFilterType = EditorGUI.Popup(searchTF, skeletonModifiersFilterType, skeletonModifiersFilterTypeList); EditorGUI.indentLevel++; for (int i = 0; i < skeletonModifiers.arraySize; i++) { var thisSkelEl = skeletonModifiers.GetArrayElementAtIndex(i); //Search Filters Method if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA") { if (skeletonModifiersFilterType == 1 || skeletonModifiersFilterType == 2 || skeletonModifiersFilterType == 3) { string thisProperty = thisSkelEl.FindPropertyRelative("property").enumNames[thisSkelEl.FindPropertyRelative("property").enumValueIndex]; if (skeletonModifiersFilterType == 1)//Position Modifiers { if (thisProperty.IndexOf("position", StringComparison.CurrentCultureIgnoreCase) == -1) continue; } else if (skeletonModifiersFilterType == 2)//Rotation Modifiers { if (thisProperty.IndexOf("rotation", StringComparison.CurrentCultureIgnoreCase) == -1) continue; } else if (skeletonModifiersFilterType == 3)//scale Modifiers { if (thisProperty.IndexOf("scale", StringComparison.CurrentCultureIgnoreCase) == -1) continue; } } else if (skeletonModifiersFilterType == 5)//Adjust Bones { if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) == -1) continue; } else if (skeletonModifiersFilterType == 6)//Non Adjust Bones { if (thisSkelEl.displayName.IndexOf("adjust", StringComparison.CurrentCultureIgnoreCase) > -1) continue; } } if (skeletonModifiersFilter.Length >= 3) { if (skeletonModifiersFilterTypeList[skeletonModifiersFilterType] != "DNA") { if (thisSkelEl.displayName.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) == -1) continue; } else //Searches for Modifiers that use a given DNA Value- slow but super handy { string[] XYZ = new string[] { "X", "Y", "Z" }; SerializedProperty mods; SerializedProperty thisMod; int modsi; bool _continue = true; foreach (string xyz in XYZ) { mods = thisSkelEl.FindPropertyRelative("values" + xyz).FindPropertyRelative("val").FindPropertyRelative("modifiers"); for (int mi = 0; mi < mods.arraySize; mi++) { thisMod = mods.GetArrayElementAtIndex(mi); modsi = thisMod.FindPropertyRelative("modifier").enumValueIndex; if (modsi > 3) { if (thisMod.FindPropertyRelative("DNATypeName").stringValue.IndexOf(skeletonModifiersFilter, StringComparison.CurrentCultureIgnoreCase) > -1) _continue = false; } } } if (_continue) { continue; } } } Rect currentRect = EditorGUILayout.GetControlRect(false, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none)); //Delete button Rect sDelButR = currentRect; sDelButR.x = sDelButR.x + sDelButR.width - 100f; sDelButR.width = 100f; sDelButR.height = EditorGUIUtility.singleLineHeight; if (GUI.Button(sDelButR, "Delete")) { skeletonModifiers.DeleteArrayElementAtIndex(i); continue; } Rect thisSkelRect = new Rect(currentRect.xMin, currentRect.yMin, currentRect.width, _skelModPropDrawer.GetPropertyHeight(thisSkelEl, GUIContent.none)); _skelModPropDrawer.OnGUI(thisSkelRect, thisSkelEl, new GUIContent(thisSkelEl.displayName)); } //we want to discourage users from using the starting values to customise their models _skelModPropDrawer.enableSkelModValueEditing = enableSkelModValueEditing = EditorGUILayout.ToggleLeft("Enable editing of starting Value (not reccommended)", enableSkelModValueEditing); //and make it easy to set the starting values back to the defaults if (GUILayout.Button("Reset All Starting Values to Default")) { for (int i = 0; i < skeletonModifiers.arraySize; i++) { var thisSkeModProp = skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumNames[skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("property").enumValueIndex]; if (thisSkeModProp != "") { if (thisSkeModProp == "Position" || thisSkeModProp == "Rotation") { skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f; skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f; skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 0f; } if (thisSkeModProp == "Scale") { skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f; skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f; skeletonModifiers.GetArrayElementAtIndex(i).FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = 1f; } } } skeletonModifiers.serializedObject.ApplyModifiedProperties(); } //Add a new Skeleton Modifier EditorGUI.BeginDisabledGroup(true); EditorGUILayout.LabelField("Add Modifier"); EditorGUI.EndDisabledGroup(); Rect addSkelButsR = EditorGUILayout.GetControlRect(false); var addSkelLabel = addSkelButsR; var addSkelBone = addSkelButsR; var addSkelProp = addSkelButsR; var addSkelAddBut = addSkelButsR; addSkelLabel.width = 100; addSkelAddBut.width = 70; addSkelBone.width = addSkelProp.width = (addSkelButsR.width - (addSkelLabel.width + (addSkelAddBut.width + 5))) / 2; addSkelBone.x = addSkelLabel.xMax; addSkelProp.x = addSkelBone.xMax; addSkelAddBut.x = addSkelProp.xMax + 5; EditorGUI.LabelField(addSkelLabel, "Bone Name"); EditorGUI.indentLevel--; List<string> thisBoneNames = new List<string>(0); EditorGUI.BeginChangeCheck(); if (minimalMode == false) { selectedAddHash = EditorGUI.Popup(addSkelBone, selectedAddHash, hashNames.ToArray()); } else { var boneNames = umaData.skeleton.BoneNames; Array.Sort(boneNames); thisBoneNames = new List<string>(boneNames); thisBoneNames.Insert(0, "ChooseBone"); selectedAddHash = EditorGUI.Popup(addSkelBone, selectedAddHash, thisBoneNames.ToArray()); } string[] propertyArray = new string[] { "Position", "Rotation", "Scale" }; selectedAddProp = EditorGUI.Popup(addSkelProp, selectedAddProp, propertyArray); if (EditorGUI.EndChangeCheck()) { if (minimalMode == false) { //we will have an int that relates to a hashName and hash value addSkelBoneName = hashNames[selectedAddHash]; addSkelBoneHash = hashes[selectedAddHash]; } else { //otherwise we will have selected a bone from the bone names popup if (selectedAddHash > 0) { addSkelBoneName = thisBoneNames[selectedAddHash]; addSkelBoneHash = UMAUtils.StringToHash(addSkelBoneName); } else { addSkelBoneName = ""; addSkelBoneHash = 0; canAddSkel = false; } } } if (addSkelBoneName != "" && addSkelBoneHash != 0) { canAddSkel = true; alreadyExistedSkel = false; //we need to check if there is already a modifier for that bone for the selected property for (int i = 0; i < skeletonModifiers.arraySize; i++) { var thisSkelMod = skeletonModifiers.GetArrayElementAtIndex(i); if (thisSkelMod.FindPropertyRelative("property").enumValueIndex == selectedAddProp && thisSkelMod.FindPropertyRelative("hash").intValue == addSkelBoneHash) { canAddSkel = false; alreadyExistedSkel = true; } } } if (canAddSkel == false) { EditorGUI.BeginDisabledGroup(true); } if (GUI.Button(addSkelAddBut, "Add It!")) { if (minimalMode) { if (!hashes.Contains(addSkelBoneHash)) { var numhashes = hashList.arraySize; hashList.InsertArrayElementAtIndex(numhashes); hashList.serializedObject.ApplyModifiedProperties(); hashList.GetArrayElementAtIndex(numhashes).FindPropertyRelative("hashName").stringValue = addSkelBoneName; hashList.GetArrayElementAtIndex(numhashes).FindPropertyRelative("hash").intValue = addSkelBoneHash; hashList.serializedObject.ApplyModifiedProperties(); UpdateHashNames(); } } var numSkelMods = skeletonModifiers.arraySize; skeletonModifiers.InsertArrayElementAtIndex(numSkelMods); var thisSkelMod = skeletonModifiers.GetArrayElementAtIndex(numSkelMods); thisSkelMod.FindPropertyRelative("property").enumValueIndex = selectedAddProp; thisSkelMod.FindPropertyRelative("hashName").stringValue = addSkelBoneName; thisSkelMod.FindPropertyRelative("hash").intValue = addSkelBoneHash; thisSkelMod.FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].x; thisSkelMod.FindPropertyRelative("valuesX").FindPropertyRelative("val").FindPropertyRelative("modifiers").ClearArray(); thisSkelMod.FindPropertyRelative("valuesX").FindPropertyRelative("min").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].y; thisSkelMod.FindPropertyRelative("valuesX").FindPropertyRelative("max").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].z; // thisSkelMod.FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].x; thisSkelMod.FindPropertyRelative("valuesY").FindPropertyRelative("val").FindPropertyRelative("modifiers").ClearArray(); thisSkelMod.FindPropertyRelative("valuesY").FindPropertyRelative("min").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].y; thisSkelMod.FindPropertyRelative("valuesY").FindPropertyRelative("max").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].z; // thisSkelMod.FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("value").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].x; thisSkelMod.FindPropertyRelative("valuesZ").FindPropertyRelative("val").FindPropertyRelative("modifiers").ClearArray(); thisSkelMod.FindPropertyRelative("valuesZ").FindPropertyRelative("min").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].y; thisSkelMod.FindPropertyRelative("valuesZ").FindPropertyRelative("max").floatValue = skelAddDefaults[propertyArray[selectedAddProp]].z; skeletonModifiers.serializedObject.ApplyModifiedProperties(); addSkelBoneHash = 0; addSkelBoneName = ""; } if (canAddSkel == false) { EditorGUI.EndDisabledGroup(); } if (alreadyExistedSkel == true) { EditorGUILayout.HelpBox("There was already a modifier for that bone with that property. You can filter the existing modifiers at the top of the list to find it.", MessageType.Warning); } EditorGUILayout.Space(); } EditorGUILayout.Space(); serializedObject.FindProperty("overallModifiersEnabled").boolValue = EditorGUILayout.ToggleLeft("Enable Overall Modifiers", serializedObject.FindProperty("overallModifiersEnabled").boolValue); SerializedProperty overallModifiersEnabledProp = serializedObject.FindProperty("overallModifiersEnabled"); bool overallModifiersEnabled = overallModifiersEnabledProp.boolValue; if (overallModifiersEnabled) { EditorGUILayout.PropertyField(serializedObject.FindProperty("overallScale")); EditorGUILayout.PropertyField(serializedObject.FindProperty("heightModifiers")); EditorGUILayout.PropertyField(serializedObject.FindProperty("radiusModifier")); EditorGUILayout.PropertyField(serializedObject.FindProperty("massModifiers")); } serializedObject.ApplyModifiedProperties(); } }
//********************************************************* // // 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 System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Windows.Devices.PointOfService; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario4_SymbologyAttributes : Page { MainPage rootPage = MainPage.Current; BarcodeScanner scanner = null; ClaimedBarcodeScanner claimedScanner = null; ObservableCollection<SymbologyListEntry> listOfSymbologies = null; BarcodeSymbologyAttributes symbologyAttributes = null; public Scenario4_SymbologyAttributes() { this.InitializeComponent(); listOfSymbologies = new ObservableCollection<SymbologyListEntry>(); SymbologyListSource.Source = listOfSymbologies; } protected override void OnNavigatedTo(NavigationEventArgs e) { ResetTheScenarioState(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { ResetTheScenarioState(); } /// <summary> /// Event Handler for Start Scan Button Click. /// Sets up the barcode scanner to be ready to receive the data events from the scan. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ScenarioStartScanButton_Click(object sender, RoutedEventArgs e) { ScenarioStartScanButton.IsEnabled = false; rootPage.NotifyUser("Acquiring barcode scanner object.", NotifyType.StatusMessage); // create the barcode scanner. scanner = await DeviceHelpers.GetFirstBarcodeScannerAsync(); if (scanner != null) { // claim the scanner for exclusive use and enable it so that data received events are received. claimedScanner = await scanner.ClaimScannerAsync(); if (claimedScanner != null) { // It is always a good idea to have a release device requested event handler. If this event is not handled, there are chances of another app can // claim ownership of the barcode scanner. claimedScanner.ReleaseDeviceRequested += claimedScanner_ReleaseDeviceRequested; // after successfully claiming, attach the datareceived event handler. claimedScanner.DataReceived += claimedScanner_DataReceived; // Ask the API to decode the data by default. By setting this, API will decode the raw data from the barcode scanner and // send the ScanDataLabel and ScanDataType in the DataReceived event claimedScanner.IsDecodeDataEnabled = true; // enable the scanner. // Note: If the scanner is not enabled (i.e. EnableAsync not called), attaching the event handler will not be any useful because the API will not fire the event // if the claimedScanner has not been Enabled await claimedScanner.EnableAsync(); // after successful claim, list supported symbologies IReadOnlyList<uint> supportedSymbologies = await scanner.GetSupportedSymbologiesAsync(); foreach (uint symbology in supportedSymbologies) { listOfSymbologies.Add(new SymbologyListEntry(symbology)); } // reset the button state ScenarioEndScanButton.IsEnabled = true; rootPage.NotifyUser("Ready to scan. Device ID: " + claimedScanner.DeviceId, NotifyType.StatusMessage); } else { scanner.Dispose(); scanner = null; ScenarioStartScanButton.IsEnabled = true; rootPage.NotifyUser("Claim barcode scanner failed.", NotifyType.ErrorMessage); } } else { ScenarioStartScanButton.IsEnabled = true; rootPage.NotifyUser("Barcode scanner not found. Please connect a barcode scanner.", NotifyType.ErrorMessage); } } /// <summary> /// Event handler for the Release Device Requested event fired when barcode scanner receives Claim request from another application /// </summary> /// <param name="sender"></param> /// <param name="args"> Contains the ClamiedBarcodeScanner that is sending this request</param> void claimedScanner_ReleaseDeviceRequested(object sender, ClaimedBarcodeScanner e) { // always retain the device e.RetainDevice(); rootPage.NotifyUser("Event ReleaseDeviceRequested received. Retaining the barcode scanner.", NotifyType.StatusMessage); } /// <summary> /// Event handler for the DataReceived event fired when a barcode is scanned by the barcode scanner /// </summary> /// <param name="sender"></param> /// <param name="args"> Contains the BarcodeScannerReport which contains the data obtained in the scan</param> async void claimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) { // need to update the UI data on the dispatcher thread. // update the UI with the data received from the scan. await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // read the data from the buffer and convert to string. ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType); ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData); ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType); }); } /// <summary> /// Reset the Scenario state /// </summary> private void ResetTheScenarioState() { if (claimedScanner != null) { // Detach the event handlers claimedScanner.DataReceived -= claimedScanner_DataReceived; claimedScanner.ReleaseDeviceRequested -= claimedScanner_ReleaseDeviceRequested; // Release the Barcode Scanner and set to null claimedScanner.Dispose(); claimedScanner = null; } if (scanner != null) { scanner.Dispose(); scanner = null; } symbologyAttributes = null; // Reset the UI if we are still the current page. if (Frame.Content == this) { rootPage.NotifyUser("Click the start scanning button to begin.", NotifyType.StatusMessage); this.ScenarioOutputScanData.Text = "No data"; this.ScenarioOutputScanDataLabel.Text = "No data"; this.ScenarioOutputScanDataType.Text = "No data"; // reset the button state ScenarioEndScanButton.IsEnabled = false; ScenarioStartScanButton.IsEnabled = true; SetSymbologyAttributesButton.IsEnabled = false; EnableCheckDigit.IsEnabled = false; TransmitCheckDigit.IsEnabled = false; SetDecodeRangeLimits.IsEnabled = false; // reset symbology list listOfSymbologies.Clear(); } } /// <summary> /// Event handler for End Scan Button Click. /// Releases the Barcode Scanner and resets the text in the UI /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ScenarioEndScanButton_Click(object sender, RoutedEventArgs e) { // reset the scenario state this.ResetTheScenarioState(); } /// <summary> /// Event handler for Symbology listbox selection changed. /// Get symbology attributes and populate attribute UI components /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void SymbologySelection_Changed(object sender, SelectionChangedEventArgs args) { if (claimedScanner != null) { SymbologyListEntry symbologyListEntry = (SymbologyListEntry)SymbologyListBox.SelectedItem; if (symbologyListEntry != null) { SetSymbologyAttributesButton.IsEnabled = false; try { symbologyAttributes = await claimedScanner.GetSymbologyAttributesAsync(symbologyListEntry.Id); } catch (Exception) { symbologyAttributes = null; } if (symbologyAttributes != null) { SetSymbologyAttributesButton.IsEnabled = true; // initialize attributes UIs EnableCheckDigit.IsEnabled = symbologyAttributes.IsCheckDigitValidationSupported; EnableCheckDigit.IsChecked = symbologyAttributes.IsCheckDigitValidationEnabled; TransmitCheckDigit.IsEnabled = symbologyAttributes.IsCheckDigitTransmissionSupported; TransmitCheckDigit.IsChecked = symbologyAttributes.IsCheckDigitTransmissionEnabled; SetDecodeRangeLimits.IsEnabled = symbologyAttributes.IsDecodeLengthSupported; bool decodeLengthEnabled = (symbologyAttributes.DecodeLengthKind == BarcodeSymbologyDecodeLengthKind.Range); SetDecodeRangeLimits.IsChecked = decodeLengthEnabled; if (decodeLengthEnabled) { MinimumDecodeLength.Value = Math.Min(symbologyAttributes.DecodeLength1, symbologyAttributes.DecodeLength2); MaximumDecodeLength.Value = Math.Max(symbologyAttributes.DecodeLength1, symbologyAttributes.DecodeLength2); } } else { rootPage.NotifyUser("Symbology attributes are not available.", NotifyType.ErrorMessage); EnableCheckDigit.IsEnabled = false; TransmitCheckDigit.IsEnabled = false; SetDecodeRangeLimits.IsEnabled = false; } } } } private async void SetSymbologyAttributes_Click(object sender, RoutedEventArgs e) { if ((claimedScanner != null) && (symbologyAttributes != null)) { // populate attributes if (symbologyAttributes.IsCheckDigitValidationSupported) { symbologyAttributes.IsCheckDigitValidationEnabled = EnableCheckDigit.IsChecked.Value; } if (symbologyAttributes.IsCheckDigitTransmissionSupported) { symbologyAttributes.IsCheckDigitTransmissionEnabled = TransmitCheckDigit.IsChecked.Value; } if (symbologyAttributes.IsDecodeLengthSupported) { if (SetDecodeRangeLimits.IsChecked.Value) { symbologyAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.Range; symbologyAttributes.DecodeLength1 = (uint)MinimumDecodeLength.Value; symbologyAttributes.DecodeLength2 = (uint)MaximumDecodeLength.Value; } else { symbologyAttributes.DecodeLengthKind = BarcodeSymbologyDecodeLengthKind.AnyLength; } } SymbologyListEntry symbologyListEntry = (SymbologyListEntry)SymbologyListBox.SelectedItem; if (symbologyListEntry != null) { bool attributesSet = false; try { attributesSet = await claimedScanner.SetSymbologyAttributesAsync(symbologyListEntry.Id, symbologyAttributes); } catch (Exception) { // Scanner could not set the attributes. } if (attributesSet) { rootPage.NotifyUser("Attributes set for symbology '" + symbologyListEntry.Name + "'", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Attributes could not be set for symbology '" + symbologyListEntry.Name + "'.", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Select a symbology from the list.", NotifyType.ErrorMessage); } } } } }
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. 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 System; using System.Collections.Generic; using System.Text; using System.Xml; namespace com.esri.gpt.csw { /// <summary> /// CswSearchRequest class. /// </summary> /// <remarks> /// CswSearchRequest class is used to submit CSW search queries and to return CSW search results. /// Before submiting a request, you need to specify a catalog and provide search criteria. /// </remarks> public class CswSearchRequest { private CswCatalog _catalog; private CswSearchCriteria _criteria; private CswSearchResponse _response; private CswClient _cswClient; private string _mapServerUrl; #region "Properties" /// <summary> /// Accessor methods /// </summary> public CswCatalog Catalog { get { return _catalog; } set { _catalog = value; } } public CswSearchCriteria Criteria { get { return _criteria; } set { _criteria = value; } } #endregion #region Constructor /// <summary> /// Constructor /// </summary> public CswSearchRequest() { } #endregion #region "Methods and Functions" /// <summary> /// Search CSW catalog using the provided criteria. Search result can be accessed by calling GetResponse(). /// </summary> public void Search() { _response = new CswSearchResponse(); StringBuilder sb = new StringBuilder(); if (_criteria == null) { sb.AppendLine(DateTime.Now + " Criteria not specified."); throw new NullReferenceException("Criteria not specified."); } if (_catalog == null) { sb.AppendLine(DateTime.Now + " Catalog not specified."); throw new NullReferenceException("Catalog not specified."); } if (_catalog.URL == null || _catalog.URL.Length == 0) { sb.AppendLine(DateTime.Now + " Catalog URL not specified."); throw new NullReferenceException("Catalog URL not specified."); } if (_catalog.Profile == null) { sb.AppendLine(DateTime.Now + " Catalog profile not specified."); throw new NullReferenceException("Catalog profile not specified."); } CswProfile profile = _catalog.Profile; writeLogMessage("Csw profile used : " + profile.Name); // generate getRecords query string requestUrl = _catalog.Capabilities.GetRecords_PostURL; string requestQuery = profile.GenerateCSWGetRecordsRequest(_criteria); // requestQuery = "<csw:GetCapabilities xmlns:csw=\"http://www.opengis.net/cat/csw/2.0.2\" request=\"GetCapabilities\" service=\"CSW\" version=\"2.0.2\"/>"; requestQuery = requestQuery.Replace("utf-16", "utf-8"); requestQuery = requestQuery.Replace("UTF-16", "UTF-8"); // submit search query if (_cswClient == null) { _cswClient = new CswClient(); } string responseText; sb.AppendLine(DateTime.Now + " Sending CSW GetRecords request to endpoint : " + requestUrl); sb.AppendLine("Request Query : " + requestQuery); if(!_catalog.Capabilities.GetRecords_IsSoapEndPoint) responseText = _cswClient.SubmitHttpRequest("POST", requestUrl, requestQuery); else responseText = _cswClient.SubmitHttpRequest("SOAP", requestUrl, requestQuery); // parse out csw search records CswRecords records = new CswRecords(); sb.AppendLine(DateTime.Now + " Response received : " + responseText); profile.ReadCSWGetRecordsResponse(responseText, records); sb.AppendLine(DateTime.Now + " Parsed GetRecords response."); // populate CSW response _response.ResponseXML = responseText; _response.Records = records; writeLogMessage(sb.ToString()); } private void writeLogMessage(String logMessage){ Utils.logger.writeLog(logMessage); } /// <summary> /// Retrieve metadata from CSW service by its ID /// </summary> /// <param name="DocID">Metadata document ID</param> public bool GetMetadataByID(string DocID, bool bApplyTransform) { _response = new CswSearchResponse(); StringBuilder sb = new StringBuilder(); if (DocID == null || DocID == "") { throw new ArgumentNullException(); } if (_catalog == null) { throw new NullReferenceException("Catalog not specified."); } if (_catalog.Capabilities == null) { throw new NullReferenceException("Catalog capabilities not initialized."); } if (_catalog.Profile == null) { throw new NullReferenceException("Catalog profile not specified."); } if (_catalog.Capabilities.GetRecordByID_GetURL == null || _catalog.Capabilities.GetRecordByID_GetURL.Length == 0) { throw new NullReferenceException("GetRecordByID URL not specified for the catalog capabilities."); } CswProfile profile = _catalog.Profile; writeLogMessage(" Csw profile used : " + profile.Name); // generate request url string getRecordByIDBaseUrl = _catalog.Capabilities.GetRecordByID_GetURL; string requestUrl = profile.GenerateCSWGetMetadataByIDRequestURL(getRecordByIDBaseUrl, DocID); sb.AppendLine(DateTime.Now + " GetRecordsById request URL : " + requestUrl); if (_cswClient == null) { _cswClient = new CswClient(); } string responseText = _cswClient.SubmitHttpRequest("GET", requestUrl, ""); _response.ResponseXML = responseText; sb.AppendLine(DateTime.Now + " GetRecordsById response xml : " + responseText); CswRecord record = new CswRecord(DocID); bool isTransformed = false; if (bApplyTransform) { isTransformed = profile.TransformCSWGetMetadataByIDResponse(responseText, record); if(isTransformed) sb.AppendLine(DateTime.Now + " Transformed xml : " + record.FullMetadata); } else { record.FullMetadata = responseText; } /*if (!isTransformed) { XmlDocument responseXml = new XmlDocument(); try { responseXml.LoadXml(responseText); } catch (XmlException xmlEx) { throw new XmlException("Error occurred \r\n" + xmlEx.Message); } record.FullMetadata = responseXml.FirstChild.InnerText ; }*/ // add record to the response CswRecords records = new CswRecords(); if (record != null) { records.Add(record.ID, record); } _response.Records = records; _mapServerUrl = record.MapServerURL; if (_mapServerUrl != null) sb.AppendLine(DateTime.Now + " Map Server Url : " + _mapServerUrl); writeLogMessage(sb.ToString()); return isTransformed; } /// <summary> /// Get Add to map information /// </summary> /// <param name="DocID">document identifier</param> public void GetAddToMapInfoByID(string DocID) { _response = new CswSearchResponse(); StringBuilder sb = new StringBuilder(); if (DocID == null || DocID == "") { throw new ArgumentNullException(); } if (_catalog == null) { throw new NullReferenceException("Catalog not specified."); } if (_catalog.Capabilities == null) { throw new NullReferenceException("Catalog capabilities not initialized."); } if (_catalog.Profile == null) { throw new NullReferenceException("Catalog profile not specified."); } if (_catalog.Capabilities.GetRecordByID_GetURL == null || _catalog.Capabilities.GetRecordByID_GetURL.Length == 0) { sb.AppendLine(DateTime.Now + " GetRecordByID URL not specified for the catalog capabilities."); throw new NullReferenceException("GetRecordByID URL not specified for the catalog capabilities."); } CswProfile profile = _catalog.Profile; // generate request url string getRecordByIDBaseUrl = _catalog.Capabilities.GetRecordByID_GetURL; string requestUrl = profile.GenerateCSWGetMetadataByIDRequestURL(getRecordByIDBaseUrl, DocID); sb.AppendLine(DateTime.Now + " GetRecordsById request URL : " + requestUrl); if (_cswClient == null) { _cswClient = new CswClient(); } string responseText = _cswClient.SubmitHttpRequest("GET", requestUrl, ""); _response.ResponseXML = responseText; sb.AppendLine(DateTime.Now + " GetRecordsById response xml : " + responseText); CswRecord record = new CswRecord(DocID); profile.ReadCSWGetMetadataByIDResponse(responseText, record); if (record.MetadataResourceURL != null && record.MetadataResourceURL.Equals("") && profile.Name.Equals("terra catalog CSW 2.0.2 AP ISO")) { record.FullMetadata = responseText; } if (record == null) { throw new NullReferenceException("Record not populated."); } // check if full metadata or resourceURL has been returned bool hasFullMetadata = !(record.FullMetadata == null || record.FullMetadata == ""); bool hasResourceUrl = !(record.MetadataResourceURL == null || record.MetadataResourceURL == ""); if (!hasFullMetadata && !hasResourceUrl) { // throw new InvalidOperationException("Neither full metadata nor metadata resource URL was found for the CSW record."); } else if (!hasFullMetadata && record.MetadataResourceURL != null) { // need to load metadata from resource URL responseText = _cswClient.SubmitHttpRequest("GET", record.MetadataResourceURL, "", "", ""); record.FullMetadata = responseText; } // add record to the response CswRecords records = new CswRecords(); if (record != null) { records.Add(record.ID, record); } _response.Records = records; _mapServerUrl = record.MapServerURL; if (_mapServerUrl != null) sb.AppendLine(DateTime.Now + " Map Server Url : " + _mapServerUrl); writeLogMessage(sb.ToString()); } /// <summary> /// Get the CSW search response of a CSW search request /// </summary> /// <remarks> /// Get the CSW search response of a CSW search request /// </remarks> /// <returns>a CswSearchResponse object.</returns> public CswSearchResponse GetResponse() { return _response; } /// <summary> /// Map server url /// </summary> /// <returns></returns> public string GetMapServerUrl() { return _mapServerUrl; } #endregion } }
/* * 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 QuantConnect.Data.Market; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Slippage; using QuantConnect.Securities; using QuantConnect.Securities.Equity; using QuantConnect.Util; namespace QuantConnect.Brokerages { /// <summary> /// Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses /// the default transaction models /// </summary> public class DefaultBrokerageModel : IBrokerageModel { /// <summary> /// The default markets for the backtesting brokerage /// </summary> public static readonly IReadOnlyDictionary<SecurityType, string> DefaultMarketMap = new Dictionary<SecurityType, string> { {SecurityType.Base, Market.USA}, {SecurityType.Equity, Market.USA}, {SecurityType.Option, Market.USA}, {SecurityType.Forex, Market.FXCM}, {SecurityType.Cfd, Market.FXCM} }.ToReadOnlyDictionary(); /// <summary> /// Gets or sets the account type used by this model /// </summary> public virtual AccountType AccountType { get; private set; } /// <summary> /// Gets a map of the default markets to be used for each security type /// </summary> public virtual IReadOnlyDictionary<SecurityType, string> DefaultMarkets { get { return DefaultMarketMap; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class /// </summary> /// <param name="accountType">The type of account to be modelled, defaults to /// <see cref="QuantConnect.AccountType.Margin"/></param> public DefaultBrokerageModel(AccountType accountType = AccountType.Margin) { AccountType = accountType; } /// <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 virtual bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { message = null; 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 virtual bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { message = null; 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">The security being traded</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 virtual bool CanExecuteOrder(Security security, Order order) { return true; } /// <summary> /// Applies the split to the specified order ticket /// </summary> /// <remarks> /// This default implementation will update the orders to maintain a similar market value /// </remarks> /// <param name="tickets">The open tickets matching the split event</param> /// <param name="split">The split event data</param> public virtual void ApplySplit(List<OrderTicket> tickets, Split split) { // by default we'll just update the orders to have the same notional value var splitFactor = split.SplitFactor; tickets.ForEach(ticket => ticket.Update(new UpdateOrderFields { Quantity = (int?) (ticket.Quantity/splitFactor), LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (decimal?) null, StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (decimal?) null })); } /// <summary> /// Gets the brokerage's leverage for the specified security /// </summary> /// <param name="security">The security's whose leverage we seek</param> /// <returns>The leverage for the specified security</returns> public decimal GetLeverage(Security security) { switch (security.Type) { case SecurityType.Equity: return 2m; case SecurityType.Forex: case SecurityType.Cfd: return 50m; case SecurityType.Base: case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: default: return 1m; } } /// <summary> /// Gets a new fill model that represents this brokerage's fill behavior /// </summary> /// <param name="security">The security to get fill model for</param> /// <returns>The new fill model for this brokerage</returns> public virtual IFillModel GetFillModel(Security security) { return new ImmediateFillModel(); } /// <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 virtual IFeeModel GetFeeModel(Security security) { switch (security.Type) { case SecurityType.Base: return new ConstantFeeModel(0m); case SecurityType.Forex: case SecurityType.Equity: return new InteractiveBrokersFeeModel(); case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: case SecurityType.Cfd: default: return new ConstantFeeModel(0m); } } /// <summary> /// Gets a new slippage model that represents this brokerage's fill slippage behavior /// </summary> /// <param name="security">The security to get a slippage model for</param> /// <returns>The new slippage model for this brokerage</returns> public virtual ISlippageModel GetSlippageModel(Security security) { switch (security.Type) { case SecurityType.Base: case SecurityType.Equity: return new ConstantSlippageModel(0); case SecurityType.Forex: case SecurityType.Cfd: return new SpreadSlippageModel(); case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: default: return new ConstantSlippageModel(0); } } /// <summary> /// Gets a new settlement model for the security /// </summary> /// <param name="security">The security to get a settlement model for</param> /// <param name="accountType">The account type</param> /// <returns>The settlement model for this brokerage</returns> public virtual ISettlementModel GetSettlementModel(Security security, AccountType accountType) { if (security.Type == SecurityType.Equity && accountType == AccountType.Cash) return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime); return new ImmediateSettlementModel(); } } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Neo.IO.Caching { /// <summary> /// Represents a queue with indexed access to the items /// </summary> /// <typeparam name="T">The type of items in the queue</typeparam> class IndexedQueue<T> : IReadOnlyCollection<T> { private const int DefaultCapacity = 16; private const int GrowthFactor = 2; private const float TrimThreshold = 0.9f; private T[] _array; private int _head; private int _count; /// <summary> /// Indicates the count of items in the queue /// </summary> public int Count => _count; /// <summary> /// Creates a queue with the default capacity /// </summary> public IndexedQueue() : this(DefaultCapacity) { } /// <summary> /// Creates a queue with the specified capacity /// </summary> /// <param name="capacity">The initial capacity of the queue</param> public IndexedQueue(int capacity) { if (capacity <= 0) throw new ArgumentOutOfRangeException(nameof(capacity), "The capacity must be greater than zero."); _array = new T[capacity]; _head = 0; _count = 0; } /// <summary> /// Creates a queue filled with the specified items /// </summary> /// <param name="collection">The collection of items to fill the queue with</param> public IndexedQueue(IEnumerable<T> collection) { _array = collection.ToArray(); _head = 0; _count = _array.Length; } /// <summary> /// Gets the value at the index /// </summary> /// <param name="index">The index</param> /// <returns>The value at the specified index</returns> public ref T this[int index] { get { if (index < 0 || index >= _count) throw new IndexOutOfRangeException(); return ref _array[(index + _head) % _array.Length]; } } /// <summary> /// Inserts an item at the rear of the queue /// </summary> /// <param name="item">The item to insert</param> public void Enqueue(T item) { if (_array.Length == _count) { int newSize = _array.Length * GrowthFactor; if (_head == 0) { Array.Resize(ref _array, newSize); } else { T[] buffer = new T[newSize]; Array.Copy(_array, _head, buffer, 0, _array.Length - _head); Array.Copy(_array, 0, buffer, _array.Length - _head, _head); _array = buffer; _head = 0; } } _array[(_head + _count) % _array.Length] = item; ++_count; } /// <summary> /// Provides access to the item at the front of the queue without dequeueing it /// </summary> /// <returns>The frontmost item</returns> public T Peek() { if (_count == 0) throw new InvalidOperationException("The queue is empty."); return _array[_head]; } /// <summary> /// Attempts to return an item from the front of the queue without removing it /// </summary> /// <param name="item">The item</param> /// <returns>True if the queue returned an item or false if the queue is empty</returns> public bool TryPeek(out T item) { if (_count == 0) { item = default; return false; } else { item = _array[_head]; return true; } } /// <summary> /// Removes an item from the front of the queue, returning it /// </summary> /// <returns>The item that was removed</returns> public T Dequeue() { if (_count == 0) throw new InvalidOperationException("The queue is empty"); T result = _array[_head]; ++_head; _head %= _array.Length; --_count; return result; } /// <summary> /// Attempts to return an item from the front of the queue, removing it /// </summary> /// <param name="item">The item</param> /// <returns>True if the queue returned an item or false if the queue is empty</returns> public bool TryDequeue(out T item) { if (_count == 0) { item = default; return false; } else { item = _array[_head]; ++_head; _head %= _array.Length; --_count; return true; } } /// <summary> /// Clears the items from the queue /// </summary> public void Clear() { _head = 0; _count = 0; } /// <summary> /// Trims the extra array space that isn't being used. /// </summary> public void TrimExcess() { if (_count == 0) { _array = new T[DefaultCapacity]; } else if (_array.Length * TrimThreshold >= _count) { T[] arr = new T[_count]; CopyTo(arr, 0); _array = arr; _head = 0; } } /// <summary> /// Copys the queue's items to a destination array /// </summary> /// <param name="array">The destination array</param> /// <param name="arrayIndex">The index in the destination to start copying at</param> public void CopyTo(T[] array, int arrayIndex) { if (array is null) throw new ArgumentNullException(nameof(array)); if (arrayIndex < 0 || arrayIndex + _count > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex)); if (_head + _count <= _array.Length) { Array.Copy(_array, _head, array, arrayIndex, _count); } else { Array.Copy(_array, _head, array, arrayIndex, _array.Length - _head); Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, _count + _head - _array.Length); } } /// <summary> /// Returns an array of the items in the queue /// </summary> /// <returns>An array containing the queue's items</returns> public T[] ToArray() { T[] result = new T[_count]; CopyTo(result, 0); return result; } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < _count; i++) yield return _array[(_head + i) % _array.Length]; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
// THIS CODE AND INFORMATION IS 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 (c) 2006 Microsoft Corporation. All rights reserved. using System; using System.Drawing; using System.Windows.Forms; using System.Collections.Generic; namespace Microsoft.Samples.RssPlatform.ScreenSaver.UI { /// <summary> /// Encapsulates the rendering of a list of items. Each item's description is shown in a list, and a single item is selected. /// </summary> /// <typeparam name="T">The type of item that this ItemListView will draw.</typeparam> public class FeedListView<T> : IDisposable where T : IItem { private const float percentOfArticleDisplayBoxToFillWithText = 0.5f; private const float percentOfFontHeightForSelectionBox = 1.5f; private const int padding = 20; // Where to draw private Point location; private Size size; private FeedList feeds; private string title; private Font feedFont; private Font titleFont; private Color backColor; private Color borderColor; private Color foreColor; private Color titleBackColor; private Color titleForeColor; private Color selectedForeColor; private Color selectedBackColor; private float feedFontHeight; // The maximum number of feeds that will be displayed (defines viewport) private int maxFeedsToShow; // The current first index of the feed visible in viewport private int firstFeedToShow = 0; // The minimum number of feeds that will be displayed // If there are fewer than this then there will be blank space in the display private int minFeedsToShow; private int NumFeeds { get { return Math.Min(feeds.Count, maxFeedsToShow); } } private int NumFeedRows { get { return Math.Max(NumFeeds, minFeedsToShow); } } public Point Location { get { return location; } set { location = value; } } public Size Size { get { return size; } set { size = value; } } public Color ForeColor { get { return foreColor; } set { foreColor = value; } } public Color BackColor { get { return backColor; } set { backColor = value; } } public Color BorderColor { get { return borderColor; } set { borderColor = value; } } public Color TitleForeColor { get { return titleForeColor; } set { titleForeColor = value; } } public Color TitleBackColor { get { return titleBackColor; } set { titleBackColor = value; } } public Color SelectedForeColor { get { return selectedForeColor; } set { selectedForeColor = value; } } public Color SelectedBackColor { get { return selectedBackColor; } set { selectedBackColor = value; } } public int MaxFeedsToShow { get { return maxFeedsToShow; } set { maxFeedsToShow = value; } } public int MinFeedsToShow { get { return minFeedsToShow; } set { minFeedsToShow = value; } } public int RowHeight { get { // There is one row for each item plus 2 rows for the title. return size.Height / (NumFeedRows + 2); } } public Font ItemFont { get { // Choose a font for each of the item titles that will fit all numItems // of them (plus some slack for the title) in the control feedFontHeight = (float)(percentOfArticleDisplayBoxToFillWithText * RowHeight); if (feedFont == null || feedFont.Size != feedFontHeight) { feedFont = new Font("Microsoft Sans Serif", feedFontHeight, GraphicsUnit.Pixel); } return feedFont; } } public Font TitleFont { get { // Choose a font for the title text. // This font will be twice as big as the ItemFont float titleFontHeight = (float)(percentOfArticleDisplayBoxToFillWithText * 2 * RowHeight); if (titleFont == null || titleFont.Size != titleFontHeight) { titleFont = new Font("Microsoft Sans Serif", titleFontHeight, GraphicsUnit.Pixel); } return titleFont; } } public FeedListView(string title, FeedList feeds) { if (feeds == null) throw new ArgumentNullException("feeds"); this.feeds = feeds; this.title = title; } public void Paint(PaintEventArgs args) { Graphics g = args.Graphics; // Settings to make the text drawing look nice g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; DrawBackground(g); // Determine the viewport for display int index = feeds.CurrentFeedIndex + 1; if (firstFeedToShow < index - maxFeedsToShow) // selection at bottom firstFeedToShow = Math.Max(index - maxFeedsToShow, 0); else if (firstFeedToShow >= index) // selection at top firstFeedToShow = feeds.CurrentFeedIndex; index = firstFeedToShow; // Draw each feed's description int row = 0; while (row < maxFeedsToShow && index < feeds.Count) { DrawFeedTitle(g, row++, feeds.GetFeed(index++)); } // Draw the title text DrawTitle(g); } /// <summary> /// Draws a box and border ontop of which the text of the items can be drawn. /// </summary> /// <param name="g">The Graphics object to draw onto</param> private void DrawBackground(Graphics g) { using (Brush backBrush = new SolidBrush(BackColor)) using (Pen borderPen = new Pen(BorderColor, 4)) { g.FillRectangle(backBrush, new Rectangle(Location.X + 4, Location.Y + 4, Size.Width - 8, Size.Height - 8)); g.DrawRectangle(borderPen, new Rectangle(Location, Size)); } } /// <summary> /// Draws the title of the feed with the given index. /// </summary> /// <param name="g">The Graphics object to draw onto</param> /// <param name="index">The index of the item in the list</param> private void DrawFeedTitle(Graphics g, int row, Rss.RssFeed rssFeed) { // Set formatting and layout StringFormat stringFormat = new StringFormat(StringFormatFlags.LineLimit); stringFormat.Trimming = StringTrimming.EllipsisCharacter; Rectangle feedTitleRect = new Rectangle(Location.X + padding, Location.Y + (int)(row * RowHeight) + padding, Size.Width - (2 * padding), (int)(percentOfFontHeightForSelectionBox * feedFontHeight)); // Select color and draw border if current index is selected Color textBrushColor = ForeColor; if (rssFeed == feeds.CurrentFeed) { textBrushColor = SelectedForeColor; using (Brush backBrush = new SolidBrush(SelectedBackColor)) { g.FillRectangle(backBrush, feedTitleRect); } } // Draw the title of the feed string textToDraw = rssFeed.Title + " (" + rssFeed.LastWriteTime + ")"; using (Brush textBrush = new SolidBrush(textBrushColor)) { g.DrawString(textToDraw, ItemFont, textBrush, feedTitleRect, stringFormat); } } /// <summary> /// Draws a title bar. /// </summary> /// <param name="g">The Graphics object to draw onto</param> private void DrawTitle(Graphics g) { Point titleLocation = new Point(Location.X + padding, Location.Y + Size.Height - (RowHeight) - padding); Size titleSize = new Size(Size.Width - (2 * padding), 2 * RowHeight); Rectangle titleRectangle = new Rectangle(titleLocation, titleSize); // Draw the title box and the selected item box using (Brush titleBackBrush = new SolidBrush(TitleBackColor)) { g.FillRectangle(titleBackBrush, titleRectangle); } // Draw the title text StringFormat titleFormat = new StringFormat(StringFormatFlags.LineLimit); titleFormat.Alignment = StringAlignment.Far; titleFormat.Trimming = StringTrimming.EllipsisCharacter; using (Brush titleBrush = new SolidBrush(TitleForeColor)) { g.DrawString(title, TitleFont, titleBrush, titleRectangle, titleFormat); } } /// <summary> /// Dispose all disposable fields /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (feedFont != null) { feedFont.Dispose(); feedFont = null; } if (titleFont != null) { titleFont.Dispose(); titleFont = null; } } } } }
using System.Collections.Generic; using System.Linq; using Content.Client.State; using Content.Shared.GameObjects; using Content.Shared.GameObjects.EntitySystemMessages; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Interfaces.GameObjects.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.GameObjects.EntitySystems; using Robust.Client.Graphics.Shaders; using Robust.Client.Interfaces.Graphics.ClientEye; using Robust.Client.Interfaces.Input; using Robust.Client.Interfaces.State; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Input; using Robust.Shared.Input.Binding; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Log; using Robust.Shared.Maths; using Robust.Shared.Prototypes; namespace Content.Client.GameObjects.EntitySystems { /// <summary> /// Handles clientside drag and drop logic /// </summary> [UsedImplicitly] public class DragDropSystem : EntitySystem { [Dependency] private readonly IStateManager _stateManager = default!; [Dependency] private readonly IInputManager _inputManager = default!; [Dependency] private readonly IEyeManager _eyeManager = default!; [Dependency] private readonly IPrototypeManager _prototypeManager = default!; // drag will be triggered when mouse leaves this deadzone around the click position. private const float DragDeadzone = 2f; // how often to recheck possible targets (prevents calling expensive // check logic each update) private const float TargetRecheckInterval = 0.25f; // if a drag ends up being cancelled and it has been under this // amount of time since the mousedown, we will "replay" the original // mousedown event so it can be treated like a regular click private const float MaxMouseDownTimeForReplayingClick = 0.85f; private const string ShaderDropTargetInRange = "SelectionOutlineInrange"; private const string ShaderDropTargetOutOfRange = "SelectionOutline"; // entity performing the drag action private IEntity _dragger; private IEntity _draggedEntity; private readonly List<IDraggable> _draggables = new List<IDraggable>(); private IEntity _dragShadow; private DragState _state; // time since mouse down over the dragged entity private float _mouseDownTime; // screen pos where the mouse down began private Vector2 _mouseDownScreenPos; // how much time since last recheck of all possible targets private float _targetRecheckTime; // reserved initial mousedown event so we can replay it if no drag ends up being performed private PointerInputCmdHandler.PointerInputCmdArgs? _savedMouseDown; // whether we are currently replaying the original mouse down, so we // can ignore any events sent to this system private bool _isReplaying; private ShaderInstance _dropTargetInRangeShader; private ShaderInstance _dropTargetOutOfRangeShader; private SharedInteractionSystem _interactionSystem; private InputSystem _inputSystem; private List<SpriteComponent> highlightedSprites = new List<SpriteComponent>(); private enum DragState { NotDragging, // not dragging yet, waiting to see // if they hold for long enough MouseDown, // currently dragging something Dragging, } public override void Initialize() { _state = DragState.NotDragging; _dropTargetInRangeShader = _prototypeManager.Index<ShaderPrototype>(ShaderDropTargetInRange).Instance(); _dropTargetOutOfRangeShader = _prototypeManager.Index<ShaderPrototype>(ShaderDropTargetOutOfRange).Instance(); _interactionSystem = Get<SharedInteractionSystem>(); _inputSystem = Get<InputSystem>(); // needs to fire on mouseup and mousedown so we can detect a drag / drop CommandBinds.Builder .Bind(EngineKeyFunctions.Use, new PointerInputCmdHandler(OnUse, false)) .Register<DragDropSystem>(); } public override void Shutdown() { CancelDrag(false, null); CommandBinds.Unregister<DragDropSystem>(); base.Shutdown(); } private bool OnUse(in PointerInputCmdHandler.PointerInputCmdArgs args) { // not currently predicted if (_inputSystem.Predicted) return false; // currently replaying a saved click, don't handle this because // we already decided this click doesn't represent an actual drag attempt if (_isReplaying) return false; if (args.State == BoundKeyState.Down) { return OnUseMouseDown(args); } else if (args.State == BoundKeyState.Up) { return OnUseMouseUp(args); } return false; } private bool OnUseMouseDown(in PointerInputCmdHandler.PointerInputCmdArgs args) { var dragger = args.Session.AttachedEntity; // cancel any current dragging if there is one (shouldn't be because they would've had to have lifted // the mouse, canceling the drag, but just being cautious) CancelDrag(false, null); // possibly initiating a drag // check if the clicked entity is draggable if (EntityManager.TryGetEntity(args.EntityUid, out var entity)) { // check if the entity is reachable if (!_interactionSystem.InRangeUnobstructed(dragger, entity)) { return false; } var canDrag = false; foreach (var draggable in entity.GetAllComponents<IDraggable>()) { var dragEventArgs = new StartDragDropEventArgs(args.Session.AttachedEntity, entity); if (draggable.CanStartDrag(dragEventArgs)) { // wait to initiate a drag _dragger = dragger; _draggedEntity = entity; _draggables.Add(draggable); _mouseDownTime = 0; _state = DragState.MouseDown; _mouseDownScreenPos = _inputManager.MouseScreenPosition; // don't want anything else to process the click, // but we will save the event so we can "re-play" it if this drag does // not turn into an actual drag so the click can be handled normally _savedMouseDown = args; canDrag = true; } } return canDrag; } return false; } private bool OnUseMouseUp(in PointerInputCmdHandler.PointerInputCmdArgs args) { if (_state == DragState.MouseDown) { // quick mouseup, definitely treat it as a normal click by // replaying the original CancelDrag(true, args.OriginalMessage); return false; } if (_state != DragState.Dragging) return false; // remaining CancelDrag calls will not replay the click because // by this time we've determined the input was actually a drag attempt // tell the server we are dropping if we are over a valid drop target in range. // We don't use args.EntityUid here because drag interactions generally should // work even if there's something "on top" of the drop target if (!_interactionSystem.InRangeUnobstructed(_dragger, args.Coordinates, ignoreInsideBlocker: true)) { CancelDrag(false, null); return false; } var entities = GameScreenBase.GetEntitiesUnderPosition(_stateManager, args.Coordinates); foreach (var entity in entities) { // check if it's able to be dropped on by current dragged entity var dropArgs = new DragDropEventArgs(_dragger, args.Coordinates, _draggedEntity, entity); foreach (var draggable in _draggables) { if (!draggable.CanDrop(dropArgs)) { continue; } // tell the server about the drop attempt RaiseNetworkEvent(new DragDropMessage(args.Coordinates, _draggedEntity.Uid, entity.Uid)); draggable.Drop(dropArgs); CancelDrag(false, null); return true; } } CancelDrag(false, null); return false; } private void StartDragging() { // this is checked elsewhere but adding this as a failsafe if (_draggedEntity == null || _draggedEntity.Deleted) { Logger.Error("Programming error. Cannot initiate drag, no dragged entity or entity" + " was deleted."); return; } if (_draggedEntity.TryGetComponent<SpriteComponent>(out var draggedSprite)) { _state = DragState.Dragging; // pop up drag shadow under mouse var mousePos = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition); _dragShadow = EntityManager.SpawnEntity("dragshadow", mousePos); var dragSprite = _dragShadow.GetComponent<SpriteComponent>(); dragSprite.CopyFrom(draggedSprite); dragSprite.RenderOrder = EntityManager.CurrentTick.Value; dragSprite.Color = dragSprite.Color.WithAlpha(0.7f); // keep it on top of everything dragSprite.DrawDepth = (int) DrawDepth.Overlays; if (dragSprite.Directional) { _dragShadow.Transform.WorldRotation = _draggedEntity.Transform.WorldRotation; } HighlightTargets(); } else { Logger.Warning("Unable to display drag shadow for {0} because it" + " has no sprite component.", _draggedEntity.Name); } } private void HighlightTargets() { if (_state != DragState.Dragging || _draggedEntity == null || _draggedEntity.Deleted || _dragShadow == null || _dragShadow.Deleted) { Logger.Warning("Programming error. Can't highlight drag and drop targets, not currently " + "dragging anything or dragged entity / shadow was deleted."); return; } // highlights the possible targets which are visible // and able to be dropped on by the current dragged entity // remove current highlights RemoveHighlights(); // find possible targets on screen even if not reachable // TODO: Duplicated in SpriteSystem var pvsBounds = _eyeManager.GetWorldViewport().Enlarged(5); var pvsEntities = EntityManager.GetEntitiesIntersecting(_eyeManager.CurrentMap, pvsBounds, true); foreach (var pvsEntity in pvsEntities) { if (pvsEntity.TryGetComponent<SpriteComponent>(out var inRangeSprite)) { // can't highlight if there's no sprite or it's not visible if (inRangeSprite.Visible == false) continue; // check if it's able to be dropped on by current dragged entity var canDropArgs = new CanDropEventArgs(_dragger, _draggedEntity, pvsEntity); var anyValidDraggable = _draggables.Any(draggable => draggable.CanDrop(canDropArgs)); if (anyValidDraggable) { // highlight depending on whether its in or out of range var inRange = _interactionSystem.InRangeUnobstructed(_dragger, pvsEntity); inRangeSprite.PostShader = inRange ? _dropTargetInRangeShader : _dropTargetOutOfRangeShader; inRangeSprite.RenderOrder = EntityManager.CurrentTick.Value; highlightedSprites.Add(inRangeSprite); } } } } private void RemoveHighlights() { foreach (var highlightedSprite in highlightedSprites) { highlightedSprite.PostShader = null; highlightedSprite.RenderOrder = 0; } highlightedSprites.Clear(); } /// <summary> /// Cancels the drag, firing our saved drag event if instructed to do so and /// we are within the threshold for replaying the click /// (essentially reverting the drag attempt and allowing the original click /// to proceed as if no drag was performed) /// </summary> /// <param name="cause">if fireSavedCmd is true, this should be passed with the value of /// the pointer cmd that caused the drag to be cancelled</param> private void CancelDrag(bool fireSavedCmd, FullInputCmdMessage cause) { RemoveHighlights(); if (_dragShadow != null) { EntityManager.DeleteEntity(_dragShadow); } _dragShadow = null; _draggedEntity = null; _draggables.Clear(); _dragger = null; _state = DragState.NotDragging; _mouseDownTime = 0; if (fireSavedCmd && _savedMouseDown.HasValue && _mouseDownTime < MaxMouseDownTimeForReplayingClick) { var savedValue = _savedMouseDown.Value; _isReplaying = true; // adjust the timing info based on the current tick so it appears as if it happened now var replayMsg = savedValue.OriginalMessage; var adjustedInputMsg = new FullInputCmdMessage(cause.Tick, cause.SubTick, replayMsg.InputFunctionId, replayMsg.State, replayMsg.Coordinates, replayMsg.ScreenCoordinates, replayMsg.Uid); _inputSystem.HandleInputCommand(savedValue.Session, EngineKeyFunctions.Use, adjustedInputMsg, true); _isReplaying = false; } _savedMouseDown = null; } public override void Update(float frameTime) { base.Update(frameTime); if (_state == DragState.MouseDown) { var screenPos = _inputManager.MouseScreenPosition; if (_draggedEntity == null || _draggedEntity.Deleted) { // something happened to the clicked entity or we moved the mouse off the target so // we shouldn't replay the original click CancelDrag(false, null); return; } else if ((_mouseDownScreenPos - screenPos).Length > DragDeadzone) { // initiate actual drag StartDragging(); _mouseDownTime = 0; } } else if (_state == DragState.Dragging) { if (_draggedEntity == null || _draggedEntity.Deleted) { CancelDrag(false, null); return; } // still in range of the thing we are dragging? if (!_interactionSystem.InRangeUnobstructed(_dragger, _draggedEntity)) { CancelDrag(false, null); return; } // keep dragged entity under mouse var mousePos = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition); // TODO: would use MapPosition instead if it had a setter, but it has no setter. // is that intentional, or should we add a setter for Transform.MapPosition? _dragShadow.Transform.WorldPosition = mousePos.Position; _targetRecheckTime += frameTime; if (_targetRecheckTime > TargetRecheckInterval) { HighlightTargets(); _targetRecheckTime = 0; } } } } }
using System; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Globalization; namespace ClosedXML.Excel.CalcEngine { /// <summary> /// Base class that represents parsed expressions. /// </summary> /// <remarks> /// For example: /// <code> /// Expression expr = scriptEngine.Parse(strExpression); /// object val = expr.Evaluate(); /// </code> /// </remarks> internal class Expression : IComparable<Expression> { //--------------------------------------------------------------------------- #region ** fields internal Token _token; #endregion //--------------------------------------------------------------------------- #region ** ctors internal Expression() { _token = new Token(null, TKID.ATOM, TKTYPE.IDENTIFIER); } internal Expression(object value) { _token = new Token(value, TKID.ATOM, TKTYPE.LITERAL); } internal Expression(Token tk) { _token = tk; } #endregion //--------------------------------------------------------------------------- #region ** object model public virtual object Evaluate() { if (_token.Type != TKTYPE.LITERAL) { throw new ArgumentException("Bad expression."); } return _token.Value; } public virtual Expression Optimize() { return this; } #endregion //--------------------------------------------------------------------------- #region ** implicit converters public static implicit operator string(Expression x) { var v = x.Evaluate(); return v == null ? string.Empty : v.ToString(); } public static implicit operator double(Expression x) { // evaluate var v = x.Evaluate(); // handle doubles if (v is double) { return (double)v; } // handle booleans if (v is bool) { return (bool)v ? 1 : 0; } // handle dates if (v is DateTime) { return ((DateTime)v).ToOADate(); } // handle nulls if (v == null || v is string) { return 0; } // handle everything else CultureInfo _ci = Thread.CurrentThread.CurrentCulture; return (double)Convert.ChangeType(v, typeof(double), _ci); } public static implicit operator bool(Expression x) { // evaluate var v = x.Evaluate(); // handle booleans if (v is bool) { return (bool)v; } // handle nulls if (v == null) { return false; } // handle doubles if (v is double) { return (double)v == 0 ? false : true; } // handle everything else return (double)x == 0 ? false : true; } public static implicit operator DateTime(Expression x) { // evaluate var v = x.Evaluate(); // handle dates if (v is DateTime) { return (DateTime)v; } // handle doubles if (v is double || v is int) { return DateTime.FromOADate((double)x); } // handle everything else CultureInfo _ci = Thread.CurrentThread.CurrentCulture; return (DateTime)Convert.ChangeType(v, typeof(DateTime), _ci); } #endregion //--------------------------------------------------------------------------- #region ** IComparable<Expression> public int CompareTo(Expression other) { // get both values var c1 = this.Evaluate() as IComparable; var c2 = other.Evaluate() as IComparable; // handle nulls if (c1 == null && c2 == null) { return 0; } if (c2 == null) { return -1; } if (c1 == null) { return +1; } // make sure types are the same if (c1.GetType() != c2.GetType()) { try { if (c1 is DateTime) c2 = ((DateTime)other); else if (c2 is DateTime) c1 = ((DateTime)this); else c2 = Convert.ChangeType(c2, c1.GetType()) as IComparable; } catch (InvalidCastException) { return -1; } catch (FormatException) { return -1; } catch (OverflowException) { return -1; } catch (ArgumentNullException) { return -1; } } // compare return c1.CompareTo(c2); } #endregion } /// <summary> /// Unary expression, e.g. +123 /// </summary> class UnaryExpression : Expression { // ** fields Expression _expr; // ** ctor public UnaryExpression(Token tk, Expression expr) : base(tk) { _expr = expr; } // ** object model override public object Evaluate() { switch (_token.ID) { case TKID.ADD: return +(double)_expr; case TKID.SUB: return -(double)_expr; } throw new ArgumentException("Bad expression."); } public override Expression Optimize() { _expr = _expr.Optimize(); return _expr._token.Type == TKTYPE.LITERAL ? new Expression(this.Evaluate()) : this; } } /// <summary> /// Binary expression, e.g. 1+2 /// </summary> class BinaryExpression : Expression { // ** fields Expression _lft; Expression _rgt; // ** ctor public BinaryExpression(Token tk, Expression exprLeft, Expression exprRight) : base(tk) { _lft = exprLeft; _rgt = exprRight; } // ** object model override public object Evaluate() { // handle comparisons if (_token.Type == TKTYPE.COMPARE) { var cmp = _lft.CompareTo(_rgt); switch (_token.ID) { case TKID.GT: return cmp > 0; case TKID.LT: return cmp < 0; case TKID.GE: return cmp >= 0; case TKID.LE: return cmp <= 0; case TKID.EQ: return cmp == 0; case TKID.NE: return cmp != 0; } } // handle everything else switch (_token.ID) { case TKID.CONCAT: return (string)_lft + (string)_rgt; case TKID.ADD: return (double)_lft + (double)_rgt; case TKID.SUB: return (double)_lft - (double)_rgt; case TKID.MUL: return (double)_lft * (double)_rgt; case TKID.DIV: return (double)_lft / (double)_rgt; case TKID.DIVINT: return (double)(int)((double)_lft / (double)_rgt); case TKID.MOD: return (double)(int)((double)_lft % (double)_rgt); case TKID.POWER: var a = (double)_lft; var b = (double)_rgt; if (b == 0.0) return 1.0; if (b == 0.5) return Math.Sqrt(a); if (b == 1.0) return a; if (b == 2.0) return a * a; if (b == 3.0) return a * a * a; if (b == 4.0) return a * a * a * a; return Math.Pow((double)_lft, (double)_rgt); } throw new ArgumentException("Bad expression."); } public override Expression Optimize() { _lft = _lft.Optimize(); _rgt = _rgt.Optimize(); return _lft._token.Type == TKTYPE.LITERAL && _rgt._token.Type == TKTYPE.LITERAL ? new Expression(this.Evaluate()) : this; } } /// <summary> /// Function call expression, e.g. sin(0.5) /// </summary> class FunctionExpression : Expression { // ** fields FunctionDefinition _fn; List<Expression> _parms; // ** ctor internal FunctionExpression() { } public FunctionExpression(FunctionDefinition function, List<Expression> parms) { _fn = function; _parms = parms; } // ** object model override public object Evaluate() { return _fn.Function(_parms); } public override Expression Optimize() { bool allLits = true; if (_parms != null) { for (int i = 0; i < _parms.Count; i++) { var p = _parms[i].Optimize(); _parms[i] = p; if (p._token.Type != TKTYPE.LITERAL) { allLits = false; } } } return allLits ? new Expression(this.Evaluate()) : this; } } /// <summary> /// Simple variable reference. /// </summary> class VariableExpression : Expression { Dictionary<string, object> _dct; string _name; public VariableExpression(Dictionary<string, object> dct, string name) { _dct = dct; _name = name; } public override object Evaluate() { return _dct[_name]; } } /// <summary> /// Expression that represents an external object. /// </summary> class XObjectExpression : Expression, IEnumerable { object _value; // ** ctor internal XObjectExpression(object value) { _value = value; } public object Value { get { return _value; } } // ** object model public override object Evaluate() { // use IValueObject if available var iv = _value as IValueObject; if (iv != null) { return iv.GetValue(); } // return raw object return _value; } public IEnumerator GetEnumerator() { return (_value as IEnumerable).GetEnumerator(); } } /// <summary> /// Interface supported by external objects that have to return a value /// other than themselves (e.g. a cell range object should return the /// cell content instead of the range itself). /// </summary> public interface IValueObject { object GetValue(); } }
// 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 Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Test.EditorUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Extensions { public class ITextSnapshotLineExtensionsTests { [Fact] public void GetFirstNonWhitespacePosition_EmptyLineReturnsNull() { var position = GetFirstNonWhitespacePosition(string.Empty); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull1() { var position = GetFirstNonWhitespacePosition(" "); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull2() { var position = GetFirstNonWhitespacePosition(" \t "); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_WhitespaceLineReturnsNull3() { var position = GetFirstNonWhitespacePosition("\t\t"); Assert.Null(position); } [Fact] public void GetFirstNonWhitespacePosition_TextLine() { var position = GetFirstNonWhitespacePosition("Foo"); Assert.Equal(0, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace1() { var position = GetFirstNonWhitespacePosition(" Foo"); Assert.Equal(4, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace2() { var position = GetFirstNonWhitespacePosition(" \t Foo"); Assert.Equal(3, position.Value); } [Fact] public void GetFirstNonWhitespacePosition_TextLineStartingWithWhitespace3() { var position = GetFirstNonWhitespacePosition("\t\tFoo"); Assert.Equal(2, position.Value); } [Fact] public void GetLastNonWhitespacePosition_EmptyLineReturnsNull() { var position = GetLastNonWhitespacePosition(string.Empty); Assert.Null(position); } [Fact] public void GetLastNonWhitespacePosition_WhitespaceLineReturnsNull1() { var position = GetLastNonWhitespacePosition(" "); Assert.Null(position); } [Fact] public void GetLastNonWhitespacePosition_WhitespaceLineReturnsNull2() { var position = GetLastNonWhitespacePosition(" \t "); Assert.Null(position); } [Fact] public void GetLastNonWhitespacePosition_WhitespaceLineReturnsNull3() { var position = GetLastNonWhitespacePosition("\t\t"); Assert.Null(position); } [Fact] public void GetLastNonWhitespacePosition_TextLine() { var position = GetLastNonWhitespacePosition("Foo"); Assert.Equal(2, position.Value); } [Fact] public void GetLastNonWhitespacePosition_TextLineEndingWithWhitespace1() { var position = GetLastNonWhitespacePosition("Foo "); Assert.Equal(2, position.Value); } [Fact] public void GetLastNonWhitespacePosition_TextLineEndingWithWhitespace2() { var position = GetLastNonWhitespacePosition("Foo \t "); Assert.Equal(2, position.Value); } [Fact] public void GetLastNonWhitespacePosition_TextLineEndingWithWhitespace3() { var position = GetLastNonWhitespacePosition("Foo\t\t"); Assert.Equal(2, position.Value); } [Fact] public void IsEmptyOrWhitespace_EmptyLineReturnsTrue() { var value = IsEmptyOrWhitespace(string.Empty); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue1() { var value = IsEmptyOrWhitespace(" "); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue2() { var value = IsEmptyOrWhitespace("\t\t"); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_WhitespaceLineReturnsTrue3() { var value = IsEmptyOrWhitespace(" \t "); Assert.True(value); } [Fact] public void IsEmptyOrWhitespace_TextLineReturnsFalse() { var value = IsEmptyOrWhitespace("Foo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse1() { var value = IsEmptyOrWhitespace(" Foo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse2() { var value = IsEmptyOrWhitespace(" \t Foo"); Assert.False(value); } [Fact] public void IsEmptyOrWhitespace_TextLineStartingWithWhitespaceReturnsFalse3() { var value = IsEmptyOrWhitespace("\t\tFoo"); Assert.False(value); } private ITextSnapshotLine GetLine(string codeLine) { var snapshot = EditorFactory.CreateBuffer(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, codeLine).CurrentSnapshot; return snapshot.GetLineFromLineNumber(0); } private bool IsEmptyOrWhitespace(string codeLine) { var line = GetLine(codeLine); return line.IsEmptyOrWhitespace(); } private int? GetFirstNonWhitespacePosition(string codeLine) { var line = GetLine(codeLine); return line.GetFirstNonWhitespacePosition(); } private int? GetLastNonWhitespacePosition(string codeLine) { var line = GetLine(codeLine); return line.GetLastNonWhitespacePosition(); } } }
using System.Collections.Generic; using GuiLabs.Canvas.Controls; using GuiLabs.Canvas.DrawStyle; using GuiLabs.Canvas.Events; using GuiLabs.Editor.Actions; using GuiLabs.Undo; using GuiLabs.Utils.Delegates; using GuiLabs.Utils.Commands; using GuiLabs.Utils; namespace GuiLabs.Editor.Blocks { /// <summary> /// Base class for all blocks /// </summary> public abstract partial class Block { #region Events public event BlockKeyDownEventHandler KeyDown; protected void RaiseKeyDown(System.Windows.Forms.KeyEventArgs e) { if (KeyDown != null && !e.Handled) { KeyDown(this, e); } } public event EmptyHandler ParentChanged; protected void RaiseParentChanged() { if (ParentChanged != null) { ParentChanged(); } } public event EmptyHandler RootChanged; protected void RaiseRootChanged() { if (RootChanged != null) { RootChanged(); } } public event ChangeHandler<Block> VisibleChanged; protected void RaiseVisibleChanged() { if (VisibleChanged != null) { VisibleChanged(this); } } public event ChangeHandler<Block> Deleted; protected void RaiseDeleted() { if (Deleted != null) { Deleted(this); } } #endregion #region Parent & Root private ContainerBlock mParent; /// <summary> /// Parent Block of this Block. /// </summary> public ContainerBlock Parent { get { return mParent; } internal set { mParent = value; } } internal void NotifyParentChanged(ContainerBlock oldParent) { OnParentChanged(oldParent, mParent); RaiseParentChanged(); } internal void NotifyRootChanged(RootBlock oldRoot) { if (oldRoot == mRoot) { return; } OnRootChanged(oldRoot, mRoot); RaiseRootChanged(); } /// <summary> /// Returns this.Parent.Parent; can be null. /// </summary> /// <remarks>Doesn't throw; just returns null.</remarks> /// <exception cref="Doesn't throw"></exception> public ContainerBlock ParentParent { get { if (this.Parent != null) { return this.Parent.Parent; } return null; } } private RootBlock mRoot; public virtual RootBlock Root { get { return mRoot; } internal set { mRoot = value; } } public bool IsInSubtreeOf(ContainerBlock someParent) { Block current = this; while (current != null) { if (current == someParent) { return true; } current = current.Parent; } return false; } public bool IsInStrictSubtreeOf(ContainerBlock someParent) { ContainerBlock current = this.Parent; while (current != null) { if (current == someParent) { return true; } current = current.Parent; } return false; } #endregion public IEnumerable<T> FindAllContainingBlocks<T>() where T : class { ContainerBlock current = this.Parent; while (current != null) { T nextFound = current as T; if (nextFound != null) { yield return nextFound; } current = current.Parent; } } #region ActionManagerProvider public virtual ActionManager ActionManager { get { if (Root != null) { return Root.ActionManager; } return null; } } /// <summary> /// Records and runs the action if this.Root != null /// and simply runs it when this.Root == null /// </summary> /// <param name="action">An action to (record and) execute</param> public void RunAction(IAction action) { if (Root != null) { Root.ActionManager.RecordAction(action); } else { action.Execute(); } } #endregion #region Linked List Node (Prev, Next...) private Block mPrev; public Block Prev { get { return mPrev; } set { mPrev = value; } } private Block mNext; public Block Next { get { return mNext; } set { mNext = value; } } #region GetNeighborBlocks public IEnumerable<Block> GetNeighborBlocks(int from, int to) { Block current = this.GetNeighborBlock(from); while (from <= to && current != null) { yield return current; current = current.Next; from++; } } public Block GetNeighborBlock(int offsetFromCurrentBlock) { Block current = this; while (offsetFromCurrentBlock < 0 && current != null) { current = current.Prev; offsetFromCurrentBlock++; } while (offsetFromCurrentBlock > 0 && current != null) { current = current.Next; offsetFromCurrentBlock--; } return current; } #endregion /// <summary> /// Establishes a two-way link between /// this node and its previous node, /// if the previous node exists /// </summary> /// <param name="PrevNode"></param> internal void LinkToPrev(Block prevNode) { this.Prev = prevNode; if (prevNode != null) { prevNode.Next = this; } } /// <summary> /// Establishes a two-way link between /// this node and its next node /// if the next node exists /// </summary> /// <param name="NextNode"></param> internal void LinkToNext(Block NextNode) { this.Next = NextNode; if (NextNode != null) { NextNode.Prev = this; } } #endregion #region Control /// <summary> /// abstract means no implementation provided /// Implementation must be provided in derived classes /// </summary> public abstract Control MyControl { get; } protected virtual void SubscribeControl() { MyControl.ControlActivated += OnActivated; MyControl.ControlDeactivated += OnDeactivated; MyControl.Click += OnClick; MyControl.DoubleClick += OnDoubleClick; MyControl.MouseDown += OnMouseDown; MyControl.MouseMove += OnMouseMove; MyControl.MouseUp += OnMouseUp; MyControl.KeyDown += OnKeyDown; MyControl.KeyPress += OnKeyPress; MyControl.KeyUp += OnKeyUp; MyControl.VisibleChanged += OnVisibleChanged; MyControl.CollapseChanged += OnCollapseChanged; InitStyle(); } protected virtual void OnCollapseChanged(Control itemChanged) { } protected virtual void UnSubscribeControl() { MyControl.ControlActivated -= OnActivated; MyControl.ControlDeactivated -= OnDeactivated; MyControl.Click -= OnClick; MyControl.DoubleClick -= OnDoubleClick; MyControl.MouseDown -= OnMouseDown; MyControl.MouseMove -= OnMouseMove; MyControl.MouseUp -= OnMouseUp; MyControl.KeyDown -= OnKeyDown; MyControl.KeyPress -= OnKeyPress; MyControl.KeyUp -= OnKeyUp; MyControl.VisibleChanged -= OnVisibleChanged; MyControl.CollapseChanged -= OnCollapseChanged; } #endregion #region OnEvents protected virtual void OnClick(MouseWithKeysEventArgs MouseInfo) { } protected virtual void OnDoubleClick(MouseWithKeysEventArgs MouseInfo) { } protected virtual void OnMouseDown(MouseWithKeysEventArgs e) { } protected virtual void OnMouseMove(MouseWithKeysEventArgs e) { } protected virtual void OnMouseUp(MouseWithKeysEventArgs e) { //if (Menu != null // && e.IsRightButtonPressed // && this.HasPoint(e.X, e.Y) // //&& (Root != null && Root.DragState == null) // ) //{ // ShowPopupMenu(e.Location); // e.Handled = true; //} } private bool mCanMoveUpDown = false; public bool CanMoveUpDown { get { return mCanMoveUpDown; } set { mCanMoveUpDown = value; } } protected bool IsMoveUpDown(System.Windows.Forms.KeyEventArgs e) { if (!CanMoveUpDown) { return false; } if (e.KeyCode == System.Windows.Forms.Keys.Up && e.Control) { MoveUp(); return true; } if (e.KeyCode == System.Windows.Forms.Keys.Down && e.Control) { MoveDown(); return true; } return false; } protected virtual void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.Handled) { return; } if (IsMoveUpDown(e)) { e.Handled = true; return; } RaiseKeyDown(e); if (e.Handled) { return; } switch (e.KeyCode) { case System.Windows.Forms.Keys.F11: ObjectViewer.Show(this); break; case System.Windows.Forms.Keys.Delete: if (e.Shift) { Cut(); } else { OnKeyDownDelete(e); } break; case System.Windows.Forms.Keys.PageDown: OnKeyDownPageDown(e); break; case System.Windows.Forms.Keys.PageUp: OnKeyDownPageUp(e); break; case System.Windows.Forms.Keys.C: if (e.Control) { Copy(); } break; case System.Windows.Forms.Keys.X: if (e.Control) { Cut(); } break; case System.Windows.Forms.Keys.V: if (e.Control) { Paste(); } break; case System.Windows.Forms.Keys.Insert: if (e.Control) { Copy(); } else if (e.Shift) { Paste(); } break; default: break; } } protected virtual void OnKeyDownDelete(System.Windows.Forms.KeyEventArgs e) { if (e.Handled) { return; } this.Delete(); e.Handled = true; } protected virtual void OnKeyDownPageUp(System.Windows.Forms.KeyEventArgs e) { Block prev = this.FindPrevFocusableSibling(); if (prev != null) { prev.SetFocus(); e.Handled = true; } } protected virtual void OnKeyDownPageDown(System.Windows.Forms.KeyEventArgs e) { Block next = this.FindNextFocusableSibling(); if (next != null) { next.SetFocus(); e.Handled = true; } } protected virtual void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { } protected virtual void OnKeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { } protected virtual void OnParentChanged(ContainerBlock oldParent, ContainerBlock newParent) { } protected virtual void OnRootChanged(RootBlock oldRoot, RootBlock newRoot) { } protected virtual void OnActivated(Control control) { if (this.Root != null) this.Root.ActiveBlock = this; } protected virtual void OnDeactivated(Control control) { } protected virtual void OnVisibleChanged(Control itemChanged) { } #endregion #region Style protected internal void InitStyle() { if (StyleFactory.Instance == null || MyControl == null) { return; } string styleName = StyleName(); if (!string.IsNullOrEmpty(styleName)) { IShapeStyle newStyle = StyleFactory.Instance.GetStyle(styleName); if (newStyle != null) { MyControl.Style = newStyle; } } string selectedStyleName = SelectedStyleName(); if (!string.IsNullOrEmpty(selectedStyleName)) { IShapeStyle newSelectedStyle = StyleFactory.Instance.GetStyle(selectedStyleName); if (newSelectedStyle != null) { MyControl.SelectedStyle = newSelectedStyle; } } } //private static IStyleFactory mCurrentSkin; //public static IStyleFactory CurrentSkin //{ // get // { // return mCurrentSkin; // } // set // { // mCurrentSkin = value; // } //} protected virtual string StyleName() { return ""; } protected string SelectedStyleName() { return StyleName() + "_selected"; } protected string ValidatedStyleName() { return StyleName() + "_validated"; } #endregion #region CanBeSelected private bool mCanBeSelected = true; public bool CanBeSelected { get { return mCanBeSelected; } set { mCanBeSelected = value; } } #endregion #region Dragging private bool mDraggable = false; public virtual bool Draggable { get { return mDraggable; } set { mDraggable = value; } } public virtual void BeforeStartDrag() { } #endregion #region HitTest public virtual Block FindBlockAtPoint(int x, int y) { return this; } public virtual bool HasPoint(int x, int y) { if (!this.MyControl.HitTest(x, y)) { return false; } Control c = this.MyControl.FindControlAtPoint(x, y); if (c is CollapsePicture) { return false; } if (c == null || c == this.MyControl) { return true; } if (!c.CanGetFocus) { c = c.FindNearestFocusableParent(); if (c == null || c == this.MyControl) { return true; } } return false; } #endregion #region Menu private CommandList mMenu; public CommandList Menu { get { return mMenu; } set { mMenu = value; } } public void ShowPopupMenu(System.Drawing.Point location) { if (this.Menu != null && this.Root != null) { this.Root.MyRootControl.ShowPopupMenu(Menu, location); } } #endregion public static Block[] EmptyArray = new Block[] { }; public static string ClipboardFormat = "blocks"; } public delegate void BlockKeyDownEventHandler(Block block, System.Windows.Forms.KeyEventArgs e); }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id: SQLiteErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections; using System.Data; using System.Data.SQLite; using System.Globalization; using System.IO; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses SQLite as its backing store. /// </summary> public class SQLiteErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SQLiteErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config, true); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the SQLite error log."); _connectionString = connectionString; InitializeDatabase(); ApplicationName = Mask.NullString((string) config["applicationName"]); } /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SQLiteErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString); InitializeDatabase(); } private static readonly object _lock = new object(); private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(dbFilePath)) return; SQLiteConnection.CreateFile(dbFilePath); const string sql = @" CREATE TABLE Error ( ErrorId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Application TEXT NOT NULL, Host TEXT NOT NULL, Type TEXT NOT NULL, Source TEXT NOT NULL, Message TEXT NOT NULL, User TEXT NOT NULL, StatusCode INTEGER NOT NULL, TimeUtc TEXT NOT NULL, AllXml TEXT NOT NULL )"; using (SQLiteConnection connection = new SQLiteConnection(connectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { connection.Open(); command.ExecuteNonQuery(); } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQLite Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); const string query = @" INSERT INTO Error ( Application, Host, Type, Source, Message, User, StatusCode, TimeUtc, AllXml) VALUES ( @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml); SELECT last_insert_rowid();"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(query, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@Application", DbType.String, 60).Value = string.IsNullOrEmpty(error.ApplicationName) ? this.ApplicationName : error.ApplicationName;; parameters.Add("@Host", DbType.String, 30).Value = error.HostName; parameters.Add("@Type", DbType.String, 100).Value = error.Type; parameters.Add("@Source", DbType.String, 60).Value = error.Source; parameters.Add("@Message", DbType.String, 500).Value = error.Message; parameters.Add("@User", DbType.String, 50).Value = error.User; parameters.Add("@StatusCode", DbType.Int64).Value = error.StatusCode; parameters.Add("@TimeUtc", DbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", DbType.String).Value = errorXml; connection.Open(); return Convert.ToInt64(command.ExecuteScalar()).ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT ErrorId, Application, Host, Type, Source, Message, User, StatusCode, TimeUtc FROM Error ORDER BY ErrorId DESC LIMIT @PageIndex * @PageSize, @PageSize; SELECT COUNT(*) FROM Error"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@PageIndex", DbType.Int16).Value = pageIndex; parameters.Add("@PageSize", DbType.Int16).Value = pageSize; connection.Open(); using (SQLiteDataReader reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { string id = Convert.ToString(reader["ErrorId"], CultureInfo.InvariantCulture); Error error = new Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } // // Get the result of SELECT COUNT(*) FROM Page // reader.NextResult(); reader.Read(); return reader.GetInt32(0); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); long key; try { key = long.Parse(id, CultureInfo.InvariantCulture); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT AllXml FROM Error WHERE ErrorId = @ErrorId"; using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) using (SQLiteCommand command = new SQLiteCommand(sql, connection)) { SQLiteParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", DbType.Int64).Value = key; connection.Open(); string errorXml = (string) command.ExecuteScalar(); if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } } #endif //!NET_1_1 && !NET_1_0
/* Project Orleans Cloud Service SDK ver. 1.0 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. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Threading; namespace Orleans.Runtime { // This class implements an LRU cache of values. It keeps a bounded set of values and will // flush "old" values internal class LRU<TKey, TValue> : IEnumerable<KeyValuePair<TKey,TValue>> where TKey : class { // Delegate type for fetching the value associated with a given key. public delegate TValue FetchValueDelegate(TKey key); // The following machinery is used to notify client objects when a key and its value // is being flushed from the cache. // The client's event handler is called after the key has been removed from the cache, // but when the cache is in a consistent state so that other methods on the cache may freely // be invoked. public class FlushEventArgs : EventArgs { private readonly TKey key; private readonly TValue value; public FlushEventArgs(TKey k, TValue v) { key = k; value = v; } public TKey Key { get { return key; } } public TValue Value { get { return value; } } } public event EventHandler<FlushEventArgs> RaiseFlushEvent; private long nextGeneration = 0; private long generationToFree = 0; private readonly TimeSpan requiredFreshness; // We want this to be a reference type so that we can update the values in the cache // without having to call AddOrUpdate, which is a nuisance private class TimestampedValue { public readonly DateTime WhenLoaded; public readonly TValue Value; public long Generation; public TimestampedValue(LRU<TKey,TValue> l, TValue v) { Generation = Interlocked.Increment(ref l.nextGeneration); Value = v; WhenLoaded = DateTime.UtcNow; } } private readonly ConcurrentDictionary<TKey, TimestampedValue> cache; readonly FetchValueDelegate fetcher; public int Count { get { return cache.Count; } } public int MaximumSize { get; private set; } /// <summary> /// Creates a new LRU cache. /// </summary> /// <param name="maxSize">Maximum number of entries to allow.</param> /// <param name="maxAge">Maximum age of an entry.</param> /// <param name="f"></param> public LRU(int maxSize, TimeSpan maxAge, FetchValueDelegate f) { if (maxSize <= 0) { throw new ArgumentOutOfRangeException("maxSize", "LRU maxSize must be greater than 0"); } MaximumSize = maxSize; requiredFreshness = maxAge; fetcher = f; cache = new ConcurrentDictionary<TKey, TimestampedValue>(); } public void Add(TKey key, TValue value) { AdjustSize(); var result = new TimestampedValue(this, value); cache.AddOrUpdate(key, result, (k, o) => result); } public bool ContainsKey(TKey key) { TimestampedValue ignore; return cache.TryGetValue(key, out ignore); } public bool RemoveKey(TKey key, out TValue value) { value = default(TValue); TimestampedValue tv; if (!cache.TryRemove(key, out tv)) return false; value = tv.Value; return true; } public void Clear() { foreach (var pair in cache) { var args = new FlushEventArgs(pair.Key, pair.Value.Value); EventHandler<FlushEventArgs> handler = RaiseFlushEvent; if (handler == null) continue; handler(this, args); } cache.Clear(); } public bool TryGetValue(TKey key, out TValue value) { TimestampedValue result; value = default(TValue); if (cache.TryGetValue(key, out result)) { result.Generation = Interlocked.Increment(ref nextGeneration); var age = DateTime.UtcNow.Subtract(result.WhenLoaded); if (age > requiredFreshness) { if (!cache.TryRemove(key, out result)) return false; if (RaiseFlushEvent == null) return false; var args = new FlushEventArgs(key, result.Value); RaiseFlushEvent(this, args); return false; } value = result.Value; } else { return false; } return true; } public TValue Get(TKey key) { TValue value; if (TryGetValue(key, out value)) return value; if (fetcher == null) return value; value = fetcher(key); Add(key, value); return value; } private void AdjustSize() { while (cache.Count >= MaximumSize) { long generationToDelete = Interlocked.Increment(ref generationToFree); KeyValuePair<TKey, TimestampedValue> entryToFree = cache.FirstOrDefault(kvp => kvp.Value.Generation == generationToDelete); if (entryToFree.Key == null) continue; TKey keyToFree = entryToFree.Key; TimestampedValue old; if (!cache.TryRemove(keyToFree, out old)) continue; if (RaiseFlushEvent == null) continue; var args = new FlushEventArgs(keyToFree, old.Value); RaiseFlushEvent(this, args); } } #region Implementation of IEnumerable public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return cache.Select(p => new KeyValuePair<TKey, TValue>(p.Key, p.Value.Value)).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Google.Apis.Discovery; using Google.Apis.Json; using Google.Apis.Requests; using Google.Apis.Testing; using Google.Apis.Util; using Newtonsoft.Json; using NUnit.Framework; using System.Linq; namespace Google.Apis.Tests.Apis.Discovery { /// <summary> /// Test for the "BaseService" class. /// </summary> [TestFixture] public class BaseServiceTest { private class ConcreteClass : BaseService { public ConcreteClass(JsonDictionary js) : base(ServiceFactory.Default, js, new ConcreteFactoryParameters()) { } public new string ServerUrl { get { return base.ServerUrl; } set { base.ServerUrl = value; } } public new string BasePath { get { return base.BasePath; } set { base.BasePath = value; } } #region Nested type: ConcreteFactoryParameters private class ConcreteFactoryParameters : FactoryParameters { public ConcreteFactoryParameters() : base("http://test/", "testService/") {} } #endregion } /// <summary> /// A Json schema for testing serialization/deserialization. /// </summary> internal class MockJsonSchema : IDirectResponseSchema { [JsonProperty("kind")] public string Kind { get; set; } [JsonProperty("longUrl")] public string LongURL { get; set; } [JsonProperty("status")] public string Status { get; set; } public RequestError Error { get; set; } public string ETag { get; set; } } #region Test Helper methods private void CheckDeserializationResults(MockJsonSchema result) { Assert.NotNull(result); Assert.That(result.Kind, Is.EqualTo("urlshortener#url")); Assert.That(result.LongURL, Is.EqualTo("http://google.com/")); Assert.That(result.Status, Is.Null); } private IService CreateService(DiscoveryVersion version) { return version == DiscoveryVersion.Version_0_3 ? CreateLegacyV03Service() : CreateV1Service(); } private IService CreateV1Service() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); return new ConcreteClass(dict); } private IService CreateLegacyV03Service() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); dict.Add("features", new[] { Features.LegacyDataResponse.GetStringValue() }); return new ConcreteClass(dict); } #endregion /// <summary> /// This tests the v0.3 Deserialization of the BaseService. /// </summary> [Test] public void TestDeserializationV0_3() { const string ResponseV0_3 = @"{ ""data"" : { ""kind"": ""urlshortener#url"", ""longUrl"": ""http://google.com/"", } }"; IService impl = CreateLegacyV03Service(); // Check that the default serializer is set. Assert.IsInstanceOf<NewtonsoftJsonSerializer>(impl.Serializer); // Check that the response is decoded correctly. var stream = new MemoryStream(Encoding.Default.GetBytes(ResponseV0_3)); var response = new MockResponse() { Stream = stream }; CheckDeserializationResults(impl.DeserializeResponse<MockJsonSchema>(response)); } /// <summary> /// This tests the v1 Deserialization of the BaseService. /// </summary> [Test] public void TestDeserializationV1() { const string ResponseV1 = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}"; IService impl = CreateV1Service(); // Check that the default serializer is set Assert.IsInstanceOf<NewtonsoftJsonSerializer>(impl.Serializer); // Check that the response is decoded correctly var stream = new MemoryStream(Encoding.Default.GetBytes(ResponseV1)); CheckDeserializationResults( impl.DeserializeResponse<MockJsonSchema>(new MockResponse() { Stream = stream })); } /// <summary> /// Confirms that the serializer won't do anything if a string is the requested response type. /// </summary> [Test] public void TestDeserializationString() { const string ResponseV1 = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}"; IService impl = CreateV1Service(); // Check that the response is decoded correctly var stream = new MemoryStream(Encoding.Default.GetBytes(ResponseV1)); string result = impl.DeserializeResponse<string>(new MockResponse() { Stream = stream }); Assert.AreEqual(ResponseV1, result); } /// <summary> /// Tests the deserialization for server error responses. /// </summary> [Test] public void TestErrorDeserialization( [Values(DiscoveryVersion.Version_0_3, DiscoveryVersion.Version_1_0)] DiscoveryVersion version) { const string ErrorResponse = @"{ ""error"": { ""errors"": [ { ""domain"": ""global"", ""reason"": ""required"", ""message"": ""Required"", ""locationType"": ""parameter"", ""location"": ""resource.longUrl"" } ], ""code"": 400, ""message"": ""Required"" } }"; IService impl = CreateService(version); using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse))) { RequestError error = impl.DeserializeError(new MockResponse() { Stream = stream }); Assert.AreEqual(400, error.Code); Assert.AreEqual("Required", error.Message); Assert.AreEqual(1, error.Errors.Count); } } /// <summary> /// This tests the "Features" extension of services. /// </summary> [Test] public void TestFeaturesV1() { IService impl = CreateV1Service(); Assert.NotNull(impl.Features); Assert.IsFalse(impl.HasFeature(Features.LegacyDataResponse)); } /// <summary> /// This test is designed to test the "Features" extension of services. /// </summary> [Test] public void TestFeaturesV03() { IService impl = CreateLegacyV03Service(); Assert.NotNull(impl.Features); Assert.IsTrue(impl.HasFeature(Features.LegacyDataResponse)); } /// <summary> /// This test confirms that the BaseService will not crash on non-existent, optional fields /// within the JSON document. /// </summary> [Test] public void TestNoThrowOnFieldsMissing() { IService impl = CreateV1Service(); Assert.AreEqual("v1", impl.Version); Assert.IsNull(impl.Id); Assert.IsNotNull(impl.Labels); MoreAsserts.IsEmpty(impl.Labels); Assert.AreEqual("TestName", impl.Name); Assert.IsNull(impl.Protocol); Assert.IsNull(impl.Title); } /// <summary> /// Tests if serialization works. /// </summary> [Test] public void TestSerializationV0_3() { const string ResponseV0_3 = "{\"data\":{\"kind\":\"urlshortener#url\",\"longUrl\":\"http://google.com/\"}}"; MockJsonSchema schema = new MockJsonSchema(); schema.Kind = "urlshortener#url"; schema.LongURL = "http://google.com/"; IService impl = CreateLegacyV03Service(); // Check if a response is serialized correctly string result = impl.SerializeRequest(schema); Assert.AreEqual(ResponseV0_3, result); } /// <summary> /// Tests if serialization works. /// </summary> [Test] public void TestSerializationV1() { const string ResponseV1 = @"{""kind"":""urlshortener#url"",""longUrl"":""http://google.com/""}"; MockJsonSchema schema = new MockJsonSchema(); schema.Kind = "urlshortener#url"; schema.LongURL = "http://google.com/"; IService impl = CreateV1Service(); // Check if a response is serialized correctly string result = impl.SerializeRequest(schema); Assert.AreEqual(ResponseV1, result); } /// <summary> /// The test targets the more basic properties of the BaseService. /// It should ensure that all properties return the values assigned to them within the JSON document. /// </summary> [Test] public void TestSimpleGetters() { var dict = new JsonDictionary(); dict.Add("name", "TestName"); dict.Add("version", "v1"); dict.Add("description", "Test Description"); dict.Add("documentationLink", "https://www.google.com/"); dict.Add("features", new List<object>{ "feature1", "feature2" }); dict.Add("labels", new List<object>{ "label1", "label2" }); dict.Add("id", "TestId"); dict.Add("title", "Test API"); IService impl = new ConcreteClass(dict); Assert.AreEqual("Test Description", impl.Description); Assert.AreEqual("https://www.google.com/", impl.DocumentationLink); MoreAsserts.ContentsEqualAndInOrder(new List<string> { "feature1", "feature2" }, impl.Features); MoreAsserts.ContentsEqualAndInOrder(new List<string> { "label1", "label2" }, impl.Labels); Assert.AreEqual("TestId", impl.Id); Assert.AreEqual("Test API", impl.Title); } /// <summary> /// Confirms that OAuth2 scopes can be parsed correctly. /// </summary> [Test] public void TestOAuth2Scopes() { var scopes = new JsonDictionary(); scopes.Add("https://www.example.com/auth/one", new Scope() { ID = "https://www.example.com/auth/one" }); scopes.Add("https://www.example.com/auth/two", new Scope() { ID = "https://www.example.com/auth/two" }); var oauth2 = new JsonDictionary() { { "scopes", scopes } }; var auth = new JsonDictionary() { { "oauth2", oauth2 } }; var dict = new JsonDictionary() { { "auth", auth }, { "name", "TestName" }, { "version", "v1" } }; IService impl = new ConcreteClass(dict); Assert.IsNotNull(impl.Scopes); Assert.AreEqual(2, impl.Scopes.Count); Assert.IsTrue(impl.Scopes.ContainsKey("https://www.example.com/auth/one")); Assert.IsTrue(impl.Scopes.ContainsKey("https://www.example.com/auth/two")); } /// <summary> /// Test that the Parameters property is initialized. /// </summary> [Test] public void TestCommonParameters() { const string testJson = @"{ 'fields': { 'type': 'string', 'description': 'Selector specifying which fields to include in a partial response.', 'location': 'query' }, 'prettyPrint': { 'type': 'boolean', 'description': 'Returns response with indentations and line breaks.', 'default': 'true', 'location': 'query' }, }"; var paramDict = Google.Apis.Json.JsonReader.Parse(testJson.Replace('\'', '\"')) as JsonDictionary; var dict = new JsonDictionary() { { "parameters", paramDict}, { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters.Count, Is.EqualTo(2)); Assert.That(impl.Parameters.Keys, Is.EquivalentTo(new string[] { "fields", "prettyPrint" })); var prettyPrint = impl.Parameters["prettyPrint"]; Assert.That(prettyPrint.Description, Is.EqualTo("Returns response with indentations and line breaks.")); Assert.That(prettyPrint.ValueType, Is.EqualTo("boolean")); } /// <summary> /// Test a service with empty parameters. /// </summary> [Test] public void TestCommonParametersEmpty() { var paramDict = new JsonDictionary(); var dict = new JsonDictionary() { { "parameters", paramDict }, { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters, Is.Not.Null); Assert.That(impl.Parameters.Count, Is.EqualTo(0)); } /// <summary> /// Test a service with no parameters /// </summary> [Test] public void TestCommonParametersMissing() { var paramDict = new JsonDictionary(); var dict = new JsonDictionary() { { "name", "TestName" }, { "version", "v1" } }; var impl = new ConcreteClass(dict); Assert.That(impl.Parameters, Is.Not.Null); Assert.That(impl.Parameters.Count, Is.EqualTo(0)); } /// <summary> /// Confirms that methods, which are directly on the service, are supported /// </summary> [Test] public void TestMethodsOnService() { var testMethod = new JsonDictionary(); testMethod.Add("id", "service.testMethod"); testMethod.Add("path", "service/testMethod"); testMethod.Add("httpMethod", "GET"); var methods = new JsonDictionary() { { "testMethod", testMethod } }; var dict = new JsonDictionary() { { "methods", methods }, { "name", "TestName" }, { "version", "v1" } }; IService impl = new ConcreteClass(dict); Assert.IsNotNull(impl.Methods); Assert.AreEqual(1, impl.Methods.Count); Assert.AreEqual("testMethod", impl.Methods["testMethod"].Name); } /// <summary> /// Tests the BaseResource.GetResource method. /// </summary> [Test] public void TestGetResource() { var container = CreateV1Service(); container.Resources.Clear(); // Create json. var subJson = new JsonDictionary(); subJson.Add("resources", new JsonDictionary { { "Grandchild", new JsonDictionary() } }); var topJson = new JsonDictionary(); topJson.Add("resources", new JsonDictionary { { "Sub", subJson } }); // Create the resource hierachy. var topResource = ServiceFactory.Default.CreateResource("Top", topJson); var subResource = topResource.Resources["Sub"]; var grandchildResource = subResource.Resources["Grandchild"]; container.Resources.Add("Top", topResource); // Check the generated full name. Assert.AreEqual(container.Methods, BaseService.GetResource(container, "").Methods); Assert.AreEqual(topResource, BaseService.GetResource(container, "Top")); Assert.AreEqual(subResource, BaseService.GetResource(container, "Top.Sub")); Assert.AreEqual(grandchildResource, BaseService.GetResource(container, "Top.Sub.Grandchild")); } [Test] public void TestBaseUri() { ConcreteClass instance = (ConcreteClass)CreateV1Service(); instance.BasePath = "/test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "/test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value/test/", instance.BaseUri.ToString()); // Mono's Uri class strips double forward slashes so this test will not work. // Only run for MS.Net if ( Google.Apis.Util.Utilities.IsMonoRuntime() == false) { instance.BasePath = "//test/"; instance.ServerUrl = "https://www.test.value"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "//test/"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "test/"; instance.ServerUrl = "https://www.test.value//"; Assert.AreEqual("https://www.test.value//test/", instance.BaseUri.ToString()); instance.BasePath = "/test//"; instance.ServerUrl = "https://www.test.value/"; Assert.AreEqual("https://www.test.value/test//", instance.BaseUri.ToString()); } } [Test] public void RemoveAnnotations() { string json = @" { 'schemas': { 'Event': { 'id': 'Event', 'type': 'object', 'properties': { 'description': { 'type': 'string', 'description': 'Description of the event. Optional.' }, 'end': { '$ref': 'EventDateTime', 'description': 'The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance.', 'annotations': { 'required': [ 'calendar.events.import', 'calendar.events.insert', 'calendar.events.update' ] } }, } } } }"; JsonDictionary js = Google.Apis.Json.JsonReader.Parse(json) as JsonDictionary; var end = AssertNode(js, "schemas", "Event", "properties", "end"); Assert.That(end.Count, Is.EqualTo(3)); Assert.That(end.ContainsKey("annotations"), Is.True); BaseService.RemoveAnnotations(js, 0); Assert.That(end.Count, Is.EqualTo(2)); Assert.That(end.ContainsKey("annotations"), Is.False); } private JsonDictionary AssertNode(JsonDictionary dict, params string[] nodes) { JsonDictionary cur = dict; for(int i=0;i<nodes.Length;i++) { Assert.That(cur.ContainsKey(nodes[i])); Assert.That(cur[nodes[i]], Is.TypeOf(typeof(JsonDictionary))); cur = cur[nodes[i]] as JsonDictionary; } return cur; } } }
using System; using System.Collections.ObjectModel; using System.Drawing; using System.Globalization; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.IE { /// <summary> /// InternetExplorerWebElement allows you to have access to specific items that are found on the page. /// </summary> /// <seealso cref="IRenderedWebElement"/> /// <seealso cref="ILocatable"/> /// <example> /// <code> /// [Test] /// public void TestGoogle() /// { /// driver = new InternetExplorerDriver(); /// InternetExplorerWebElement elem = driver.FindElement(By.Name("q")); /// elem.SendKeys("Cheese please!"); /// } /// </code> /// </example> public sealed class InternetExplorerWebElement : IRenderedWebElement, ILocatable, IDisposable, IWrapsDriver { private SafeInternetExplorerWebElementHandle elementHandle; private InternetExplorerDriver driver; #region Constructor /// <summary> /// Initializes a new instance of the InternetExplorerWebElement class. /// </summary> /// <param name="driver">Drive in use.</param> /// <param name="wrapper">Wrapper of the handle to get.</param> internal InternetExplorerWebElement(InternetExplorerDriver driver, SafeInternetExplorerWebElementHandle wrapper) { this.driver = driver; this.elementHandle = wrapper; } #endregion #region Properties #region Public Properties /// <summary> /// Gets the text from the element. /// </summary> public string Text { get { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetElementText(elementHandle, ref stringHandle); ResultHandler.VerifyResultCode(result, "get the Text property"); string returnValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { // StringWrapper correctly disposes of the handle returnValue = wrapper.Value; } return returnValue; } } /// <summary> /// Gets the DOM Tag of element. /// </summary> public string TagName { get { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetElementTagName(elementHandle, ref stringHandle); ResultHandler.VerifyResultCode(result, "get the Value property"); string returnValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { // StringWrapper correctly disposes of the handle returnValue = wrapper.Value; } return returnValue; } } /// <summary> /// Gets a value indicating whether an element is currently enabled. /// </summary> public bool Enabled { get { int enabled = 0; WebDriverResult result = NativeDriverLibrary.Instance.IsElementEnabled(elementHandle, ref enabled); ResultHandler.VerifyResultCode(result, "get the Enabled property"); return enabled == 1; } } /// <summary> /// Gets the value of the element's "value" attribute. If this value has been modified after the page has loaded (for example, through javascript) then this will reflect the current value of the "value" attribute. /// </summary> public string Value { get { return GetAttribute("value"); } } /// <summary> /// Gets a value indicating whether this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons. /// </summary> public bool Selected { get { int selected = 0; WebDriverResult result = NativeDriverLibrary.Instance.IsElementSelected(elementHandle, ref selected); ResultHandler.VerifyResultCode(result, "Checking if element is selected"); return selected == 1; } } /// <summary> /// Gets the Location of an element that is off the screen by scrolling and returns a Point object. /// </summary> public Point LocationOnScreenOnceScrolledIntoView { get { Point location = Point.Empty; int x = 0; int y = 0; int width = 0; int height = 0; IntPtr hwnd = IntPtr.Zero; WebDriverResult result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(elementHandle, ref hwnd, ref x, ref y, ref width, ref height); ResultHandler.VerifyResultCode(result, "get the location once scrolled onto the screen"); location = new Point(x, y); return location; } } /// <summary> /// Gets the Location of an element and returns a Point object. /// </summary> public Point Location { get { Point elementLocation = Point.Empty; int x = 0; int y = 0; WebDriverResult result = NativeDriverLibrary.Instance.GetElementLocation(elementHandle, ref x, ref y); ResultHandler.VerifyResultCode(result, "get the location"); elementLocation = new Point(x, y); return elementLocation; } } /// <summary> /// Gets the <see cref="Size"/> of the element on the page. /// </summary> public Size Size { get { Size elementSize = Size.Empty; int width = 0; int height = 0; WebDriverResult result = NativeDriverLibrary.Instance.GetElementSize(elementHandle, ref width, ref height); ResultHandler.VerifyResultCode(result, "get the size"); elementSize = new Size(width, height); return elementSize; } } /// <summary> /// Gets a value indicating whether the object is currently being displayed. /// </summary> public bool Displayed { get { int displayed = 0; WebDriverResult result = NativeDriverLibrary.Instance.IsElementDisplayed(elementHandle, ref displayed); ResultHandler.VerifyResultCode(result, "get the Displayed property"); return displayed == 1; } } /// <summary> /// Gets the <see cref="IWebDriver"/> used to find this element. /// </summary> public IWebDriver WrappedDriver { get { return driver; } } #endregion #region Internal properties /// <summary> /// Gets the wrappers handle. /// </summary> internal SafeInternetExplorerWebElementHandle Wrapper { get { return elementHandle; } } #endregion #endregion #region Methods #region Public Methods /// <summary> /// Method to clear the text out of an Input element. /// </summary> public void Clear() { WebDriverResult result = NativeDriverLibrary.Instance.ClearElement(elementHandle); ResultHandler.VerifyResultCode(result, "clear the element"); } /// <summary> /// Method for sending native key strokes to the browser. /// </summary> /// <param name="text">String containing what you would like to type onto the screen.</param> public void SendKeys(string text) { WebDriverResult result = NativeDriverLibrary.Instance.SendKeysToElement(elementHandle, text); ResultHandler.VerifyResultCode(result, "send keystrokes to the element"); } /// <summary> /// If this current element is a form, or an element within a form, then this will be submitted to the remote server. /// If this causes the current page to change, then this method will block until the new page is loaded. /// </summary> public void Submit() { WebDriverResult result = NativeDriverLibrary.Instance.SubmitElement(elementHandle); ResultHandler.VerifyResultCode(result, "submit the element"); } /// <summary> /// Click this element. If this causes a new page to load, this method will block until the page has loaded. At this point, you should discard all references to this element and any further operations performed on this element /// will have undefined behaviour unless you know that the element and the page will still be present. If this element is not clickable, then this operation is a no-op since it's pretty common for someone to accidentally miss /// the target when clicking in Real Life. /// </summary> public void Click() { WebDriverResult result = NativeDriverLibrary.Instance.ClickElement(elementHandle); ResultHandler.VerifyResultCode(result, "click the element"); } /// <summary> /// If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded. /// </summary> /// <param name="attributeName">Attribute you wish to get details of.</param> /// <returns>The attribute's current value or null if the value is not set.</returns> public string GetAttribute(string attributeName) { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); SafeInternetExplorerDriverHandle driverHandle = driver.GetUnderlayingHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetElementAttribute(driverHandle, elementHandle, attributeName, ref stringHandle); ResultHandler.VerifyResultCode(result, string.Format(CultureInfo.InvariantCulture, "getting attribute '{0}' of the element", attributeName)); string returnValue = null; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { returnValue = wrapper.Value; } return returnValue; } /// <summary> /// Method to select or unselect element. This operation only applies to input elements such as checkboxes, options in a select and radio buttons. /// </summary> public void Select() { WebDriverResult result = NativeDriverLibrary.Instance.SetElementSelected(elementHandle); ResultHandler.VerifyResultCode(result, "(Un)selecting element"); } /// <summary> /// If the element is a checkbox this will toggle the elements state from selected to not selected, or from not selected to selected. /// </summary> /// <returns>Whether the toggled element is selected (true) or not (false) after this toggle is complete.</returns> public bool Toggle() { int toggled = 0; WebDriverResult result = NativeDriverLibrary.Instance.ToggleElement(elementHandle, ref toggled); ResultHandler.VerifyResultCode(result, "Toggling element"); return toggled == 1; } /// <summary> /// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page. /// </summary> /// <param name="by">By mechanism for finding the object.</param> /// <returns>ReadOnlyCollection of IWebElement.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> classList = driver.FindElements(By.ClassName("class")); /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElements(By by) { return by.FindElements(new Finder(driver, elementHandle)); } /// <summary> /// Finds the first element in the page that matches the <see cref="By"/> object. /// </summary> /// <param name="by">By mechanism.</param> /// <returns>IWebElement object so that you can interction that object.</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// IWebElement elem = driver.FindElement(By.Name("q")); /// </code> /// </example> public IWebElement FindElement(By by) { return by.FindElement(new Finder(driver, elementHandle)); } /// <summary> /// Method to return the value of a CSS Property /// </summary> /// <param name="propertyName">CSS property key</param> /// <returns>string value of the CSS property</returns> public string GetValueOfCssProperty(string propertyName) { SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle(); WebDriverResult result = NativeDriverLibrary.Instance.GetElementValueOfCssProperty(elementHandle, propertyName, ref stringHandle); ResultHandler.VerifyResultCode(result, string.Format(CultureInfo.InvariantCulture, "get the value of CSS property '{0}'", propertyName)); string returnValue = string.Empty; using (StringWrapper wrapper = new StringWrapper(stringHandle)) { returnValue = wrapper.Value; } return returnValue; } /// <summary> /// Moves the mouse over the element to do a hover. /// </summary> public void Hover() { IntPtr hwnd = IntPtr.Zero; int x = 0; int y = 0; int width = 0; int height = 0; WebDriverResult result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(elementHandle, ref hwnd, ref x, ref y, ref width, ref height); ResultHandler.VerifyResultCode(result, "hover"); int midX = x + (width / 2); int midY = y + (height / 2); result = NativeDriverLibrary.Instance.MouseMoveTo(hwnd, 100, 0, 0, midX, midY); ResultHandler.VerifyResultCode(result, "hover mouse move"); } /// <summary> /// Move to an element, MouseDown on the element and move it by passing in the how many pixels horizontally and vertically you wish to move it. /// </summary> /// <param name="moveRightBy">Integer to move it left or right.</param> /// <param name="moveDownBy">Integer to move it up or down.</param> public void DragAndDropBy(int moveRightBy, int moveDownBy) { IntPtr hwnd = IntPtr.Zero; int x = 0; int y = 0; int width = 0; int height = 0; WebDriverResult result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(elementHandle, ref hwnd, ref x, ref y, ref width, ref height); ResultHandler.VerifyResultCode(result, "Unable to determine location once scrolled on to screen"); NativeDriverLibrary.Instance.MouseDownAt(hwnd, x, y); int endX = x + moveRightBy; int endY = y + moveDownBy; int duration = driver.Manage().Speed.Timeout; NativeDriverLibrary.Instance.MouseMoveTo(hwnd, duration, x, y, endX, endY); NativeDriverLibrary.Instance.MouseUpAt(hwnd, endX, endY); } /// <summary> /// Drag and Drop an element to another element. /// </summary> /// <param name="element">Element you wish to drop on.</param> public void DragAndDropOn(IRenderedWebElement element) { IntPtr hwnd = IntPtr.Zero; int x = 0; int y = 0; int width = 0; int height = 0; WebDriverResult result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(elementHandle, ref hwnd, ref x, ref y, ref width, ref height); ResultHandler.VerifyResultCode(result, "Unable to determine location once scrolled on to screen"); int startX = x + (width / 2); int startY = y + (height / 2); NativeDriverLibrary.Instance.MouseDownAt(hwnd, startX, startY); SafeInternetExplorerWebElementHandle other = ((InternetExplorerWebElement)element).Wrapper; result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(other, ref hwnd, ref x, ref y, ref width, ref height); ResultHandler.VerifyResultCode(result, "Unable to determine location of target once scrolled on to screen"); int endX = x + (width / 2); int endY = y + (height / 2); int duration = driver.Manage().Speed.Timeout; NativeDriverLibrary.Instance.MouseMoveTo(hwnd, duration, startX, startY, endX, endY); NativeDriverLibrary.Instance.MouseUpAt(hwnd, endX, endY); } /// <summary> /// Compares if two elements are equal. /// </summary> /// <param name="obj">Object to compare against.</param> /// <returns>A boolean if it is equal or not.</returns> public override bool Equals(object obj) { IWebElement other = obj as IWebElement; if (other == null) { return false; } if (other is IWrapsElement) { other = ((IWrapsElement)obj).WrappedElement; } if (!(other is InternetExplorerWebElement)) { return false; } bool result = (bool)driver.ExecuteScript("return arguments[0] === arguments[1];", this, other); return result; } /// <summary> /// Method to get the hash code of the element. /// </summary> /// <returns>Interger of the hash code for the element.</returns> public override int GetHashCode() { return elementHandle.GetHashCode(); } #region IDisposable Members /// <summary> /// Dispose the Element. /// </summary> public void Dispose() { elementHandle.Dispose(); GC.SuppressFinalize(this); } #endregion #endregion #region Internal methods /// <summary> /// Add to the script args. /// </summary> /// <param name="scriptArgs">Arguments to be added.</param> /// <returns>A Driver result from adding it.</returns> internal WebDriverResult AddToScriptArgs(SafeScriptArgsHandle scriptArgs) { WebDriverResult result = NativeDriverLibrary.Instance.AddElementScriptArg(scriptArgs, elementHandle); ResultHandler.VerifyResultCode(result, "adding to script arguments"); return result; } #endregion #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.IO; using System.Text; using System.Threading.Tasks; namespace System.Xml { public interface IXmlTextWriterInitializer { void SetOutput(Stream stream, Encoding encoding, bool ownsStream); } internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer { private XmlUTF8NodeWriter _writer; public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (encoding.WebName != Encoding.UTF8.WebName) { stream = new EncodingStreamWrapper(stream, encoding, true); } if (_writer == null) { _writer = new XmlUTF8NodeWriter(); } _writer.SetOutput(stream, ownsStream, encoding); SetOutput(_writer); } protected override XmlSigningNodeWriter CreateSigningNodeWriter() { return new XmlSigningNodeWriter(true); } } internal class XmlUTF8NodeWriter : XmlStreamNodeWriter { private byte[] _entityChars; private bool[] _isEscapedAttributeChar; private bool[] _isEscapedElementChar; private bool _inAttribute; private const int bufferLength = 512; private const int maxEntityLength = 32; private Encoding _encoding; private char[] _chars; private static readonly byte[] s_startDecl = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ', (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', }; private static readonly byte[] s_endDecl = { (byte)'"', (byte)'?', (byte)'>' }; private static readonly byte[] s_utf8Decl = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l', (byte)' ', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"', (byte)' ', (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=', (byte)'"', (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8', (byte)'"', (byte)'?', (byte)'>' }; private static readonly byte[] s_digits = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' }; private static readonly bool[] s_defaultIsEscapedAttributeChar = new bool[] { true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, true, false, false, false, true, false, false, false, false, false, false, false, false, false, // '"', '&' false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>' }; private static readonly bool[] s_defaultIsEscapedElementChar = new bool[] { true, true, true, true, true, true, true, true, true, false, false, true, true, true, true, true, // All but 0x09, 0x0A true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, // '&' false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false // '<', '>' }; public XmlUTF8NodeWriter() : this(s_defaultIsEscapedAttributeChar, s_defaultIsEscapedElementChar) { } public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementChar) { _isEscapedAttributeChar = isEscapedAttributeChar; _isEscapedElementChar = isEscapedElementChar; _inAttribute = false; } new public void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { Encoding utf8Encoding = null; if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage) { utf8Encoding = encoding; encoding = null; } base.SetOutput(stream, ownsStream, utf8Encoding); _encoding = encoding; _inAttribute = false; } private byte[] GetCharEntityBuffer() { if (_entityChars == null) { _entityChars = new byte[maxEntityLength]; } return _entityChars; } private char[] GetCharBuffer(int charCount) { if (charCount >= 256) return new char[charCount]; if (_chars == null || _chars.Length < charCount) _chars = new char[charCount]; return _chars; } public override void WriteDeclaration() { if (_encoding == null) { WriteUTF8Chars(s_utf8Decl, 0, s_utf8Decl.Length); } else { WriteUTF8Chars(s_startDecl, 0, s_startDecl.Length); if (_encoding.WebName == Encoding.BigEndianUnicode.WebName) WriteUTF8Chars("utf-16BE"); else WriteUTF8Chars(_encoding.WebName); WriteUTF8Chars(s_endDecl, 0, s_endDecl.Length); } } public override void WriteCData(string text) { byte[] buffer; int offset; buffer = GetBuffer(9, out offset); buffer[offset + 0] = (byte)'<'; buffer[offset + 1] = (byte)'!'; buffer[offset + 2] = (byte)'['; buffer[offset + 3] = (byte)'C'; buffer[offset + 4] = (byte)'D'; buffer[offset + 5] = (byte)'A'; buffer[offset + 6] = (byte)'T'; buffer[offset + 7] = (byte)'A'; buffer[offset + 8] = (byte)'['; Advance(9); WriteUTF8Chars(text); buffer = GetBuffer(3, out offset); buffer[offset + 0] = (byte)']'; buffer[offset + 1] = (byte)']'; buffer[offset + 2] = (byte)'>'; Advance(3); } private void WriteStartComment() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'<'; buffer[offset + 1] = (byte)'!'; buffer[offset + 2] = (byte)'-'; buffer[offset + 3] = (byte)'-'; Advance(4); } private void WriteEndComment() { int offset; byte[] buffer = GetBuffer(3, out offset); buffer[offset + 0] = (byte)'-'; buffer[offset + 1] = (byte)'-'; buffer[offset + 2] = (byte)'>'; Advance(3); } public override void WriteComment(string text) { WriteStartComment(); WriteUTF8Chars(text); WriteEndComment(); } public override void WriteStartElement(string prefix, string localName) { WriteByte('<'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); } public override async Task WriteStartElementAsync(string prefix, string localName) { await WriteByteAsync('<').ConfigureAwait(false); if (prefix.Length != 0) { // This method calls into unsafe method which cannot run asyncly. WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); } // This method calls into unsafe method which cannot run asyncly. WriteLocalName(localName); } public override void WriteStartElement(string prefix, XmlDictionaryString localName) { WriteStartElement(prefix, localName.Value); } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte('<'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEndStartElement(bool isEmpty) { if (!isEmpty) { WriteByte('>'); } else { WriteBytes('/', '>'); } } public override async Task WriteEndStartElementAsync(bool isEmpty) { if (!isEmpty) { await WriteByteAsync('>').ConfigureAwait(false); } else { await WriteBytesAsync('/', '>').ConfigureAwait(false); } } public override void WriteEndElement(string prefix, string localName) { WriteBytes('<', '/'); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteByte('>'); } public override async Task WriteEndElementAsync(string prefix, string localName) { await WriteBytesAsync('<', '/').ConfigureAwait(false); if (prefix.Length != 0) { WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); } WriteLocalName(localName); await WriteByteAsync('>').ConfigureAwait(false); } public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteBytes('<', '/'); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteByte('>'); } private void WriteStartXmlnsAttribute() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)' '; buffer[offset + 1] = (byte)'x'; buffer[offset + 2] = (byte)'m'; buffer[offset + 3] = (byte)'l'; buffer[offset + 4] = (byte)'n'; buffer[offset + 5] = (byte)'s'; Advance(6); _inAttribute = true; } public override void WriteXmlnsAttribute(string prefix, string ns) { WriteStartXmlnsAttribute(); if (prefix.Length != 0) { WriteByte(':'); WritePrefix(prefix); } WriteBytes('=', '"'); WriteEscapedText(ns); WriteEndAttribute(); } public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { WriteXmlnsAttribute(prefix, ns.Value); } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { WriteStartXmlnsAttribute(); if (prefixLength != 0) { WriteByte(':'); WritePrefix(prefixBuffer, prefixOffset, prefixLength); } WriteBytes('=', '"'); WriteEscapedText(nsBuffer, nsOffset, nsLength); WriteEndAttribute(); } public override void WriteStartAttribute(string prefix, string localName) { WriteByte(' '); if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteLocalName(localName); WriteBytes('=', '"'); _inAttribute = true; } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { WriteStartAttribute(prefix, localName.Value); } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteByte(' '); if (prefixLength != 0) { WritePrefix(prefixBuffer, prefixOffset, prefixLength); WriteByte(':'); } WriteLocalName(localNameBuffer, localNameOffset, localNameLength); WriteBytes('=', '"'); _inAttribute = true; } public override void WriteEndAttribute() { WriteByte('"'); _inAttribute = false; } public override async Task WriteEndAttributeAsync() { await WriteByteAsync('"').ConfigureAwait(false); _inAttribute = false; } private void WritePrefix(string prefix) { if (prefix.Length == 1) { WriteUTF8Char(prefix[0]); } else { WriteUTF8Chars(prefix); } } private void WritePrefix(byte[] prefixBuffer, int prefixOffset, int prefixLength) { if (prefixLength == 1) { WriteUTF8Char((char)prefixBuffer[prefixOffset]); } else { WriteUTF8Chars(prefixBuffer, prefixOffset, prefixLength); } } private void WriteLocalName(string localName) { WriteUTF8Chars(localName); } private void WriteLocalName(byte[] localNameBuffer, int localNameOffset, int localNameLength) { WriteUTF8Chars(localNameBuffer, localNameOffset, localNameLength); } public override void WriteEscapedText(XmlDictionaryString s) { WriteEscapedText(s.Value); } public unsafe override void WriteEscapedText(string s) { int count = s.Length; if (count > 0) { fixed (char* chars = s) { UnsafeWriteEscapedText(chars, count); } } } public unsafe override void WriteEscapedText(char[] s, int offset, int count) { if (count > 0) { fixed (char* chars = &s[offset]) { UnsafeWriteEscapedText(chars, count); } } } private unsafe void UnsafeWriteEscapedText(char* chars, int count) { bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar); int isEscapedCharLength = isEscapedChar.Length; int i = 0; for (int j = 0; j < count; j++) { char ch = chars[j]; if (ch < isEscapedCharLength && isEscapedChar[ch] || ch >= 0xFFFE) { UnsafeWriteUTF8Chars(chars + i, j - i); WriteCharEntity(ch); i = j + 1; } } UnsafeWriteUTF8Chars(chars + i, count - i); } public override void WriteEscapedText(byte[] chars, int offset, int count) { bool[] isEscapedChar = (_inAttribute ? _isEscapedAttributeChar : _isEscapedElementChar); int isEscapedCharLength = isEscapedChar.Length; int i = 0; for (int j = 0; j < count; j++) { byte ch = chars[offset + j]; if (ch < isEscapedCharLength && isEscapedChar[ch]) { WriteUTF8Chars(chars, offset + i, j - i); WriteCharEntity(ch); i = j + 1; } else if (ch == 239 && offset + j + 2 < count) { // 0xFFFE and 0xFFFF must be written as char entities // UTF8(239, 191, 190) = (char) 0xFFFE // UTF8(239, 191, 191) = (char) 0xFFFF byte ch2 = chars[offset + j + 1]; byte ch3 = chars[offset + j + 2]; if (ch2 == 191 && (ch3 == 190 || ch3 == 191)) { WriteUTF8Chars(chars, offset + i, j - i); WriteCharEntity(ch3 == 190 ? (char)0xFFFE : (char)0xFFFF); i = j + 3; } } } WriteUTF8Chars(chars, offset + i, count - i); } public void WriteText(int ch) { WriteUTF8Char(ch); } public override void WriteText(byte[] chars, int offset, int count) { WriteUTF8Chars(chars, offset, count); } public unsafe override void WriteText(char[] chars, int offset, int count) { if (count > 0) { fixed (char* pch = &chars[offset]) { UnsafeWriteUTF8Chars(pch, count); } } } public override void WriteText(string value) { WriteUTF8Chars(value); } public override void WriteText(XmlDictionaryString value) { WriteUTF8Chars(value.Value); } public void WriteLessThanCharEntity() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'l'; buffer[offset + 2] = (byte)'t'; buffer[offset + 3] = (byte)';'; Advance(4); } public void WriteGreaterThanCharEntity() { int offset; byte[] buffer = GetBuffer(4, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'g'; buffer[offset + 2] = (byte)'t'; buffer[offset + 3] = (byte)';'; Advance(4); } public void WriteAmpersandCharEntity() { int offset; byte[] buffer = GetBuffer(5, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'m'; buffer[offset + 3] = (byte)'p'; buffer[offset + 4] = (byte)';'; Advance(5); } public void WriteApostropheCharEntity() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'a'; buffer[offset + 2] = (byte)'p'; buffer[offset + 3] = (byte)'o'; buffer[offset + 4] = (byte)'s'; buffer[offset + 5] = (byte)';'; Advance(6); } public void WriteQuoteCharEntity() { int offset; byte[] buffer = GetBuffer(6, out offset); buffer[offset + 0] = (byte)'&'; buffer[offset + 1] = (byte)'q'; buffer[offset + 2] = (byte)'u'; buffer[offset + 3] = (byte)'o'; buffer[offset + 4] = (byte)'t'; buffer[offset + 5] = (byte)';'; Advance(6); } private void WriteHexCharEntity(int ch) { byte[] chars = GetCharEntityBuffer(); int offset = maxEntityLength; chars[--offset] = (byte)';'; offset -= ToBase16(chars, offset, (uint)ch); chars[--offset] = (byte)'x'; chars[--offset] = (byte)'#'; chars[--offset] = (byte)'&'; WriteUTF8Chars(chars, offset, maxEntityLength - offset); } public override void WriteCharEntity(int ch) { switch (ch) { case '<': WriteLessThanCharEntity(); break; case '>': WriteGreaterThanCharEntity(); break; case '&': WriteAmpersandCharEntity(); break; case '\'': WriteApostropheCharEntity(); break; case '"': WriteQuoteCharEntity(); break; default: WriteHexCharEntity(ch); break; } } private int ToBase16(byte[] chars, int offset, uint value) { int count = 0; do { count++; chars[--offset] = s_digits[(int)(value & 0x0F)]; value /= 16; } while (value != 0); return count; } public override void WriteBoolText(bool value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxBoolChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDecimalText(decimal value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDecimalChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDoubleText(double value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDoubleChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteFloatText(float value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxFloatChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteDateTimeText(DateTime value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxDateTimeChars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteUniqueIdText(UniqueId value) { if (value.IsGuid) { int charCount = value.CharArrayLength; char[] chars = GetCharBuffer(charCount); value.ToCharArray(chars, 0); WriteText(chars, 0, charCount); } else { WriteEscapedText(value.ToString()); } } public override void WriteInt32Text(int value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxInt32Chars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteInt64Text(long value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxInt64Chars, out offset); Advance(XmlConverter.ToChars(value, buffer, offset)); } public override void WriteUInt64Text(ulong value) { int offset; byte[] buffer = GetBuffer(XmlConverter.MaxUInt64Chars, out offset); Advance(XmlConverter.ToChars((double)value, buffer, offset)); } public override void WriteGuidText(Guid value) { WriteText(value.ToString()); } public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { InternalWriteBase64Text(trailBytes, 0, trailByteCount); } InternalWriteBase64Text(buffer, offset, count); } public override async Task WriteBase64TextAsync(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (trailByteCount > 0) { await InternalWriteBase64TextAsync(trailBytes, 0, trailByteCount).ConfigureAwait(false); } await InternalWriteBase64TextAsync(buffer, offset, count).ConfigureAwait(false); } private void InternalWriteBase64Text(byte[] buffer, int offset, int count) { Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3); int charCount = byteCount / 3 * 4; int charOffset; byte[] chars = GetBuffer(charCount, out charOffset); Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset)); offset += byteCount; count -= byteCount; } if (count > 0) { int charOffset; byte[] chars = GetBuffer(4, out charOffset); Advance(encoding.GetChars(buffer, offset, count, chars, charOffset)); } } private async Task InternalWriteBase64TextAsync(byte[] buffer, int offset, int count) { Base64Encoding encoding = XmlConverter.Base64Encoding; while (count >= 3) { int byteCount = Math.Min(bufferLength / 4 * 3, count - count % 3); int charCount = byteCount / 3 * 4; int charOffset; BytesWithOffset bufferResult = await GetBufferAsync(charCount).ConfigureAwait(false); byte[] chars = bufferResult.Bytes; charOffset = bufferResult.Offset; Advance(encoding.GetChars(buffer, offset, byteCount, chars, charOffset)); offset += byteCount; count -= byteCount; } if (count > 0) { int charOffset; BytesWithOffset bufferResult = await GetBufferAsync(4).ConfigureAwait(false); byte[] chars = bufferResult.Bytes; charOffset = bufferResult.Offset; Advance(encoding.GetChars(buffer, offset, count, chars, charOffset)); } } public override void WriteTimeSpanText(TimeSpan value) { WriteText(XmlConvert.ToString(value)); } public override void WriteStartListText() { } public override void WriteListSeparator() { WriteByte(' '); } public override void WriteEndListText() { } public override void WriteQualifiedName(string prefix, XmlDictionaryString localName) { if (prefix.Length != 0) { WritePrefix(prefix); WriteByte(':'); } WriteText(localName); } } }
// 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 Microsoft.Xml.Serialization { using System; using Microsoft.Xml.Schema; using System.Collections; using System.ComponentModel; using System.Reflection; using Microsoft.CodeDom; using Microsoft.CodeDom.Compiler; using Microsoft.Xml.Serialization.Advanced; #if DEBUG using System.Diagnostics; #endif /// <include file='doc\SchemaImporter.uex' path='docs/doc[@for="SchemaImporter"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] public abstract class SchemaImporter { private XmlSchemas _schemas; private StructMapping _root; private CodeGenerationOptions _options; private CodeDomProvider _codeProvider; private TypeScope _scope; private ImportContext _context; private bool _rootImported; private NameTable _typesInUse; private NameTable _groupsInUse; private SchemaImporterExtensionCollection _extensions; internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, CodeDomProvider codeProvider, ImportContext context) { if (!schemas.Contains(XmlSchema.Namespace)) { schemas.AddReference(XmlSchemas.XsdSchema); schemas.SchemaSet.Add(XmlSchemas.XsdSchema); } if (!schemas.Contains(XmlReservedNs.NsXml)) { schemas.AddReference(XmlSchemas.XmlSchema); schemas.SchemaSet.Add(XmlSchemas.XmlSchema); } _schemas = schemas; _options = options; _codeProvider = codeProvider; _context = context; Schemas.SetCache(Context.Cache, Context.ShareTypes); _extensions = new SchemaImporterExtensionCollection(); } internal ImportContext Context { get { if (_context == null) _context = new ImportContext(); return _context; } } internal CodeDomProvider CodeProvider { get { if (_codeProvider == null) _codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); return _codeProvider; } } public SchemaImporterExtensionCollection Extensions { get { if (_extensions == null) _extensions = new SchemaImporterExtensionCollection(); return _extensions; } } internal Hashtable ImportedElements { get { return Context.Elements; } } internal Hashtable ImportedMappings { get { return Context.Mappings; } } internal CodeIdentifiers TypeIdentifiers { get { return Context.TypeIdentifiers; } } internal XmlSchemas Schemas { get { if (_schemas == null) _schemas = new XmlSchemas(); return _schemas; } } internal TypeScope Scope { get { if (_scope == null) _scope = new TypeScope(); return _scope; } } internal NameTable GroupsInUse { get { if (_groupsInUse == null) _groupsInUse = new NameTable(); return _groupsInUse; } } internal NameTable TypesInUse { get { if (_typesInUse == null) _typesInUse = new NameTable(); return _typesInUse; } } internal CodeGenerationOptions Options { get { return _options; } } internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect) { structMapping.ReferencedByTopLevelElement = true; TypeDesc baseTypeDesc; if (baseType != null) { baseTypeDesc = Scope.GetTypeDesc(baseType); if (baseTypeDesc != null) { TypeDesc typeDescToChange = structMapping.TypeDesc; if (baseTypeCanBeIndirect) { // if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the // inheritance chain, not necessarily directly to the imported type. while (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) typeDescToChange = typeDescToChange.BaseTypeDesc; } if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) throw new InvalidOperationException(string.Format(ResXml.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); typeDescToChange.BaseTypeDesc = baseTypeDesc; } } } internal string GenerateUniqueTypeName(string typeName) { typeName = CodeIdentifier.MakeValid(typeName); return TypeIdentifiers.AddUnique(typeName, typeName); } private StructMapping CreateRootMapping() { TypeDesc typeDesc = Scope.GetTypeDesc(typeof(object)); StructMapping mapping = new StructMapping(); mapping.TypeDesc = typeDesc; mapping.Members = new MemberMapping[0]; mapping.IncludeInSchema = false; mapping.TypeName = Soap.UrType; mapping.Namespace = XmlSchema.Namespace; return mapping; } internal StructMapping GetRootMapping() { if (_root == null) _root = CreateRootMapping(); return _root; } internal StructMapping ImportRootMapping() { if (!_rootImported) { _rootImported = true; ImportDerivedTypes(XmlQualifiedName.Empty); } return GetRootMapping(); } internal abstract void ImportDerivedTypes(XmlQualifiedName baseName); internal void AddReference(XmlQualifiedName name, NameTable references, string error) { if (name.Namespace == XmlSchema.Namespace) return; if (references[name] != null) { throw new InvalidOperationException(string.Format(error, name.Name, name.Namespace)); } references[name] = name; } internal void RemoveReference(XmlQualifiedName name, NameTable references) { references[name] = null; } internal void AddReservedIdentifiersForDataBinding(CodeIdentifiers scope) { if ((_options & CodeGenerationOptions.EnableDataBinding) != 0) { scope.AddReserved(CodeExporter.PropertyChangedEvent.Name); scope.AddReserved(CodeExporter.RaisePropertyChangedEventMethod.Name); } } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using ConsoleExamples.Examples; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.ML.Factory; using Encog.ML.Train; using Encog.ML.Train.Strategy; using Encog.Neural.Networks.Training.Propagation.Manhattan; using Encog.Util.Simple; namespace Encog.Examples.XOR { /// <summary> /// This example shows how to use the Encog machine learning factory to /// generate a number of machine learning methods and training techniques /// to learn the XOR operator. /// </summary> public class XORFactory : IExample { public const string METHOD_FEEDFORWARD_A = "?:B->SIGMOID->4:B->SIGMOID->?"; public const string METHOD_BIASLESS_A = "?->SIGMOID->4->SIGMOID->?"; public const string METHOD_SVMC_A = "?->C->?"; public const string METHOD_SVMR_A = "?->R->?"; public const string METHOD_RBF_A = "?->gaussian(c=4)->?"; public const string METHOD_PNNC_A = "?->C(kernel=gaussian)->?"; public const string METHOD_PNNR_A = "?->R(kernel=gaussian)->?"; /// <summary> /// Input for the XOR function. /// </summary> public static double[][] XORInput = { new double[2] {0.0, 0.0}, new double[2] {1.0, 0.0}, new double[2] {0.0, 1.0}, new double[2] {1.0, 1.0} }; /// <summary> /// Ideal output for the XOR function. /// </summary> public static double[][] XORIdeal = { new double[1] {0.0}, new double[1] {1.0}, new double[1] {1.0}, new double[1] {0.0} }; public static ExampleInfo Info { get { var info = new ExampleInfo( typeof (XORFactory), "xor-factory", "Use XOR with many different training and network types.", "This example shows many neural network types and training methods used with XOR."); return info; } } #region IExample Members /// <summary> /// Program entry point. /// </summary> /// <param name="app">Holds arguments and other info.</param> public void Execute(IExampleInterface app) { if (app.Args.Length > 0) { Run(app.Args[0]); } else { Usage(); } } #endregion /** * Demonstrate a feedforward network with RPROP. */ public void xorRPROP() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeRPROP, "", 1); } /** * Demonstrate a feedforward biasless network with RPROP. */ public void xorBiasless() { Process( MLMethodFactory.TypeFeedforward, METHOD_BIASLESS_A, MLTrainFactory.TypeRPROP, "", 1); } /** * Demonstrate a feedforward network with backpropagation. */ public void xorBackProp() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeBackprop, "", 1); } /** * Demonstrate a SVM-classify. */ public void xorSVMClassify() { Process( MLMethodFactory.TypeSVM, METHOD_SVMC_A, MLTrainFactory.TypeSVM, "", 1); } /** * Demonstrate a SVM-regression. */ public void xorSVMRegression() { Process( MLMethodFactory.TypeSVM, METHOD_SVMR_A, MLTrainFactory.TypeSVM, "", 1); } /** * Demonstrate a SVM-regression search. */ public void xorSVMSearchRegression() { Process( MLMethodFactory.TypeSVM, METHOD_SVMR_A, MLTrainFactory.TypeSVMSearch, "", 1); } /** * Demonstrate a XOR annealing. */ public void xorAnneal() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeAnneal, "", 1); } /** * Demonstrate a XOR genetic. */ public void xorGenetic() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeGenetic, "", 1); } /** * Demonstrate a XOR LMA. */ public void xorLMA() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeLma, "", 1); } /** * Demonstrate a XOR LMA. */ public void xorManhattan() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeManhattan, "lr=0.0001", 1); } /** * Demonstrate a XOR SCG. */ public void xorSCG() { Process( MLMethodFactory.TypeFeedforward, METHOD_FEEDFORWARD_A, MLTrainFactory.TypeSCG, "", 1); } /** * Demonstrate a XOR RBF. */ public void xorRBF() { Process( MLMethodFactory.TypeRbfnetwork, METHOD_RBF_A, MLTrainFactory.TypeRPROP, "", 1); } /** * Demonstrate a XOR RBF. */ public void xorSVD() { Process( MLMethodFactory.TypeRbfnetwork, METHOD_RBF_A, MLTrainFactory.TypeSvd, "", 1); } /** * Demonstrate a XOR RBF. */ public void xorPNNC() { Process( MLMethodFactory.TypePNN, METHOD_PNNC_A, MLTrainFactory.TypePNN, "", 2); } /** * Demonstrate a XOR RBF. */ public void xorPNNr() { Process( MLMethodFactory.TypePNN, METHOD_PNNR_A, MLTrainFactory.TypePNN, "", 1); } public void xorQProp() { Process( MLMethodFactory.TypeFeedforward, XORFactory.METHOD_FEEDFORWARD_A, MLTrainFactory.TypeQPROP, "", 1); } public void Process(String methodName, String methodArchitecture, String trainerName, String trainerArgs, int outputNeurons) { // first, create the machine learning method var methodFactory = new MLMethodFactory(); IMLMethod method = methodFactory.Create(methodName, methodArchitecture, 2, outputNeurons); // second, create the data set IMLDataSet dataSet = new BasicMLDataSet(XORInput, XORIdeal); // third, create the trainer var trainFactory = new MLTrainFactory(); IMLTrain train = trainFactory.Create(method, dataSet, trainerName, trainerArgs); // reset if improve is less than 1% over 5 cycles if (method is IMLResettable && !(train is ManhattanPropagation)) { train.AddStrategy(new RequiredImprovementStrategy(500)); } // fourth, train and evaluate. EncogUtility.TrainToError(train, 0.01); method = train.Method; EncogUtility.Evaluate((IMLRegression) method, dataSet); // finally, write out what we did Console.WriteLine(@"Machine Learning Type: " + methodName); Console.WriteLine(@"Machine Learning Architecture: " + methodArchitecture); Console.WriteLine(@"Training Method: " + trainerName); Console.WriteLine(@"Training Args: " + trainerArgs); } /// <summary> /// Display usage information. /// </summary> public void Usage() { Console.WriteLine( @"Usage: XORFactory [mode] Where mode is one of: backprop - Feedforward biased with backpropagation rprop - Feedforward biased with resilient propagation biasless - Feedforward biasless with resilient propagation svm-c - Support Vector Machine for classification svm-r - Support Vector Machine for regression svm-search-r - Support Vector Machine for classification, search training anneal - Feedforward biased with annealing genetic - Feedforward biased with genetic lma - Feedforward biased with Levenberg Marquardt manhattan - Feedforward biased with Manhattan Update Rule scg - Feedforward biased with Scaled Conjugate Gradient rbf - RBF Network with Resilient propagation svd - RBF Network with SVD pnn-c PNN for Classification pnn-r PNN for Regression qprop Feedforward QuickProp"); } /// <summary> /// Run the program in the specific mode. /// </summary> /// <param name="mode">The mode to use.</param> public void Run(string mode) { if (string.Compare(mode, "backprop", true) == 0) { xorBackProp(); } else if (string.Compare(mode, "rprop", true) == 0) { xorRPROP(); } else if (string.Compare(mode, "biasless", true) == 0) { xorBiasless(); } else if (string.Compare(mode, "svm-c", true) == 0) { xorSVMClassify(); } else if (string.Compare(mode, "svm-r", true) == 0) { xorSVMRegression(); } else if (string.Compare(mode, "svm-search-r", true) == 0) { xorSVMSearchRegression(); } else if (string.Compare(mode, "anneal", true) == 0) { xorAnneal(); } else if (string.Compare(mode, "genetic", true) == 0) { xorGenetic(); } else if (string.Compare(mode, "lma", true) == 0) { xorLMA(); } else if (string.Compare(mode, "manhattan", true) == 0) { xorManhattan(); } else if (string.Compare(mode, "scg", true) == 0) { xorSCG(); } else if (string.Compare(mode, "rbf", true) == 0) { xorRBF(); } else if (string.Compare(mode, "svd", true) == 0) { xorSVD(); } else if (string.Compare(mode, "pnn-c", true) == 0) { xorPNNC(); } else if (string.Compare(mode, "pnn-r", true) == 0) { xorPNNr(); } else if (string.Compare(mode, "qprop", true) == 0) { xorQProp(); } else { Usage(); } } } }
#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.Text; #if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 using System.Numerics; #endif using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Tests.Bson; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Linq.JsonPath { [TestFixture] public class JPathExecuteTests : TestFixtureBase { [Test] public void GreaterThanWithIntegerParameterAndStringValue() { string json = @"{ ""persons"": [ { ""name"" : ""John"", ""age"": ""26"" }, { ""name"" : ""Jane"", ""age"": ""2"" } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.persons[?(@.age > 3)]").ToList(); Assert.AreEqual(1, results.Count); } [Test] public void GreaterThanWithStringParameterAndIntegerValue() { string json = @"{ ""persons"": [ { ""name"" : ""John"", ""age"": 26 }, { ""name"" : ""Jane"", ""age"": 2 } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.persons[?(@.age > '3')]").ToList(); Assert.AreEqual(1, results.Count); } [Test] public void RecursiveWildcard() { string json = @"{ ""a"": [ { ""id"": 1 } ], ""b"": [ { ""id"": 2 }, { ""id"": 3, ""c"": { ""id"": 4 } } ], ""d"": [ { ""id"": 5 } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.b..*.id").ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual(2, (int)results[0]); Assert.AreEqual(3, (int)results[1]); Assert.AreEqual(4, (int)results[2]); } [Test] public void ScanFilter() { string json = @"{ ""elements"": [ { ""id"": ""A"", ""children"": [ { ""id"": ""AA"", ""children"": [ { ""id"": ""AAA"" }, { ""id"": ""AAB"" } ] }, { ""id"": ""AB"" } ] }, { ""id"": ""B"", ""children"": [] } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.elements..[?(@.id=='AAA')]").ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual(models["elements"][0]["children"][0]["children"][0], results[0]); } [Test] public void FilterTrue() { string json = @"{ ""elements"": [ { ""id"": ""A"", ""children"": [ { ""id"": ""AA"", ""children"": [ { ""id"": ""AAA"" }, { ""id"": ""AAB"" } ] }, { ""id"": ""AB"" } ] }, { ""id"": ""B"", ""children"": [] } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.elements[?(true)]").ToList(); Assert.AreEqual(2, results.Count); Assert.AreEqual(results[0], models["elements"][0]); Assert.AreEqual(results[1], models["elements"][1]); } [Test] public void ScanFilterTrue() { string json = @"{ ""elements"": [ { ""id"": ""A"", ""children"": [ { ""id"": ""AA"", ""children"": [ { ""id"": ""AAA"" }, { ""id"": ""AAB"" } ] }, { ""id"": ""AB"" } ] }, { ""id"": ""B"", ""children"": [] } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.elements..[?(true)]").ToList(); Assert.AreEqual(25, results.Count); } [Test] public void ScanQuoted() { string json = @"{ ""Node1"": { ""Child1"": { ""Name"": ""IsMe"", ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } }, ""My.Child.Node"": { ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } } }, ""Node2"": { ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } } }"; JObject models = JObject.Parse(json); int result = models.SelectTokens("$..['My.Child.Node']").Count(); Assert.AreEqual(1, result); result = models.SelectTokens("..['My.Child.Node']").Count(); Assert.AreEqual(1, result); } [Test] public void ScanMultipleQuoted() { string json = @"{ ""Node1"": { ""Child1"": { ""Name"": ""IsMe"", ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } }, ""My.Child.Node"": { ""TargetNode"": { ""Prop1"": ""Val3"", ""Prop2"": ""Val4"" } } }, ""Node2"": { ""TargetNode"": { ""Prop1"": ""Val5"", ""Prop2"": ""Val6"" } } }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$..['My.Child.Node','Prop1','Prop2']").ToList(); Assert.AreEqual("Val1", (string)results[0]); Assert.AreEqual("Val2", (string)results[1]); Assert.AreEqual(JTokenType.Object, results[2].Type); Assert.AreEqual("Val3", (string)results[3]); Assert.AreEqual("Val4", (string)results[4]); Assert.AreEqual("Val5", (string)results[5]); Assert.AreEqual("Val6", (string)results[6]); } [Test] public void ParseWithEmptyArrayContent() { var json = @"{ 'controls': [ { 'messages': { 'addSuggestion': { 'en-US': 'Add' } } }, { 'header': { 'controls': [] }, 'controls': [ { 'controls': [ { 'defaultCaption': { 'en-US': 'Sort by' }, 'sortOptions': [ { 'label': { 'en-US': 'Name' } } ] } ] } ] } ] }"; JObject jToken = JObject.Parse(json); IList<JToken> tokens = jToken.SelectTokens("$..en-US").ToList(); Assert.AreEqual(3, tokens.Count); Assert.AreEqual("Add", (string)tokens[0]); Assert.AreEqual("Sort by", (string)tokens[1]); Assert.AreEqual("Name", (string)tokens[2]); } [Test] public void SelectTokenAfterEmptyContainer() { string json = @"{ 'cont': [], 'test': 'no one will find me' }"; JObject o = JObject.Parse(json); IList<JToken> results = o.SelectTokens("$..test").ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("no one will find me", (string)results[0]); } [Test] public void EvaluatePropertyWithRequired() { string json = "{\"bookId\":\"1000\"}"; JObject o = JObject.Parse(json); string bookId = (string)o.SelectToken("bookId", true); Assert.AreEqual("1000", bookId); } [Test] public void EvaluateEmptyPropertyIndexer() { JObject o = new JObject( new JProperty("", 1)); JToken t = o.SelectToken("['']"); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateEmptyString() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken(""); Assert.AreEqual(o, t); t = o.SelectToken("['']"); Assert.AreEqual(null, t); } [Test] public void EvaluateEmptyStringWithMatchingEmptyProperty() { JObject o = new JObject( new JProperty(" ", 1)); JToken t = o.SelectToken("[' ']"); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateWhitespaceString() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken(" "); Assert.AreEqual(o, t); } [Test] public void EvaluateDollarString() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("$"); Assert.AreEqual(o, t); } [Test] public void EvaluateDollarTypeString() { JObject o = new JObject( new JProperty("$values", new JArray(1, 2, 3))); JToken t = o.SelectToken("$values[1]"); Assert.AreEqual(2, (int)t); } [Test] public void EvaluateSingleProperty() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("Blah"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateWildcardProperty() { JObject o = new JObject( new JProperty("Blah", 1), new JProperty("Blah2", 2)); IList<JToken> t = o.SelectTokens("$.*").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); } [Test] public void QuoteName() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("['Blah']"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateMissingProperty() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("Missing[1]"); Assert.IsNull(t); } [Test] public void EvaluateIndexerOnObject() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("[1]"); Assert.IsNull(t); } [Test] public void EvaluateIndexerOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject."); } [Test] public void EvaluateWildcardIndexOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject."); } [Test] public void EvaluateSliceOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject."); } [Test] public void EvaluatePropertyOnArray() { JArray a = new JArray(1, 2, 3, 4, 5); JToken t = a.SelectToken("BlahBlah"); Assert.IsNull(t); } [Test] public void EvaluateMultipleResultsError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens."); } [Test] public void EvaluatePropertyOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray."); } [Test] public void EvaluateNoResultsWithMultipleArrayIndexes() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray."); } [Test] public void EvaluateConstructorOutOfBoundsIndxerWithError() { JConstructor c = new JConstructor("Blah"); ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor."); } [Test] public void EvaluateConstructorOutOfBoundsIndxer() { JConstructor c = new JConstructor("Blah"); Assert.IsNull(c.SelectToken("[1]")); } [Test] public void EvaluateMissingPropertyWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject."); } [Test] public void EvaluatePropertyWithoutError() { JObject o = new JObject( new JProperty("Blah", 1)); JValue v = (JValue)o.SelectToken("Blah", true); Assert.AreEqual(1, v.Value); } [Test] public void EvaluateMissingPropertyIndexWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject."); } [Test] public void EvaluateMultiPropertyIndexOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray."); } [Test] public void EvaluateArraySliceWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results."); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results."); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results."); a = new JArray(); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results."); } [Test] public void EvaluateOutOfBoundsIndxer() { JArray a = new JArray(1, 2, 3, 4, 5); JToken t = a.SelectToken("[1000].Ha"); Assert.IsNull(t); } [Test] public void EvaluateArrayOutOfBoundsIndxerWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray."); } [Test] public void EvaluateArray() { JArray a = new JArray(1, 2, 3, 4); JToken t = a.SelectToken("[1]"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(2, (int)t); } [Test] public void EvaluateArraySlice() { JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9); IList<JToken> t = null; t = a.SelectTokens("[-3:]").ToList(); Assert.AreEqual(3, t.Count); Assert.AreEqual(7, (int)t[0]); Assert.AreEqual(8, (int)t[1]); Assert.AreEqual(9, (int)t[2]); t = a.SelectTokens("[-1:-2:-1]").ToList(); Assert.AreEqual(1, t.Count); Assert.AreEqual(9, (int)t[0]); t = a.SelectTokens("[-2:-1]").ToList(); Assert.AreEqual(1, t.Count); Assert.AreEqual(8, (int)t[0]); t = a.SelectTokens("[1:1]").ToList(); Assert.AreEqual(0, t.Count); t = a.SelectTokens("[1:2]").ToList(); Assert.AreEqual(1, t.Count); Assert.AreEqual(2, (int)t[0]); t = a.SelectTokens("[::-1]").ToList(); Assert.AreEqual(9, t.Count); Assert.AreEqual(9, (int)t[0]); Assert.AreEqual(8, (int)t[1]); Assert.AreEqual(7, (int)t[2]); Assert.AreEqual(6, (int)t[3]); Assert.AreEqual(5, (int)t[4]); Assert.AreEqual(4, (int)t[5]); Assert.AreEqual(3, (int)t[6]); Assert.AreEqual(2, (int)t[7]); Assert.AreEqual(1, (int)t[8]); t = a.SelectTokens("[::-2]").ToList(); Assert.AreEqual(5, t.Count); Assert.AreEqual(9, (int)t[0]); Assert.AreEqual(7, (int)t[1]); Assert.AreEqual(5, (int)t[2]); Assert.AreEqual(3, (int)t[3]); Assert.AreEqual(1, (int)t[4]); } [Test] public void EvaluateWildcardArray() { JArray a = new JArray(1, 2, 3, 4); List<JToken> t = a.SelectTokens("[*]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(4, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); Assert.AreEqual(3, (int)t[2]); Assert.AreEqual(4, (int)t[3]); } [Test] public void EvaluateArrayMultipleIndexes() { JArray a = new JArray(1, 2, 3, 4); IEnumerable<JToken> t = a.SelectTokens("[1,2,0]"); Assert.IsNotNull(t); Assert.AreEqual(3, t.Count()); Assert.AreEqual(2, (int)t.ElementAt(0)); Assert.AreEqual(3, (int)t.ElementAt(1)); Assert.AreEqual(1, (int)t.ElementAt(2)); } [Test] public void EvaluateScan() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JArray a = new JArray(o1, o2); IList<JToken> t = a.SelectTokens("$..Name").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); } [Test] public void EvaluateWildcardScan() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JArray a = new JArray(o1, o2); IList<JToken> t = a.SelectTokens("$..*").ToList(); Assert.IsNotNull(t); Assert.AreEqual(5, t.Count); Assert.IsTrue(JToken.DeepEquals(a, t[0])); Assert.IsTrue(JToken.DeepEquals(o1, t[1])); Assert.AreEqual(1, (int)t[2]); Assert.IsTrue(JToken.DeepEquals(o2, t[3])); Assert.AreEqual(2, (int)t[4]); } [Test] public void EvaluateScanNestResults() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } }; JArray a = new JArray(o1, o2, o3); IList<JToken> t = a.SelectTokens("$..Name").ToList(); Assert.IsNotNull(t); Assert.AreEqual(4, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2])); Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3])); } [Test] public void EvaluateWildcardScanNestResults() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } }; JArray a = new JArray(o1, o2, o3); IList<JToken> t = a.SelectTokens("$..*").ToList(); Assert.IsNotNull(t); Assert.AreEqual(9, t.Count); Assert.IsTrue(JToken.DeepEquals(a, t[0])); Assert.IsTrue(JToken.DeepEquals(o1, t[1])); Assert.AreEqual(1, (int)t[2]); Assert.IsTrue(JToken.DeepEquals(o2, t[3])); Assert.AreEqual(2, (int)t[4]); Assert.IsTrue(JToken.DeepEquals(o3, t[5])); Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6])); Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7])); Assert.AreEqual(3, (int)t[8]); } [Test] public void EvaluateSinglePropertyReturningArray() { JObject o = new JObject( new JProperty("Blah", new[] { 1, 2, 3 })); JToken t = o.SelectToken("Blah"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Array, t.Type); t = o.SelectToken("Blah[2]"); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(3, (int)t); } [Test] public void EvaluateLastSingleCharacterProperty() { JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}"); string a2 = (string)o2.SelectToken("People[0].N"); Assert.AreEqual("Jeff", a2); } [Test] public void ExistsQuery() { JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha"))); IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(1, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0])); } [Test] public void EqualsQuery() { JArray a = new JArray( new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi", "ha"))); IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(1, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0])); } [Test] public void NotEqualsQuery() { JArray a = new JArray( new JArray(new JObject(new JProperty("hi", "ho"))), new JArray(new JObject(new JProperty("hi", "ha")))); IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(1, t.Count); Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0])); } [Test] public void NoPathQuery() { JArray a = new JArray(1, 2, 3); IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual(2, (int)t[0]); Assert.AreEqual(3, (int)t[1]); } [Test] public void MultipleQueries() { JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9); // json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/ // first query resolves array to ints // int has no children to query IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(0, t.Count); } [Test] public void GreaterQuery() { JArray a = new JArray( new JObject(new JProperty("hi", 1)), new JObject(new JProperty("hi", 2)), new JObject(new JProperty("hi", 3))); IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } [Test] public void LesserQuery_ValueFirst() { JArray a = new JArray( new JObject(new JProperty("hi", 1)), new JObject(new JProperty("hi", 2)), new JObject(new JProperty("hi", 3))); IList<JToken> t = a.SelectTokens("[ ?( 1 < @.hi ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } #if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 [Test] public void GreaterQueryBigInteger() { JArray a = new JArray( new JObject(new JProperty("hi", new BigInteger(1))), new JObject(new JProperty("hi", new BigInteger(2))), new JObject(new JProperty("hi", new BigInteger(3)))); IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } #endif [Test] public void GreaterOrEqualQuery() { JArray a = new JArray( new JObject(new JProperty("hi", 1)), new JObject(new JProperty("hi", 2)), new JObject(new JProperty("hi", 2.0)), new JObject(new JProperty("hi", 3))); IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(4, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3])); } [Test] public void NestedQuery() { JArray a = new JArray( new JObject( new JProperty("name", "Bad Boys"), new JProperty("cast", new JArray( new JObject(new JProperty("name", "Will Smith"))))), new JObject( new JProperty("name", "Independence Day"), new JProperty("cast", new JArray( new JObject(new JProperty("name", "Will Smith"))))), new JObject( new JProperty("name", "The Rock"), new JProperty("cast", new JArray( new JObject(new JProperty("name", "Nick Cage"))))) ); IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual("Bad Boys", (string)t[0]); Assert.AreEqual("Independence Day", (string)t[1]); } [Test] public void PathWithConstructor() { JArray a = JArray.Parse(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]"); JValue v = (JValue)a.SelectToken("[1].Property2[1][0]"); Assert.AreEqual(1L, v.Value); } [Test] public void MultiplePaths() { JArray a = JArray.Parse(@"[ { ""price"": 199, ""max_price"": 200 }, { ""price"": 200, ""max_price"": 200 }, { ""price"": 201, ""max_price"": 200 } ]"); var results = a.SelectTokens("[?(@.price > @.max_price)]").ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual(a[2], results[0]); } [Test] public void Exists_True() { JArray a = JArray.Parse(@"[ { ""price"": 199, ""max_price"": 200 }, { ""price"": 200, ""max_price"": 200 }, { ""price"": 201, ""max_price"": 200 } ]"); var results = a.SelectTokens("[?(true)]").ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual(a[0], results[0]); Assert.AreEqual(a[1], results[1]); Assert.AreEqual(a[2], results[2]); } [Test] public void Exists_Null() { JArray a = JArray.Parse(@"[ { ""price"": 199, ""max_price"": 200 }, { ""price"": 200, ""max_price"": 200 }, { ""price"": 201, ""max_price"": 200 } ]"); var results = a.SelectTokens("[?(true)]").ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual(a[0], results[0]); Assert.AreEqual(a[1], results[1]); Assert.AreEqual(a[2], results[2]); } [Test] public void WildcardWithProperty() { JObject o = JObject.Parse(@"{ ""station"": 92000041000001, ""containers"": [ { ""id"": 1, ""text"": ""Sort system"", ""containers"": [ { ""id"": ""2"", ""text"": ""Yard 11"" }, { ""id"": ""92000020100006"", ""text"": ""Sort yard 12"" }, { ""id"": ""92000020100005"", ""text"": ""Yard 13"" } ] }, { ""id"": ""92000020100011"", ""text"": ""TSP-1"" }, { ""id"":""92000020100007"", ""text"": ""Passenger 15"" } ] }"); IList<JToken> tokens = o.SelectTokens("$..*[?(@.text)]").ToList(); int i = 0; Assert.AreEqual("Sort system", (string)tokens[i++]["text"]); Assert.AreEqual("TSP-1", (string)tokens[i++]["text"]); Assert.AreEqual("Passenger 15", (string)tokens[i++]["text"]); Assert.AreEqual("Yard 11", (string)tokens[i++]["text"]); Assert.AreEqual("Sort yard 12", (string)tokens[i++]["text"]); Assert.AreEqual("Yard 13", (string)tokens[i++]["text"]); Assert.AreEqual(6, tokens.Count); } [Test] public void QueryAgainstNonStringValues() { IList<object> values = new List<object> { "ff2dc672-6e15-4aa2-afb0-18f4f69596ad", new Guid("ff2dc672-6e15-4aa2-afb0-18f4f69596ad"), "http://localhost", new Uri("http://localhost"), "2000-12-05T05:07:59Z", new DateTime(2000, 12, 5, 5, 7, 59, DateTimeKind.Utc), #if !NET20 "2000-12-05T05:07:59-10:00", new DateTimeOffset(2000, 12, 5, 5, 7, 59, -TimeSpan.FromHours(10)), #endif "SGVsbG8gd29ybGQ=", Encoding.UTF8.GetBytes("Hello world"), "365.23:59:59", new TimeSpan(365, 23, 59, 59) }; JObject o = new JObject( new JProperty("prop", new JArray( values.Select(v => new JObject(new JProperty("childProp", v))) ) ) ); IList<JToken> t = o.SelectTokens("$.prop[?(@.childProp =='ff2dc672-6e15-4aa2-afb0-18f4f69596ad')]").ToList(); Assert.AreEqual(2, t.Count); t = o.SelectTokens("$.prop[?(@.childProp =='http://localhost')]").ToList(); Assert.AreEqual(2, t.Count); t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59Z')]").ToList(); Assert.AreEqual(2, t.Count); #if !NET20 t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59-10:00')]").ToList(); Assert.AreEqual(2, t.Count); #endif t = o.SelectTokens("$.prop[?(@.childProp =='SGVsbG8gd29ybGQ=')]").ToList(); Assert.AreEqual(2, t.Count); t = o.SelectTokens("$.prop[?(@.childProp =='365.23:59:59')]").ToList(); Assert.AreEqual(2, t.Count); } [Test] public void Example() { JObject o = JObject.Parse(@"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }"); string name = (string)o.SelectToken("Manufacturers[0].Name"); // Acme Co decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price"); // 50 string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name"); // Elbow Grease Assert.AreEqual("Acme Co", name); Assert.AreEqual(50m, productPrice); Assert.AreEqual("Elbow Grease", productName); IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList(); // Lambton Quay // Willis Street IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList(); // null // Headlight Fluid decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price")); // 149.95 Assert.AreEqual(2, storeNames.Count); Assert.AreEqual("Lambton Quay", storeNames[0]); Assert.AreEqual("Willis Street", storeNames[1]); Assert.AreEqual(2, firstProductNames.Count); Assert.AreEqual(null, firstProductNames[0]); Assert.AreEqual("Headlight Fluid", firstProductNames[1]); Assert.AreEqual(149.95m, totalPrice); } [Test] public void NotEqualsAndNonPrimativeValues() { string json = @"[ { ""name"": ""string"", ""value"": ""aString"" }, { ""name"": ""number"", ""value"": 123 }, { ""name"": ""array"", ""value"": [ 1, 2, 3, 4 ] }, { ""name"": ""object"", ""value"": { ""1"": 1 } } ]"; JArray a = JArray.Parse(json); List<JToken> result = a.SelectTokens("$.[?(@.value!=1)]").ToList(); Assert.AreEqual(4, result.Count); result = a.SelectTokens("$.[?(@.value!='2000-12-05T05:07:59-10:00')]").ToList(); Assert.AreEqual(4, result.Count); result = a.SelectTokens("$.[?(@.value!=null)]").ToList(); Assert.AreEqual(4, result.Count); result = a.SelectTokens("$.[?(@.value!=123)]").ToList(); Assert.AreEqual(3, result.Count); result = a.SelectTokens("$.[?(@.value)]").ToList(); Assert.AreEqual(4, result.Count); } [Test] public void RootInFilter() { string json = @"[ { ""store"" : { ""book"" : [ { ""category"" : ""reference"", ""author"" : ""Nigel Rees"", ""title"" : ""Sayings of the Century"", ""price"" : 8.95 }, { ""category"" : ""fiction"", ""author"" : ""Evelyn Waugh"", ""title"" : ""Sword of Honour"", ""price"" : 12.99 }, { ""category"" : ""fiction"", ""author"" : ""Herman Melville"", ""title"" : ""Moby Dick"", ""isbn"" : ""0-553-21311-3"", ""price"" : 8.99 }, { ""category"" : ""fiction"", ""author"" : ""J. R. R. Tolkien"", ""title"" : ""The Lord of the Rings"", ""isbn"" : ""0-395-19395-8"", ""price"" : 22.99 } ], ""bicycle"" : { ""color"" : ""red"", ""price"" : 19.95 } }, ""expensive"" : 10 } ]"; JArray a = JArray.Parse(json); List<JToken> result = a.SelectTokens("$.[?($.[0].store.bicycle.price < 20)]").ToList(); Assert.AreEqual(1, result.Count); result = a.SelectTokens("$.[?($.[0].store.bicycle.price < 10)]").ToList(); Assert.AreEqual(0, result.Count); } [Test] public void RootInFilterWithRootObject() { string json = @"{ ""store"" : { ""book"" : [ { ""category"" : ""reference"", ""author"" : ""Nigel Rees"", ""title"" : ""Sayings of the Century"", ""price"" : 8.95 }, { ""category"" : ""fiction"", ""author"" : ""Evelyn Waugh"", ""title"" : ""Sword of Honour"", ""price"" : 12.99 }, { ""category"" : ""fiction"", ""author"" : ""Herman Melville"", ""title"" : ""Moby Dick"", ""isbn"" : ""0-553-21311-3"", ""price"" : 8.99 }, { ""category"" : ""fiction"", ""author"" : ""J. R. R. Tolkien"", ""title"" : ""The Lord of the Rings"", ""isbn"" : ""0-395-19395-8"", ""price"" : 22.99 } ], ""bicycle"" : [ { ""color"" : ""red"", ""price"" : 19.95 } ] }, ""expensive"" : 10 }"; JObject a = JObject.Parse(json); List<JToken> result = a.SelectTokens("$..book[?(@.price <= $['expensive'])]").ToList(); Assert.AreEqual(2, result.Count); result = a.SelectTokens("$.store..[?(@.price > $.expensive)]").ToList(); Assert.AreEqual(3, result.Count); } [Test] public void RootInFilterWithInitializers() { JObject rootObject = new JObject { { "referenceDate", new JValue(DateTime.MinValue) }, { "dateObjectsArray", new JArray() { new JObject { { "date", new JValue(DateTime.MinValue) } }, new JObject { { "date", new JValue(DateTime.MaxValue) } }, new JObject { { "date", new JValue(DateTime.Now) } }, new JObject { { "date", new JValue(DateTime.MinValue) } }, } } }; List<JToken> result = rootObject.SelectTokens("$.dateObjectsArray[?(@.date == $.referenceDate)]").ToList(); Assert.AreEqual(2, result.Count); } } }
// 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.Text; using System.Threading; using System.Globalization; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Buffers; using System.Diagnostics.CodeAnalysis; namespace System.IO { // This abstract base class represents a writer that can write a sequential // stream of characters. A subclass must minimally implement the // Write(char) method. // // This class is intended for character output, not bytes. // There are methods on the Stream class for writing bytes. public abstract partial class TextWriter : MarshalByRefObject, IDisposable, IAsyncDisposable { public static readonly TextWriter Null = new NullTextWriter(); // We don't want to allocate on every TextWriter creation, so cache the char array. private static readonly char[] s_coreNewLine = Environment.NewLine.ToCharArray(); /// <summary> /// This is the 'NewLine' property expressed as a char[]. /// It is exposed to subclasses as a protected field for read-only /// purposes. You should only modify it by using the 'NewLine' property. /// In particular you should never modify the elements of the array /// as they are shared among many instances of TextWriter. /// </summary> protected char[] CoreNewLine = s_coreNewLine; private string CoreNewLineStr = Environment.NewLine; // Can be null - if so, ask for the Thread's CurrentCulture every time. private IFormatProvider? _internalFormatProvider; protected TextWriter() { _internalFormatProvider = null; // Ask for CurrentCulture all the time. } protected TextWriter(IFormatProvider? formatProvider) { _internalFormatProvider = formatProvider; } public virtual IFormatProvider FormatProvider { get { if (_internalFormatProvider == null) { return CultureInfo.CurrentCulture; } else { return _internalFormatProvider; } } } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public virtual ValueTask DisposeAsync() { try { Dispose(); return default; } catch (Exception exc) { return new ValueTask(Task.FromException(exc)); } } // Clears all buffers for this TextWriter and causes any buffered data to be // written to the underlying device. This default method is empty, but // descendant classes can override the method to provide the appropriate // functionality. public virtual void Flush() { } public abstract Encoding Encoding { get; } /// <summary> /// Returns the line terminator string used by this TextWriter. The default line /// terminator string is Environment.NewLine, which is platform specific. /// On Windows this is a carriage return followed by a line feed ("\r\n"). /// On OSX and Linux this is a line feed ("\n"). /// </summary> /// <remarks> /// The line terminator string is written to the text stream whenever one of the /// WriteLine methods are called. In order for text written by /// the TextWriter to be readable by a TextReader, only one of the following line /// terminator strings should be used: "\r", "\n", or "\r\n". /// </remarks> [AllowNull] public virtual string NewLine { get { return CoreNewLineStr; } set { if (value == null) { value = Environment.NewLine; } CoreNewLineStr = value; CoreNewLine = value.ToCharArray(); } } // Writes a character to the text stream. This default method is empty, // but descendant classes can override the method to provide the // appropriate functionality. // public virtual void Write(char value) { } // Writes a character array to the text stream. This default method calls // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // public virtual void Write(char[]? buffer) { if (buffer != null) { Write(buffer, 0, buffer.Length); } } // Writes a range of a character array to the text stream. This method will // write count characters of data into this TextWriter from the // buffer character array starting at position index. // public virtual void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } for (int i = 0; i < count; i++) Write(buffer[index + i]); } // Writes a span of characters to the text stream. // public virtual void Write(ReadOnlySpan<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { buffer.CopyTo(new Span<char>(array)); Write(array, 0, buffer.Length); } finally { ArrayPool<char>.Shared.Return(array); } } // Writes the text representation of a boolean to the text stream. This // method outputs either bool.TrueString or bool.FalseString. // public virtual void Write(bool value) { Write(value ? "True" : "False"); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // int.ToString() method. // public virtual void Write(int value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // uint.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the // long.ToString() method. // public virtual void Write(long value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced // by calling the ulong.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the // float.ToString(float) method. // public virtual void Write(float value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the // double.ToString(double) method. // public virtual void Write(double value) { Write(value.ToString(FormatProvider)); } public virtual void Write(decimal value) { Write(value.ToString(FormatProvider)); } // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // public virtual void Write(string? value) { if (value != null) { Write(value.ToCharArray()); } } // Writes the text representation of an object to the text stream. If the // given object is null, nothing is written to the text stream. // Otherwise, the object's ToString method is called to produce the // string representation, and the resulting string is then written to the // output stream. // public virtual void Write(object? value) { if (value != null) { if (value is IFormattable f) { Write(f.ToString(null, FormatProvider)); } else Write(value.ToString()); } } /// <summary> /// Equivalent to Write(stringBuilder.ToString()) however it uses the /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> /// <param name="value">The string (as a StringBuilder) to write to the stream</param> public virtual void Write(StringBuilder? value) { if (value != null) { foreach (ReadOnlyMemory<char> chunk in value.GetChunks()) Write(chunk.Span); } } // Writes out a formatted string. Uses the same semantics as // string.Format. // public virtual void Write(string format, object? arg0) { Write(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string. Uses the same semantics as // string.Format. // public virtual void Write(string format, object? arg0, object? arg1) { Write(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string. Uses the same semantics as // string.Format. // public virtual void Write(string format, object? arg0, object? arg1, object? arg2) { Write(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string. Uses the same semantics as // string.Format. // public virtual void Write(string format, params object?[] arg) { Write(string.Format(FormatProvider, format, arg)); } // Writes a line terminator to the text stream. The default line terminator // is Environment.NewLine, but this value can be changed by setting the NewLine property. // public virtual void WriteLine() { Write(CoreNewLine); } // Writes a character followed by a line terminator to the text stream. // public virtual void WriteLine(char value) { Write(value); WriteLine(); } // Writes an array of characters followed by a line terminator to the text // stream. // public virtual void WriteLine(char[]? buffer) { Write(buffer); WriteLine(); } // Writes a range of a character array followed by a line terminator to the // text stream. // public virtual void WriteLine(char[] buffer, int index, int count) { Write(buffer, index, count); WriteLine(); } public virtual void WriteLine(ReadOnlySpan<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { buffer.CopyTo(new Span<char>(array)); WriteLine(array, 0, buffer.Length); } finally { ArrayPool<char>.Shared.Return(array); } } // Writes the text representation of a boolean followed by a line // terminator to the text stream. // public virtual void WriteLine(bool value) { Write(value); WriteLine(); } // Writes the text representation of an integer followed by a line // terminator to the text stream. // public virtual void WriteLine(int value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(uint value) { Write(value); WriteLine(); } // Writes the text representation of a long followed by a line terminator // to the text stream. // public virtual void WriteLine(long value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(ulong value) { Write(value); WriteLine(); } // Writes the text representation of a float followed by a line terminator // to the text stream. // public virtual void WriteLine(float value) { Write(value); WriteLine(); } // Writes the text representation of a double followed by a line terminator // to the text stream. // public virtual void WriteLine(double value) { Write(value); WriteLine(); } public virtual void WriteLine(decimal value) { Write(value); WriteLine(); } // Writes a string followed by a line terminator to the text stream. // public virtual void WriteLine(string? value) { if (value != null) { Write(value); } Write(CoreNewLineStr); } /// <summary> /// Equivalent to WriteLine(stringBuilder.ToString()) however it uses the /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> public virtual void WriteLine(StringBuilder? value) { Write(value); WriteLine(); } // Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine(object? value) { if (value == null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. if (value is IFormattable f) { WriteLine(f.ToString(null, FormatProvider)); } else { WriteLine(value.ToString()); } } } // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // public virtual void WriteLine(string format, object? arg0) { WriteLine(string.Format(FormatProvider, format, arg0)); } // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // public virtual void WriteLine(string format, object? arg0, object? arg1) { WriteLine(string.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // public virtual void WriteLine(string format, object? arg0, object? arg1, object? arg2) { WriteLine(string.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string and a new line. Uses the same // semantics as string.Format. // public virtual void WriteLine(string format, params object?[] arg) { WriteLine(string.Format(FormatProvider, format, arg)); } #region Task based Async APIs public virtual Task WriteAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state!; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteAsync(string? value) { var tuple = new Tuple<TextWriter, string?>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string?>)state!; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary> /// Equivalent to WriteAsync(stringBuilder.ToString()) however it uses the /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> /// <param name="value">The string (as a StringBuilder) to write to the stream</param> public virtual Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : value == null ? Task.CompletedTask : WriteAsyncCore(value, cancellationToken); async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct) { foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) { await WriteAsync(chunk, ct).ConfigureAwait(false); } } } public Task WriteAsync(char[]? buffer) { if (buffer == null) { return Task.CompletedTask; } return WriteAsync(buffer, 0, buffer.Length); } public virtual Task WriteAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state!; t.Item1.Write(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? WriteAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state!; t.Item1.Write(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task WriteLineAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state!; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteLineAsync(string? value) { var tuple = new Tuple<TextWriter, string?>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string?>)state!; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } /// <summary> /// Equivalent to WriteLineAsync(stringBuilder.ToString()) however it uses the /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// </summary> /// <param name="value">The string (as a StringBuilder) to write to the stream</param> public virtual Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : value == null ? WriteAsync(CoreNewLine, cancellationToken) : WriteLineAsyncCore(value, cancellationToken); async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct) { foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) { await WriteAsync(chunk, ct).ConfigureAwait(false); } await WriteAsync(CoreNewLine, ct).ConfigureAwait(false); } } public Task WriteLineAsync(char[]? buffer) { if (buffer == null) { return WriteLineAsync(); } return WriteLineAsync(buffer, 0, buffer.Length); } public virtual Task WriteLineAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state!; t.Item1.WriteLine(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public virtual Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? WriteLineAsync(array.Array!, array.Offset, array.Count) : Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, ReadOnlyMemory<char>>)state!; t.Item1.WriteLine(t.Item2.Span); }, Tuple.Create(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task WriteLineAsync() { return WriteAsync(CoreNewLine); } public virtual Task FlushAsync() { return Task.Factory.StartNew(state => { ((TextWriter)state!).Flush(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } #endregion private sealed class NullTextWriter : TextWriter { internal NullTextWriter() : base(CultureInfo.InvariantCulture) { } public override Encoding Encoding { get { return Encoding.Unicode; } } public override void Write(char[] buffer, int index, int count) { } public override void Write(string? value) { } // Not strictly necessary, but for perf reasons public override void WriteLine() { } // Not strictly necessary, but for perf reasons public override void WriteLine(string? value) { } public override void WriteLine(object? value) { } public override void Write(char value) { } } public static TextWriter Synchronized(TextWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); return writer is SyncTextWriter ? writer : new SyncTextWriter(writer); } internal sealed class SyncTextWriter : TextWriter, IDisposable { private readonly TextWriter _out; internal SyncTextWriter(TextWriter t) : base(t.FormatProvider) { _out = t; } public override Encoding Encoding => _out.Encoding; public override IFormatProvider FormatProvider => _out.FormatProvider; [AllowNull] public override string NewLine { [MethodImpl(MethodImplOptions.Synchronized)] get { return _out.NewLine; } [MethodImpl(MethodImplOptions.Synchronized)] set { _out.NewLine = value; } } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _out.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_out).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override void Flush() => _out.Flush(); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[]? buffer) => _out.Write(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(char[] buffer, int index, int count) => _out.Write(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(ReadOnlySpan<char> buffer) => _out.Write(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(bool value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(int value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(uint value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(long value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(ulong value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(float value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(double value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(decimal value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string? value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(StringBuilder? value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(object? value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object? arg0) => _out.Write(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object? arg0, object? arg1) => _out.Write(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object? arg0, object? arg1, object? arg2) => _out.Write(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string format, object?[] arg) => _out.Write(format, arg); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine() => _out.WriteLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(decimal value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[]? buffer) => _out.WriteLine(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer, int index, int count) => _out.WriteLine(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(ReadOnlySpan<char> buffer) => _out.WriteLine(buffer); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(bool value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(int value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(uint value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(long value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(ulong value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(float value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(double value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string? value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(StringBuilder? value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(object? value) => _out.WriteLine(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object? arg0) => _out.WriteLine(format, arg0); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object? arg0, object? arg1) => _out.WriteLine(format, arg0, arg1); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object? arg0, object? arg1, object? arg2) => _out.WriteLine(format, arg0, arg1, arg2); [MethodImpl(MethodImplOptions.Synchronized)] public override void WriteLine(string format, object?[] arg) => _out.WriteLine(format, arg); // // On SyncTextWriter all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override ValueTask DisposeAsync() { Dispose(); return default; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(string? value) { Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Write(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(char[] buffer, int index, int count) { Write(buffer, index, count); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Write(buffer.Span); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } WriteLine(buffer.Span); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync() { WriteLine(); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(string? value) { WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } WriteLine(value); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task WriteLineAsync(char[] buffer, int index, int count) { WriteLine(buffer, index, count); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.Synchronized)] public override Task FlushAsync() { Flush(); return Task.CompletedTask; } } } }
//------------------------------------------------------------------------------ // <copyright file="DataRowCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> // <owner current="false" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; public sealed class DataRowCollection : InternalDataCollectionBase { private sealed class DataRowTree : RBTree<DataRow> { internal DataRowTree() : base(TreeAccessMethod.INDEX_ONLY) { } protected override int CompareNode (DataRow record1, DataRow record2) { throw ExceptionBuilder.InternalRBTreeError(RBTreeError.CompareNodeInDataRowTree); } protected override int CompareSateliteTreeNode (DataRow record1, DataRow record2) { throw ExceptionBuilder.InternalRBTreeError(RBTreeError.CompareSateliteTreeNodeInDataRowTree); } } private readonly DataTable table; private readonly DataRowTree list = new DataRowTree(); internal int nullInList = 0; /// <devdoc> /// Creates the DataRowCollection for the given table. /// </devdoc> internal DataRowCollection(DataTable table) { this.table = table; } public override int Count { get { return list.Count; } } /// <devdoc> /// <para>Gets the row at the specified index.</para> /// </devdoc> public DataRow this[int index] { get { return list[index]; } } /// <devdoc> /// <para>Adds the specified <see cref='System.Data.DataRow'/> to the <see cref='System.Data.DataRowCollection'/> object.</para> /// </devdoc> public void Add(DataRow row) { table.AddRow(row, -1); } public void InsertAt(DataRow row, int pos) { if (pos < 0) throw ExceptionBuilder.RowInsertOutOfRange(pos); if (pos >= list.Count) table.AddRow(row, -1); else table.InsertRow(row, -1, pos); } internal void DiffInsertAt(DataRow row, int pos) { if ((pos < 0) || (pos == list.Count)) { table.AddRow(row, pos >-1? pos+1 : -1); return; } if (table.NestedParentRelations.Length > 0) { // get in this trouble only if table has a nested parent // get into trouble if table has JUST a nested parent? how about multi parent! if (pos < list.Count) { if (list[pos] != null) { throw ExceptionBuilder.RowInsertTwice(pos, table.TableName); } list.RemoveAt(pos); nullInList--; table.InsertRow(row, pos+1, pos); } else { while (pos>list.Count) { list.Add(null); nullInList++; } table.AddRow(row, pos+1); } } else { table.InsertRow(row, pos+1, pos > list.Count ? -1 : pos); } } public Int32 IndexOf(DataRow row) { if ((null == row) || (row.Table != this.table) || ((0 == row.RBTreeNodeId) && (row.RowState == DataRowState.Detached))) //Webdata 102857 return -1; return list.IndexOf(row.RBTreeNodeId, row); } /// <devdoc> /// <para>Creates a row using specified values and adds it to the /// <see cref='System.Data.DataRowCollection'/>.</para> /// </devdoc> internal DataRow AddWithColumnEvents(params object[] values) { DataRow row = table.NewRow(-1); row.ItemArray = values; table.AddRow(row, -1); return row; } public DataRow Add(params object[] values) { int record = table.NewRecordFromArray(values); DataRow row = table.NewRow(record); table.AddRow(row, -1); return row; } internal void ArrayAdd(DataRow row) { row.RBTreeNodeId = list.Add(row); } internal void ArrayInsert(DataRow row, int pos) { row.RBTreeNodeId = list.Insert(pos, row); } internal void ArrayClear() { list.Clear(); } internal void ArrayRemove(DataRow row) { if (row.RBTreeNodeId == 0) { throw ExceptionBuilder.InternalRBTreeError(RBTreeError.AttachedNodeWithZerorbTreeNodeId); } list.RBDelete(row.RBTreeNodeId); row.RBTreeNodeId = 0; } /// <devdoc> /// <para>Gets /// the row specified by the primary key value. /// </para> /// </devdoc> public DataRow Find(object key) { return table.FindByPrimaryKey(key); } /// <devdoc> /// <para>Gets the row containing the specified primary key values.</para> /// </devdoc> public DataRow Find(object[] keys) { return table.FindByPrimaryKey(keys); } /// <devdoc> /// <para>Clears the collection of all rows.</para> /// </devdoc> public void Clear() { table.Clear(false); } /// <devdoc> /// <para> /// Gets a value indicating whether the primary key of any row in the /// collection contains the specified value. /// </para> /// </devdoc> public bool Contains(object key) { return(table.FindByPrimaryKey(key) != null); } /// <devdoc> /// <para> /// Gets a value indicating if the <see cref='System.Data.DataRow'/> with /// the specified primary key values exists. /// </para> /// </devdoc> public bool Contains(object[] keys) { return(table.FindByPrimaryKey(keys) != null); } public override void CopyTo(Array ar, int index) { list.CopyTo(ar, index); } public void CopyTo(DataRow[] array, int index) { list.CopyTo(array, index); } public override IEnumerator GetEnumerator() { return list.GetEnumerator(); } /// <devdoc> /// <para>Removes the specified <see cref='System.Data.DataRow'/> from the collection.</para> /// </devdoc> public void Remove(DataRow row) { if ((null == row) || (row.Table != table) || (-1 == row.rowID)) { throw ExceptionBuilder.RowOutOfRange(); } if ((row.RowState != DataRowState.Deleted) && (row.RowState != DataRowState.Detached)) row.Delete(); if (row.RowState != DataRowState.Detached) row.AcceptChanges(); } /// <devdoc> /// <para> /// Removes the row with the specified index from /// the collection. /// </para> /// </devdoc> public void RemoveAt(int index) { Remove(this[index]); } } }
#if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabResultEvent<LoginResult> OnLoginResultEvent; public event PlayFabRequestEvent<GetPhotonAuthenticationTokenRequest> OnGetPhotonAuthenticationTokenRequestEvent; public event PlayFabResultEvent<GetPhotonAuthenticationTokenResult> OnGetPhotonAuthenticationTokenResultEvent; public event PlayFabRequestEvent<GetTitlePublicKeyRequest> OnGetTitlePublicKeyRequestEvent; public event PlayFabResultEvent<GetTitlePublicKeyResult> OnGetTitlePublicKeyResultEvent; public event PlayFabRequestEvent<GetWindowsHelloChallengeRequest> OnGetWindowsHelloChallengeRequestEvent; public event PlayFabResultEvent<GetWindowsHelloChallengeResponse> OnGetWindowsHelloChallengeResultEvent; public event PlayFabRequestEvent<LoginWithAndroidDeviceIDRequest> OnLoginWithAndroidDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithCustomIDRequest> OnLoginWithCustomIDRequestEvent; public event PlayFabRequestEvent<LoginWithEmailAddressRequest> OnLoginWithEmailAddressRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookRequest> OnLoginWithFacebookRequestEvent; public event PlayFabRequestEvent<LoginWithGameCenterRequest> OnLoginWithGameCenterRequestEvent; public event PlayFabRequestEvent<LoginWithGoogleAccountRequest> OnLoginWithGoogleAccountRequestEvent; public event PlayFabRequestEvent<LoginWithIOSDeviceIDRequest> OnLoginWithIOSDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithKongregateRequest> OnLoginWithKongregateRequestEvent; public event PlayFabRequestEvent<LoginWithPlayFabRequest> OnLoginWithPlayFabRequestEvent; public event PlayFabRequestEvent<LoginWithSteamRequest> OnLoginWithSteamRequestEvent; public event PlayFabRequestEvent<LoginWithTwitchRequest> OnLoginWithTwitchRequestEvent; public event PlayFabRequestEvent<LoginWithWindowsHelloRequest> OnLoginWithWindowsHelloRequestEvent; public event PlayFabRequestEvent<RegisterPlayFabUserRequest> OnRegisterPlayFabUserRequestEvent; public event PlayFabResultEvent<RegisterPlayFabUserResult> OnRegisterPlayFabUserResultEvent; public event PlayFabRequestEvent<RegisterWithWindowsHelloRequest> OnRegisterWithWindowsHelloRequestEvent; public event PlayFabRequestEvent<SetPlayerSecretRequest> OnSetPlayerSecretRequestEvent; public event PlayFabResultEvent<SetPlayerSecretResult> OnSetPlayerSecretResultEvent; public event PlayFabRequestEvent<AddGenericIDRequest> OnAddGenericIDRequestEvent; public event PlayFabResultEvent<AddGenericIDResult> OnAddGenericIDResultEvent; public event PlayFabRequestEvent<AddUsernamePasswordRequest> OnAddUsernamePasswordRequestEvent; public event PlayFabResultEvent<AddUsernamePasswordResult> OnAddUsernamePasswordResultEvent; public event PlayFabRequestEvent<GetAccountInfoRequest> OnGetAccountInfoRequestEvent; public event PlayFabResultEvent<GetAccountInfoResult> OnGetAccountInfoResultEvent; public event PlayFabRequestEvent<GetPlayerCombinedInfoRequest> OnGetPlayerCombinedInfoRequestEvent; public event PlayFabResultEvent<GetPlayerCombinedInfoResult> OnGetPlayerCombinedInfoResultEvent; public event PlayFabRequestEvent<GetPlayerProfileRequest> OnGetPlayerProfileRequestEvent; public event PlayFabResultEvent<GetPlayerProfileResult> OnGetPlayerProfileResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookIDsRequest> OnGetPlayFabIDsFromFacebookIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookIDsResult> OnGetPlayFabIDsFromFacebookIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGameCenterIDsRequest> OnGetPlayFabIDsFromGameCenterIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGameCenterIDsResult> OnGetPlayFabIDsFromGameCenterIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGenericIDsRequest> OnGetPlayFabIDsFromGenericIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGenericIDsResult> OnGetPlayFabIDsFromGenericIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGoogleIDsRequest> OnGetPlayFabIDsFromGoogleIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGoogleIDsResult> OnGetPlayFabIDsFromGoogleIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromKongregateIDsRequest> OnGetPlayFabIDsFromKongregateIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromKongregateIDsResult> OnGetPlayFabIDsFromKongregateIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromSteamIDsRequest> OnGetPlayFabIDsFromSteamIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromSteamIDsResult> OnGetPlayFabIDsFromSteamIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromTwitchIDsRequest> OnGetPlayFabIDsFromTwitchIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromTwitchIDsResult> OnGetPlayFabIDsFromTwitchIDsResultEvent; public event PlayFabRequestEvent<LinkAndroidDeviceIDRequest> OnLinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<LinkAndroidDeviceIDResult> OnLinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<LinkCustomIDRequest> OnLinkCustomIDRequestEvent; public event PlayFabResultEvent<LinkCustomIDResult> OnLinkCustomIDResultEvent; public event PlayFabRequestEvent<LinkFacebookAccountRequest> OnLinkFacebookAccountRequestEvent; public event PlayFabResultEvent<LinkFacebookAccountResult> OnLinkFacebookAccountResultEvent; public event PlayFabRequestEvent<LinkGameCenterAccountRequest> OnLinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<LinkGameCenterAccountResult> OnLinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<LinkGoogleAccountRequest> OnLinkGoogleAccountRequestEvent; public event PlayFabResultEvent<LinkGoogleAccountResult> OnLinkGoogleAccountResultEvent; public event PlayFabRequestEvent<LinkIOSDeviceIDRequest> OnLinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<LinkIOSDeviceIDResult> OnLinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<LinkKongregateAccountRequest> OnLinkKongregateRequestEvent; public event PlayFabResultEvent<LinkKongregateAccountResult> OnLinkKongregateResultEvent; public event PlayFabRequestEvent<LinkSteamAccountRequest> OnLinkSteamAccountRequestEvent; public event PlayFabResultEvent<LinkSteamAccountResult> OnLinkSteamAccountResultEvent; public event PlayFabRequestEvent<LinkTwitchAccountRequest> OnLinkTwitchRequestEvent; public event PlayFabResultEvent<LinkTwitchAccountResult> OnLinkTwitchResultEvent; public event PlayFabRequestEvent<LinkWindowsHelloAccountRequest> OnLinkWindowsHelloRequestEvent; public event PlayFabResultEvent<LinkWindowsHelloAccountResponse> OnLinkWindowsHelloResultEvent; public event PlayFabRequestEvent<RemoveGenericIDRequest> OnRemoveGenericIDRequestEvent; public event PlayFabResultEvent<RemoveGenericIDResult> OnRemoveGenericIDResultEvent; public event PlayFabRequestEvent<ReportPlayerClientRequest> OnReportPlayerRequestEvent; public event PlayFabResultEvent<ReportPlayerClientResult> OnReportPlayerResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<UnlinkAndroidDeviceIDRequest> OnUnlinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkAndroidDeviceIDResult> OnUnlinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkCustomIDRequest> OnUnlinkCustomIDRequestEvent; public event PlayFabResultEvent<UnlinkCustomIDResult> OnUnlinkCustomIDResultEvent; public event PlayFabRequestEvent<UnlinkFacebookAccountRequest> OnUnlinkFacebookAccountRequestEvent; public event PlayFabResultEvent<UnlinkFacebookAccountResult> OnUnlinkFacebookAccountResultEvent; public event PlayFabRequestEvent<UnlinkGameCenterAccountRequest> OnUnlinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<UnlinkGameCenterAccountResult> OnUnlinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<UnlinkGoogleAccountRequest> OnUnlinkGoogleAccountRequestEvent; public event PlayFabResultEvent<UnlinkGoogleAccountResult> OnUnlinkGoogleAccountResultEvent; public event PlayFabRequestEvent<UnlinkIOSDeviceIDRequest> OnUnlinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkIOSDeviceIDResult> OnUnlinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkKongregateAccountRequest> OnUnlinkKongregateRequestEvent; public event PlayFabResultEvent<UnlinkKongregateAccountResult> OnUnlinkKongregateResultEvent; public event PlayFabRequestEvent<UnlinkSteamAccountRequest> OnUnlinkSteamAccountRequestEvent; public event PlayFabResultEvent<UnlinkSteamAccountResult> OnUnlinkSteamAccountResultEvent; public event PlayFabRequestEvent<UnlinkTwitchAccountRequest> OnUnlinkTwitchRequestEvent; public event PlayFabResultEvent<UnlinkTwitchAccountResult> OnUnlinkTwitchResultEvent; public event PlayFabRequestEvent<UnlinkWindowsHelloAccountRequest> OnUnlinkWindowsHelloRequestEvent; public event PlayFabResultEvent<UnlinkWindowsHelloAccountResponse> OnUnlinkWindowsHelloResultEvent; public event PlayFabRequestEvent<UpdateAvatarUrlRequest> OnUpdateAvatarUrlRequestEvent; public event PlayFabResultEvent<EmptyResult> OnUpdateAvatarUrlResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardRequest> OnGetFriendLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetFriendLeaderboardResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardAroundPlayerRequest> OnGetFriendLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetFriendLeaderboardAroundPlayerResult> OnGetFriendLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetLeaderboardRequest> OnGetLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetLeaderboardResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundPlayerRequest> OnGetLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundPlayerResult> OnGetLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticsRequest> OnGetPlayerStatisticsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticsResult> OnGetPlayerStatisticsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticsRequest> OnUpdatePlayerStatisticsRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticsResult> OnUpdatePlayerStatisticsResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTimeRequest> OnGetTimeRequestEvent; public event PlayFabResultEvent<GetTimeResult> OnGetTimeResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleNewsRequest> OnGetTitleNewsRequestEvent; public event PlayFabResultEvent<GetTitleNewsResult> OnGetTitleNewsResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<ConfirmPurchaseRequest> OnConfirmPurchaseRequestEvent; public event PlayFabResultEvent<ConfirmPurchaseResult> OnConfirmPurchaseResultEvent; public event PlayFabRequestEvent<ConsumeItemRequest> OnConsumeItemRequestEvent; public event PlayFabResultEvent<ConsumeItemResult> OnConsumeItemResultEvent; public event PlayFabRequestEvent<GetCharacterInventoryRequest> OnGetCharacterInventoryRequestEvent; public event PlayFabResultEvent<GetCharacterInventoryResult> OnGetCharacterInventoryResultEvent; public event PlayFabRequestEvent<GetPurchaseRequest> OnGetPurchaseRequestEvent; public event PlayFabResultEvent<GetPurchaseResult> OnGetPurchaseResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnGetUserInventoryResultEvent; public event PlayFabRequestEvent<PayForPurchaseRequest> OnPayForPurchaseRequestEvent; public event PlayFabResultEvent<PayForPurchaseResult> OnPayForPurchaseResultEvent; public event PlayFabRequestEvent<PurchaseItemRequest> OnPurchaseItemRequestEvent; public event PlayFabResultEvent<PurchaseItemResult> OnPurchaseItemResultEvent; public event PlayFabRequestEvent<RedeemCouponRequest> OnRedeemCouponRequestEvent; public event PlayFabResultEvent<RedeemCouponResult> OnRedeemCouponResultEvent; public event PlayFabRequestEvent<StartPurchaseRequest> OnStartPurchaseRequestEvent; public event PlayFabResultEvent<StartPurchaseResult> OnStartPurchaseResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<UnlockContainerInstanceRequest> OnUnlockContainerInstanceRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerInstanceResultEvent; public event PlayFabRequestEvent<UnlockContainerItemRequest> OnUnlockContainerItemRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerItemResultEvent; public event PlayFabRequestEvent<AddFriendRequest> OnAddFriendRequestEvent; public event PlayFabResultEvent<AddFriendResult> OnAddFriendResultEvent; public event PlayFabRequestEvent<GetFriendsListRequest> OnGetFriendsListRequestEvent; public event PlayFabResultEvent<GetFriendsListResult> OnGetFriendsListResultEvent; public event PlayFabRequestEvent<RemoveFriendRequest> OnRemoveFriendRequestEvent; public event PlayFabResultEvent<RemoveFriendResult> OnRemoveFriendResultEvent; public event PlayFabRequestEvent<SetFriendTagsRequest> OnSetFriendTagsRequestEvent; public event PlayFabResultEvent<SetFriendTagsResult> OnSetFriendTagsResultEvent; public event PlayFabRequestEvent<CurrentGamesRequest> OnGetCurrentGamesRequestEvent; public event PlayFabResultEvent<CurrentGamesResult> OnGetCurrentGamesResultEvent; public event PlayFabRequestEvent<GameServerRegionsRequest> OnGetGameServerRegionsRequestEvent; public event PlayFabResultEvent<GameServerRegionsResult> OnGetGameServerRegionsResultEvent; public event PlayFabRequestEvent<MatchmakeRequest> OnMatchmakeRequestEvent; public event PlayFabResultEvent<MatchmakeResult> OnMatchmakeResultEvent; public event PlayFabRequestEvent<StartGameRequest> OnStartGameRequestEvent; public event PlayFabResultEvent<StartGameResult> OnStartGameResultEvent; public event PlayFabRequestEvent<WriteClientCharacterEventRequest> OnWriteCharacterEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteCharacterEventResultEvent; public event PlayFabRequestEvent<WriteClientPlayerEventRequest> OnWritePlayerEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWritePlayerEventResultEvent; public event PlayFabRequestEvent<WriteTitleEventRequest> OnWriteTitleEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteTitleEventResultEvent; public event PlayFabRequestEvent<AddSharedGroupMembersRequest> OnAddSharedGroupMembersRequestEvent; public event PlayFabResultEvent<AddSharedGroupMembersResult> OnAddSharedGroupMembersResultEvent; public event PlayFabRequestEvent<CreateSharedGroupRequest> OnCreateSharedGroupRequestEvent; public event PlayFabResultEvent<CreateSharedGroupResult> OnCreateSharedGroupResultEvent; public event PlayFabRequestEvent<GetSharedGroupDataRequest> OnGetSharedGroupDataRequestEvent; public event PlayFabResultEvent<GetSharedGroupDataResult> OnGetSharedGroupDataResultEvent; public event PlayFabRequestEvent<RemoveSharedGroupMembersRequest> OnRemoveSharedGroupMembersRequestEvent; public event PlayFabResultEvent<RemoveSharedGroupMembersResult> OnRemoveSharedGroupMembersResultEvent; public event PlayFabRequestEvent<UpdateSharedGroupDataRequest> OnUpdateSharedGroupDataRequestEvent; public event PlayFabResultEvent<UpdateSharedGroupDataResult> OnUpdateSharedGroupDataResultEvent; public event PlayFabRequestEvent<ExecuteCloudScriptRequest> OnExecuteCloudScriptRequestEvent; public event PlayFabResultEvent<ExecuteCloudScriptResult> OnExecuteCloudScriptResultEvent; public event PlayFabRequestEvent<GetContentDownloadUrlRequest> OnGetContentDownloadUrlRequestEvent; public event PlayFabResultEvent<GetContentDownloadUrlResult> OnGetContentDownloadUrlResultEvent; public event PlayFabRequestEvent<ListUsersCharactersRequest> OnGetAllUsersCharactersRequestEvent; public event PlayFabResultEvent<ListUsersCharactersResult> OnGetAllUsersCharactersResultEvent; public event PlayFabRequestEvent<GetCharacterLeaderboardRequest> OnGetCharacterLeaderboardRequestEvent; public event PlayFabResultEvent<GetCharacterLeaderboardResult> OnGetCharacterLeaderboardResultEvent; public event PlayFabRequestEvent<GetCharacterStatisticsRequest> OnGetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<GetCharacterStatisticsResult> OnGetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundCharacterRequest> OnGetLeaderboardAroundCharacterRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundCharacterResult> OnGetLeaderboardAroundCharacterResultEvent; public event PlayFabRequestEvent<GetLeaderboardForUsersCharactersRequest> OnGetLeaderboardForUserCharactersRequestEvent; public event PlayFabResultEvent<GetLeaderboardForUsersCharactersResult> OnGetLeaderboardForUserCharactersResultEvent; public event PlayFabRequestEvent<GrantCharacterToUserRequest> OnGrantCharacterToUserRequestEvent; public event PlayFabResultEvent<GrantCharacterToUserResult> OnGrantCharacterToUserResultEvent; public event PlayFabRequestEvent<UpdateCharacterStatisticsRequest> OnUpdateCharacterStatisticsRequestEvent; public event PlayFabResultEvent<UpdateCharacterStatisticsResult> OnUpdateCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterDataResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterReadOnlyDataResultEvent; public event PlayFabRequestEvent<UpdateCharacterDataRequest> OnUpdateCharacterDataRequestEvent; public event PlayFabResultEvent<UpdateCharacterDataResult> OnUpdateCharacterDataResultEvent; public event PlayFabRequestEvent<AcceptTradeRequest> OnAcceptTradeRequestEvent; public event PlayFabResultEvent<AcceptTradeResponse> OnAcceptTradeResultEvent; public event PlayFabRequestEvent<CancelTradeRequest> OnCancelTradeRequestEvent; public event PlayFabResultEvent<CancelTradeResponse> OnCancelTradeResultEvent; public event PlayFabRequestEvent<GetPlayerTradesRequest> OnGetPlayerTradesRequestEvent; public event PlayFabResultEvent<GetPlayerTradesResponse> OnGetPlayerTradesResultEvent; public event PlayFabRequestEvent<GetTradeStatusRequest> OnGetTradeStatusRequestEvent; public event PlayFabResultEvent<GetTradeStatusResponse> OnGetTradeStatusResultEvent; public event PlayFabRequestEvent<OpenTradeRequest> OnOpenTradeRequestEvent; public event PlayFabResultEvent<OpenTradeResponse> OnOpenTradeResultEvent; public event PlayFabRequestEvent<AttributeInstallRequest> OnAttributeInstallRequestEvent; public event PlayFabResultEvent<AttributeInstallResult> OnAttributeInstallResultEvent; public event PlayFabRequestEvent<GetPlayerSegmentsRequest> OnGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnGetPlayerTagsResultEvent; public event PlayFabRequestEvent<AndroidDevicePushNotificationRegistrationRequest> OnAndroidDevicePushNotificationRegistrationRequestEvent; public event PlayFabResultEvent<AndroidDevicePushNotificationRegistrationResult> OnAndroidDevicePushNotificationRegistrationResultEvent; public event PlayFabRequestEvent<RegisterForIOSPushNotificationRequest> OnRegisterForIOSPushNotificationRequestEvent; public event PlayFabResultEvent<RegisterForIOSPushNotificationResult> OnRegisterForIOSPushNotificationResultEvent; public event PlayFabRequestEvent<RestoreIOSPurchasesRequest> OnRestoreIOSPurchasesRequestEvent; public event PlayFabResultEvent<RestoreIOSPurchasesResult> OnRestoreIOSPurchasesResultEvent; public event PlayFabRequestEvent<ValidateAmazonReceiptRequest> OnValidateAmazonIAPReceiptRequestEvent; public event PlayFabResultEvent<ValidateAmazonReceiptResult> OnValidateAmazonIAPReceiptResultEvent; public event PlayFabRequestEvent<ValidateGooglePlayPurchaseRequest> OnValidateGooglePlayPurchaseRequestEvent; public event PlayFabResultEvent<ValidateGooglePlayPurchaseResult> OnValidateGooglePlayPurchaseResultEvent; public event PlayFabRequestEvent<ValidateIOSReceiptRequest> OnValidateIOSReceiptRequestEvent; public event PlayFabResultEvent<ValidateIOSReceiptResult> OnValidateIOSReceiptResultEvent; public event PlayFabRequestEvent<ValidateWindowsReceiptRequest> OnValidateWindowsStoreReceiptRequestEvent; public event PlayFabResultEvent<ValidateWindowsReceiptResult> OnValidateWindowsStoreReceiptResultEvent; } } #endif
/* Distributed as part of TiledSharp, Copyright 2012 Marshall Ward * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ using System; using System.Collections.ObjectModel; using System.IO; using System.Xml.Linq; namespace TiledSharp { // TODO: The design here is all wrong. A Tileset should be a list of tiles, // it shouldn't force the user to do so much tile ID management public class TmxTileset : TmxDocument, ITmxElement { public int FirstGid {get; private set;} public string Name {get; private set;} public int TileWidth {get; private set;} public int TileHeight {get; private set;} public int Spacing {get; private set;} public int Margin {get; private set;} public int? Columns {get; private set;} public int? TileCount {get; private set;} public int? Colums {get; private set;} public Collection<TmxTilesetTile> Tiles {get; private set;} public TmxTileOffset TileOffset {get; private set;} public PropertyDict Properties {get; private set;} public TmxImage Image {get; private set;} public TmxList<TmxTerrain> Terrains {get; private set;} // TSX file constructor public TmxTileset(IDocumentLoader loader, XDocument xDoc, string tmxDir) : this(loader, xDoc.Element("tileset"), tmxDir) { } // TMX tileset element constructor public TmxTileset(IDocumentLoader loader, XElement xTileset, string tmxDir = "") : base(loader) { var xFirstGid = xTileset.Attribute("firstgid"); var source = (string) xTileset.Attribute("source"); if (source != null) { // Prepend the parent TMX directory if necessary source = Path.Combine(tmxDir, source); // source is always preceded by firstgid FirstGid = (int) xFirstGid; // Everything else is in the TSX file var xDocTileset = ReadXml(source); var ts = new TmxTileset(loader, xDocTileset, TmxDirectory); Name = ts.Name; TileWidth = ts.TileWidth; TileHeight = ts.TileHeight; Spacing = ts.Spacing; Margin = ts.Margin; Columns = ts.Columns; TileCount = ts.TileCount; TileOffset = ts.TileOffset; Image = ts.Image; Terrains = ts.Terrains; Tiles = ts.Tiles; Properties = ts.Properties; } else { // firstgid is always in TMX, but not TSX if (xFirstGid != null) FirstGid = (int) xFirstGid; Name = (string) xTileset.Attribute("name"); TileWidth = (int) xTileset.Attribute("tilewidth"); TileHeight = (int) xTileset.Attribute("tileheight"); Spacing = (int?) xTileset.Attribute("spacing") ?? 0; Margin = (int?) xTileset.Attribute("margin") ?? 0; Columns = (int?) xTileset.Attribute("columns"); TileCount = (int?) xTileset.Attribute("tilecount"); Colums = (int?) xTileset.Attribute("columns"); TileOffset = new TmxTileOffset(xTileset.Element("tileoffset")); Image = new TmxImage(xTileset.Element("image"), tmxDir); Terrains = new TmxList<TmxTerrain>(); var xTerrainType = xTileset.Element("terraintypes"); if (xTerrainType != null) { foreach (var e in xTerrainType.Elements("terrain")) Terrains.Add(new TmxTerrain(e)); } Tiles = new Collection<TmxTilesetTile>(); foreach (var xTile in xTileset.Elements("tile")) { var tile = new TmxTilesetTile(xTile, Terrains, tmxDir); Tiles.Add(tile); } Properties = new PropertyDict(xTileset.Element("properties")); } } } public class TmxTileOffset { public int X {get; private set;} public int Y {get; private set;} public TmxTileOffset(XElement xTileOffset) { if (xTileOffset == null) { X = 0; Y = 0; } else { X = (int)xTileOffset.Attribute("x"); Y = (int)xTileOffset.Attribute("y"); } } } public class TmxTerrain : ITmxElement { public string Name {get; private set;} public int Tile {get; private set;} public PropertyDict Properties {get; private set;} public TmxTerrain(XElement xTerrain) { Name = (string)xTerrain.Attribute("name"); Tile = (int)xTerrain.Attribute("tile"); Properties = new PropertyDict(xTerrain.Element("properties")); } } public class TmxTilesetTile { public int Id {get; private set;} public Collection<TmxTerrain> TerrainEdges {get; private set;} public double Probability {get; private set;} public PropertyDict Properties {get; private set;} public TmxImage Image {get; private set;} public TmxList<TmxObjectGroup> ObjectGroups {get; private set;} public Collection<TmxAnimationFrame> AnimationFrames {get; private set;} // Human-readable aliases to the Terrain markers public TmxTerrain TopLeft { get { return TerrainEdges[0]; } } public TmxTerrain TopRight { get { return TerrainEdges[1]; } } public TmxTerrain BottomLeft { get { return TerrainEdges[2]; } } public TmxTerrain BottomRight { get { return TerrainEdges[3]; } } public TmxTilesetTile(XElement xTile, TmxList<TmxTerrain> Terrains, string tmxDir = "") { Id = (int)xTile.Attribute("id"); TerrainEdges = new Collection<TmxTerrain>(); int result; TmxTerrain edge; var strTerrain = (string)xTile.Attribute("terrain") ?? ",,,"; foreach (var v in strTerrain.Split(',')) { var success = int.TryParse(v, out result); if (success) edge = Terrains[result]; else edge = null; TerrainEdges.Add(edge); // TODO: Assert that TerrainEdges length is 4 } Probability = (double?)xTile.Attribute("probability") ?? 1.0; Image = new TmxImage(xTile.Element("image"), tmxDir); ObjectGroups = new TmxList<TmxObjectGroup>(); var orderIndex = 0; foreach (var e in xTile.Elements("objectgroup")) ObjectGroups.Add(new TmxObjectGroup(e, orderIndex++)); AnimationFrames = new Collection<TmxAnimationFrame>(); if (xTile.Element("animation") != null) { foreach (var e in xTile.Element("animation").Elements("frame")) AnimationFrames.Add(new TmxAnimationFrame(e)); } Properties = new PropertyDict(xTile.Element("properties")); } } public class TmxAnimationFrame { public int Id {get; private set;} public int Duration {get; private set;} public TmxAnimationFrame(XElement xFrame) { Id = (int)xFrame.Attribute("tileid"); Duration = (int)xFrame.Attribute("duration"); } } }
using Microsoft.Extensions.Logging; using System; using System.Diagnostics; namespace Orleans.Runtime { /// <summary> /// Extension methods which preserves legacy orleans log methods style /// </summary> public static class OrleansLoggerExtension { /// <summary> /// Writes a log entry at the Debug severity level. /// </summary> /// <param name="logger">The logger</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Debug(this ILogger logger, string format, params object[] args) { logger.LogDebug(format, args); } /// <summary> /// Writes a log entry at the Verbose severity level. /// Verbose is suitable for debugging information that should usually not be logged in production. /// Verbose is lower than Info. /// </summary> /// <param name="logger">The logger</param> /// <param name="message">The log message.</param> public static void Debug(this ILogger logger, string message) { logger.LogDebug(message); } /// <summary> /// Writes a log entry at the Trace logLevel. /// </summary> /// <param name="logger">The logger</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Trace(this ILogger logger, string format, params object[] args) { logger.LogTrace(format, args); } /// <summary> /// Writes a log entry at the Verbose2 severity level. /// Verbose2 is lower than Verbose. /// </summary> /// <param name="logger">The logger</param> /// <param name="message">The log message.</param> public static void Trace(this ILogger logger, string message) { logger.LogTrace(message); } /// <summary> /// Writes a log entry at the Information Level /// </summary> /// <param name="logger">Target logger.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Info(this ILogger logger, string format, params object[] args) { logger.LogInformation(format, args); } /// <summary> /// Writes a log entry at the Info logLevel /// </summary> /// <param name="logger">Target logger.</param> /// <param name="message">The log message.</param> public static void Info(this ILogger logger, string message) { logger.LogInformation(message); } /// <summary> /// Writes a log entry at the Debug logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Debug(this ILogger logger, int logCode, string format, params object[] args) { logger.LogDebug(logCode, format, args); } internal static void Debug(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogDebug(LoggingUtils.CreateEventId(logCode), format, args); } /// <summary> /// Writes a log entry at the Debug logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The log message.</param> public static void Debug(this ILogger logger, int logCode, string message) { logger.LogDebug(logCode, message); } internal static void Debug(this ILogger logger, ErrorCode logCode, string message) { logger.LogDebug(LoggingUtils.CreateEventId(logCode), message); } /// <summary> /// Writes a log entry at the Trace logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Trace(this ILogger logger, int logCode, string format, params object[] args) { logger.LogTrace(logCode, format, args); } internal static void Trace(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogTrace(LoggingUtils.CreateEventId(logCode), format, args); } /// <summary> /// Writes a log entry at the Trace logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The log message.</param> public static void Trace(this ILogger logger, int logCode, string message) { logger.LogTrace(logCode, message); } internal static void Trace(this ILogger logger, ErrorCode logCode, string message) { logger.LogTrace(LoggingUtils.CreateEventId(logCode), message); } /// <summary> /// Writes a log entry at the Information logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Info(this ILogger logger, int logCode, string format, params object[] args) { logger.LogInformation(logCode, format, args); } internal static void Info(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogInformation(LoggingUtils.CreateEventId(logCode), format, args); } /// <summary> /// Writes a log entry at the Information logLevel /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The log message.</param> public static void Info(this ILogger logger, int logCode, string message) { logger.LogInformation(logCode, message); } internal static void Info(this ILogger logger, ErrorCode logCode, string message) { logger.LogInformation(LoggingUtils.CreateEventId(logCode), message); } /// <summary> /// Writes a log entry at the Warning level /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="format">Format string of the log message with named parameters /// <remarks>Not always suitable for <c>String.Format</c>. See Microsoft.Extensions.Logging MessageTemplate section for more information. Suggest to use their pattern over this extension method</remarks> /// </param> /// <param name="args">Any arguments to the format string.</param> public static void Warn(this ILogger logger, int logCode, string format, params object[] args) { logger.LogWarning(logCode, format, args); } internal static void Warn(this ILogger logger, ErrorCode logCode, string format, params object[] args) { logger.LogWarning(LoggingUtils.CreateEventId(logCode), format, args); } /// <summary> /// Writes a log entry at the Warning level /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The warning message to log.</param> /// <param name="exception">An exception related to the warning, if any.</param> public static void Warn(this ILogger logger, int logCode, string message, Exception exception = null) { logger.LogWarning(logCode, exception, message); } internal static void Warn(this ILogger logger, ErrorCode logCode, string message, Exception exception = null) { logger.LogWarning(LoggingUtils.CreateEventId(logCode), exception, message); } /// <summary> /// Writes a log entry at the Error level /// </summary> /// <param name="logger">The logger</param> /// <param name="logCode">The log code associated with this message.</param> /// <param name="message">The error message to log.</param> /// <param name="exception">An exception related to the error, if any.</param> public static void Error(this ILogger logger, int logCode, string message, Exception exception = null) { logger.LogError(logCode, exception, message); } internal static void Error(this ILogger logger, ErrorCode logCode, string message, Exception exception = null) { logger.LogError(LoggingUtils.CreateEventId(logCode), exception, message); } internal static void Assert(this ILogger logger, ErrorCode errorCode, bool condition, string message = null) { if (condition) return; if (message == null) { message = "Internal contract assertion has failed!"; } logger.Fail(errorCode, "Assert failed with message = " + message); } internal static void Fail(this ILogger logger, ErrorCode errorCode, string message) { if (message == null) { message = "Internal Fail!"; } if (errorCode == 0) { errorCode = ErrorCode.Runtime; } logger.Error(errorCode, "INTERNAL FAILURE! About to crash! Fail message is: " + message + Environment.NewLine + Environment.StackTrace); // Kill process if (Debugger.IsAttached) { Debugger.Break(); } else { logger.Error(ErrorCode.Logger_ProcessCrashing, "INTERNAL FAILURE! Process crashing!"); Environment.FailFast("Unrecoverable failure: " + message); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Buffers; using System.Buffers.Binary; using System.Diagnostics; using System.Text; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using X509IssuerSerial = System.Security.Cryptography.Xml.X509IssuerSerial; using Microsoft.Win32.SafeHandles; using CryptProvParam=Interop.Advapi32.CryptProvParam; using static Interop.Crypt32; namespace Internal.Cryptography.Pal.Windows { internal static class HelpersWindows { public static CryptographicException ToCryptographicException(this ErrorCode errorCode) { return ((int)errorCode).ToCryptographicException(); } public static string ToStringAnsi(this IntPtr psz) { return Marshal.PtrToStringAnsi(psz); } // Used for binary blobs without internal pointers. public static byte[] GetMsgParamAsByteArray(this SafeCryptMsgHandle hCryptMsg, CryptMsgParamType paramType, int index = 0) { int cbData = 0; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, null, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] pvData = new byte[cbData]; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, pvData, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return pvData.Resize(cbData); } // Used for binary blobs with internal pointers. public static SafeHandle GetMsgParamAsMemory(this SafeCryptMsgHandle hCryptMsg, CryptMsgParamType paramType, int index = 0) { int cbData = 0; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, null, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); SafeHandle pvData = SafeHeapAllocHandle.Alloc(cbData); if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, paramType, index, pvData.DangerousGetHandle(), ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return pvData; } public static byte[] ToByteArray(this DATA_BLOB blob) { if (blob.cbData == 0) return Array.Empty<byte>(); int length = (int)(blob.cbData); byte[] data = new byte[length]; Marshal.Copy(blob.pbData, data, 0, length); return data; } public static CryptMsgType GetMessageType(this SafeCryptMsgHandle hCryptMsg) { int cbData = sizeof(CryptMsgType); CryptMsgType cryptMsgType; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_TYPE_PARAM, 0, out cryptMsgType, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return cryptMsgType; } public static int GetVersion(this SafeCryptMsgHandle hCryptMsg) { int cbData = sizeof(int); int version; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_VERSION_PARAM, 0, out version, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return version; } /// <summary> /// Returns the inner content of the CMS. /// /// Special case: If the CMS is an enveloped CMS that has been decrypted and the inner content type is Oids.Pkcs7Data, the returned /// content bytes are the decoded octet bytes, rather than the encoding of those bytes. This is a documented convenience behavior of /// CryptMsgGetParam(CMSG_CONTENT_PARAM) that apparently got baked into the behavior of the managed EnvelopedCms class. /// </summary> public static ContentInfo GetContentInfo(this SafeCryptMsgHandle hCryptMsg) { byte[] oidBytes = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_INNER_CONTENT_TYPE_PARAM); // Desktop compat: If we get a null or non-terminated string back from Crypt32, throwing an exception seems more apropros but // for the desktop compat, we throw the result at the ASCII Encoder and let the chips fall where they may. int length = oidBytes.Length; if (length > 0 && oidBytes[length - 1] == 0) { length--; } string oidValue = Encoding.ASCII.GetString(oidBytes, 0, length); Oid contentType = new Oid(oidValue); byte[] content = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return new ContentInfo(contentType, content); } public static X509Certificate2Collection GetOriginatorCerts(this SafeCryptMsgHandle hCryptMsg) { int numCertificates = 0; int cbNumCertificates = sizeof(int); if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_CERT_COUNT_PARAM, 0, out numCertificates, ref cbNumCertificates)) throw Marshal.GetLastWin32Error().ToCryptographicException(); X509Certificate2Collection certs = new X509Certificate2Collection(); for (int index = 0; index < numCertificates; index++) { byte[] encodedCertificate = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CERT_PARAM, index); X509Certificate2 cert = new X509Certificate2(encodedCertificate); certs.Add(cert); } return certs; } /// <summary> /// Returns (AlgId)(-1) if oid is unknown. /// </summary> public static AlgId ToAlgId(this string oidValue) { CRYPT_OID_INFO info = Interop.Crypt32.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, oidValue, OidGroup.All, false); return (AlgId)(info.AlgId); } public static SafeCertContextHandle CreateCertContextHandle(this X509Certificate2 cert) { IntPtr pCertContext = cert.Handle; pCertContext = Interop.Crypt32.CertDuplicateCertificateContext(pCertContext); SafeCertContextHandle hCertContext = new SafeCertContextHandle(pCertContext); GC.KeepAlive(cert); return hCertContext; } public static unsafe byte[] GetSubjectKeyIdentifer(this SafeCertContextHandle hCertContext) { int cbData = 0; if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_IDENTIFIER_PROP_ID, null, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); byte[] ski = new byte[cbData]; if (!Interop.Crypt32.CertGetCertificateContextProperty(hCertContext, CertContextPropId.CERT_KEY_IDENTIFIER_PROP_ID, ski, ref cbData)) throw Marshal.GetLastWin32Error().ToCryptographicException(); return ski.Resize(cbData); } public static SubjectIdentifier ToSubjectIdentifier(this CERT_ID certId) { switch (certId.dwIdChoice) { case CertIdChoice.CERT_ID_ISSUER_SERIAL_NUMBER: { const int dwStrType = (int)(CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG); string issuer; unsafe { DATA_BLOB* dataBlobPtr = &certId.u.IssuerSerialNumber.Issuer; int nc = Interop.Crypt32.CertNameToStr((int)MsgEncodingType.All, dataBlobPtr, dwStrType, null, 0); if (nc <= 1) // The API actually return 1 when it fails; which is not what the documentation says. { throw Marshal.GetLastWin32Error().ToCryptographicException(); } Span<char> name = nc <= 128 ? stackalloc char[128] : new char[nc]; fixed (char* namePtr = name) { nc = Interop.Crypt32.CertNameToStr((int)MsgEncodingType.All, dataBlobPtr, dwStrType, namePtr, nc); if (nc <= 1) // The API actually return 1 when it fails; which is not what the documentation says. { throw Marshal.GetLastWin32Error().ToCryptographicException(); } issuer = new string(namePtr); } } byte[] serial = certId.u.IssuerSerialNumber.SerialNumber.ToByteArray(); X509IssuerSerial issuerSerial = new X509IssuerSerial(issuer, serial.ToSerialString()); return new SubjectIdentifier(SubjectIdentifierType.IssuerAndSerialNumber, issuerSerial); } case CertIdChoice.CERT_ID_KEY_IDENTIFIER: { byte[] ski = certId.u.KeyId.ToByteArray(); return new SubjectIdentifier(SubjectIdentifierType.SubjectKeyIdentifier, ski.ToSkiString()); } default: throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, certId.dwIdChoice)); } } public static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this CERT_ID certId) { // // SubjectIdentifierOrKey is just a SubjectIdentifier with an (irrelevant here) "key" option thumbtacked onto it so // the easiest way is to subcontract the job to SubjectIdentifier. // SubjectIdentifier subjectIdentifier = certId.ToSubjectIdentifier(); SubjectIdentifierType subjectIdentifierType = subjectIdentifier.Type; switch (subjectIdentifierType) { case SubjectIdentifierType.IssuerAndSerialNumber: return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.IssuerAndSerialNumber, subjectIdentifier.Value); case SubjectIdentifierType.SubjectKeyIdentifier: return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value); default: Debug.Fail("Only the framework can construct SubjectIdentifier's so if we got a bad value here, that's our fault."); throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, subjectIdentifierType)); } } public static SubjectIdentifierOrKey ToSubjectIdentifierOrKey(this CERT_PUBLIC_KEY_INFO publicKeyInfo) { int keyLength = Interop.Crypt32.CertGetPublicKeyLength(MsgEncodingType.All, ref publicKeyInfo); string oidValue = publicKeyInfo.Algorithm.pszObjId.ToStringAnsi(); AlgorithmIdentifier algorithmId = new AlgorithmIdentifier(Oid.FromOidValue(oidValue, OidGroup.PublicKeyAlgorithm), keyLength); byte[] keyValue = publicKeyInfo.PublicKey.ToByteArray(); PublicKeyInfo pki = new PublicKeyInfo(algorithmId, keyValue); return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.PublicKeyInfo, pki); } public static AlgorithmIdentifier ToAlgorithmIdentifier(this CRYPT_ALGORITHM_IDENTIFIER cryptAlgorithmIdentifer) { string oidValue = cryptAlgorithmIdentifer.pszObjId.ToStringAnsi(); AlgId algId = oidValue.ToAlgId(); int keyLength; switch (algId) { case AlgId.CALG_RC2: { if (cryptAlgorithmIdentifer.Parameters.cbData == 0) { keyLength = 0; } else { CRYPT_RC2_CBC_PARAMETERS rc2Parameters; unsafe { int cbSize = sizeof(CRYPT_RC2_CBC_PARAMETERS); if (!Interop.Crypt32.CryptDecodeObject(CryptDecodeObjectStructType.PKCS_RC2_CBC_PARAMETERS, cryptAlgorithmIdentifer.Parameters.pbData, (int)(cryptAlgorithmIdentifer.Parameters.cbData), &rc2Parameters, ref cbSize)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } switch (rc2Parameters.dwVersion) { case CryptRc2Version.CRYPT_RC2_40BIT_VERSION: keyLength = KeyLengths.Rc2_40Bit; break; case CryptRc2Version.CRYPT_RC2_56BIT_VERSION: keyLength = KeyLengths.Rc2_56Bit; break; case CryptRc2Version.CRYPT_RC2_64BIT_VERSION: keyLength = KeyLengths.Rc2_64Bit; break; case CryptRc2Version.CRYPT_RC2_128BIT_VERSION: keyLength = KeyLengths.Rc2_128Bit; break; default: keyLength = 0; break; } } break; } case AlgId.CALG_RC4: { int saltLength = 0; if (cryptAlgorithmIdentifer.Parameters.cbData != 0) { using (SafeHandle sh = Interop.Crypt32.CryptDecodeObjectToMemory(CryptDecodeObjectStructType.X509_OCTET_STRING, cryptAlgorithmIdentifer.Parameters.pbData, (int)cryptAlgorithmIdentifer.Parameters.cbData)) { unsafe { DATA_BLOB* pDataBlob = (DATA_BLOB*)(sh.DangerousGetHandle()); saltLength = (int)(pDataBlob->cbData); } } } // For RC4, keyLength = 128 - (salt length * 8). keyLength = KeyLengths.Rc4Max_128Bit - saltLength * 8; break; } case AlgId.CALG_DES: // DES key length is fixed at 64 (or 56 without the parity bits). keyLength = KeyLengths.Des_64Bit; break; case AlgId.CALG_3DES: // 3DES key length is fixed at 192 (or 168 without the parity bits). keyLength = KeyLengths.TripleDes_192Bit; break; default: // We've exhausted all the algorithm types that the desktop used to set the KeyLength for. Key lengths are not a viable way of // identifying algorithms in the long run so we will not extend this list any further. keyLength = 0; break; } AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(Oid.FromOidValue(oidValue, OidGroup.All), keyLength); switch (oidValue) { case Oids.RsaOaep: algorithmIdentifier.Parameters = cryptAlgorithmIdentifer.Parameters.ToByteArray(); break; } return algorithmIdentifier; } public static CryptographicAttributeObjectCollection GetUnprotectedAttributes(this SafeCryptMsgHandle hCryptMsg) { // For some reason, you can't ask how many attributes there are - you have to ask for the attributes and // get a CRYPT_E_ATTRIBUTES_MISSING failure if the count is 0. int cbUnprotectedAttr = 0; if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_UNPROTECTED_ATTR_PARAM, 0, null, ref cbUnprotectedAttr)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == (int)ErrorCode.CRYPT_E_ATTRIBUTES_MISSING) return new CryptographicAttributeObjectCollection(); throw lastError.ToCryptographicException(); } using (SafeHandle sh = hCryptMsg.GetMsgParamAsMemory(CryptMsgParamType.CMSG_UNPROTECTED_ATTR_PARAM)) { unsafe { CRYPT_ATTRIBUTES* pCryptAttributes = (CRYPT_ATTRIBUTES*)(sh.DangerousGetHandle()); return ToCryptographicAttributeObjectCollection(pCryptAttributes); } } } public static CspParameters GetProvParameters(this SafeProvOrNCryptKeyHandle handle) { // A normal key container name is a GUID (~34 bytes ASCII) // The longest standard provider name is 64 bytes (including the \0), // but we shouldn't have a CAPI call with a software CSP. // // In debug builds use a buffer which will need to be resized, but is big // enough to hold the DWORD "can't fail" values. Span<byte> stackSpan = stackalloc byte[ #if DEBUG sizeof(int) #else 64 #endif ]; stackSpan.Clear(); int size = stackSpan.Length; if (!Interop.Advapi32.CryptGetProvParam(handle, CryptProvParam.PP_PROVTYPE, stackSpan, ref size)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (size != sizeof(int)) { Debug.Fail("PP_PROVTYPE writes a DWORD - enum misalignment?"); throw new CryptographicException(); } int provType = MemoryMarshal.Read<int>(stackSpan.Slice(0, size)); size = stackSpan.Length; if (!Interop.Advapi32.CryptGetProvParam(handle, CryptProvParam.PP_KEYSET_TYPE, stackSpan, ref size)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (size != sizeof(int)) { Debug.Fail("PP_KEYSET_TYPE writes a DWORD - enum misalignment?"); throw new CryptographicException(); } int keysetType = MemoryMarshal.Read<int>(stackSpan.Slice(0, size)); // Only CRYPT_MACHINE_KEYSET is described as coming back, but be defensive. CspProviderFlags provFlags = ((CspProviderFlags)keysetType & CspProviderFlags.UseMachineKeyStore) | CspProviderFlags.UseExistingKey; byte[] rented = null; Span<byte> asciiStringBuf = stackSpan; string provName = GetStringProvParam(handle, CryptProvParam.PP_NAME, ref asciiStringBuf, ref rented, 0); int maxClear = provName.Length; string keyName = GetStringProvParam(handle, CryptProvParam.PP_CONTAINER, ref asciiStringBuf, ref rented, maxClear); maxClear = Math.Max(maxClear, keyName.Length); if (rented != null) { Array.Clear(rented, 0, maxClear); ArrayPool<byte>.Shared.Return(rented); } return new CspParameters(provType) { Flags = provFlags, KeyContainerName = keyName, ProviderName = provName, }; } private static string GetStringProvParam( SafeProvOrNCryptKeyHandle handle, CryptProvParam dwParam, ref Span<byte> buf, ref byte[] rented, int clearLen) { int len = buf.Length; if (!Interop.Advapi32.CryptGetProvParam(handle, dwParam, buf, ref len)) { if (len > buf.Length) { ArrayPool<byte> pool = ArrayPool<byte>.Shared; if (rented != null) { Array.Clear(rented, 0, clearLen); pool.Return(rented); } rented = pool.Rent(len); buf = rented; len = rented.Length; } else { throw Marshal.GetLastWin32Error().ToCryptographicException(); } if (!Interop.Advapi32.CryptGetProvParam(handle, dwParam, buf, ref len)) { throw Marshal.GetLastWin32Error().ToCryptographicException(); } } unsafe { fixed (byte* asciiPtr = &MemoryMarshal.GetReference(buf)) { return Marshal.PtrToStringAnsi((IntPtr)asciiPtr, len); } } } private static unsafe CryptographicAttributeObjectCollection ToCryptographicAttributeObjectCollection(CRYPT_ATTRIBUTES* pCryptAttributes) { CryptographicAttributeObjectCollection collection = new CryptographicAttributeObjectCollection(); for (int i = 0; i < pCryptAttributes->cAttr; i++) { CRYPT_ATTRIBUTE* pCryptAttribute = &(pCryptAttributes->rgAttr[i]); AddCryptAttribute(collection, pCryptAttribute); } return collection; } private static unsafe void AddCryptAttribute(CryptographicAttributeObjectCollection collection, CRYPT_ATTRIBUTE* pCryptAttribute) { string oidValue = pCryptAttribute->pszObjId.ToStringAnsi(); Oid oid = new Oid(oidValue); AsnEncodedDataCollection attributeCollection = new AsnEncodedDataCollection(); for (int i = 0; i < pCryptAttribute->cValue; i++) { byte[] encodedAttribute = pCryptAttribute->rgValue[i].ToByteArray(); AsnEncodedData attributeObject = PkcsHelpers.CreateBestPkcs9AttributeObjectAvailable(oid, encodedAttribute); attributeCollection.Add(attributeObject); } collection.Add(new CryptographicAttributeObject(oid, attributeCollection)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = LanguageVersion.Default; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> embeddedFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool embedAllSourceFiles = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; string instrument = ""; CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; string sourceLink = null; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { instrument = value; } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "sourcelink": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { sourceLink = ParseGenericPathToFile(value, diagnostics, baseDirectory); } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; case "embed": if (string.IsNullOrEmpty(value)) { embedAllSourceFiles = true; continue; } embeddedFiles.AddRange(ParseSeparatedFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } if (sourceLink != null) { if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SourceLinkRequiresPortablePdb); } } if (embedAllSourceFiles) { embeddedFiles.AddRange(sourceFiles); } if (embeddedFiles.Count > 0) { // Restricted to portable PDBs for now, but the IsPortable condition should be removed // and the error message adjusted accordingly when native PDB support is added. if (!emitPdb || !debugInformationFormat.IsPortable()) { AddDiagnostic(diagnostics, ErrorCode.ERR_CannotEmbedWithoutPdb); } } var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: parsedFeatures ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrument: instrument ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, SourceLink = sourceLink, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer, EmbeddedFiles = embeddedFiles.AsImmutable() }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!PortableShim.Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, out LanguageVersion version) { if (str == null) { version = LanguageVersion.Default; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "7": version = LanguageVersion.CSharp7; return true; case "default": version = LanguageVersion.Default; return true; case "latest": version = LanguageVersion.Latest; return true; default: // We are likely to introduce minor version numbers after C# 7, thus breaking the // one-to-one correspondence between the integers and the corresponding // LanguageVersion enum values. But for compatibility we continue to accept any // integral value parsed by int.TryParse for its corresponding LanguageVersion enum // value for language version C# 6 and earlier (e.g. leading zeros are allowed) int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && versionNumber <= 6 && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = LanguageVersion.Default; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_11_7_2 : EcmaTest { [Fact] [Trait("Category", "11.7.2")] public void WhiteSpaceAndLineTerminatorBetweenShiftexpressionAndOrBetweenAndAdditiveexpressionAreAllowed() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYUsesGetvalue() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.1_T1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYUsesGetvalue2() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.1_T2.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYUsesGetvalue3() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.1_T3.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYUsesDefaultValue() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.2_T1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void TonumberFirstExpressionIsCalledFirstAndThenTonumberSecondExpression() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.3_T1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.4_T1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression2() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.4_T2.js", false); } [Fact] [Trait("Category", "11.7.2")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression3() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A2.4_T3.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T1.1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY2() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T1.2.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY3() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T1.3.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY4() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T1.4.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY5() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T1.5.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY6() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY7() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.2.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY8() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.3.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY9() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.4.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY10() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.5.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY11() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.6.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY12() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.7.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY13() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.8.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYReturnsTonumberXTonumberY14() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A3_T2.9.js", false); } [Fact] [Trait("Category", "11.7.2")] public void CheckXYOperatorInDistinctPoints() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A4_T1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void CheckXYOperatorInDistinctPoints2() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A4_T2.js", false); } [Fact] [Trait("Category", "11.7.2")] public void CheckXYOperatorInDistinctPoints3() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A4_T3.js", false); } [Fact] [Trait("Category", "11.7.2")] public void CheckXYOperatorInDistinctPoints4() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A4_T4.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYUsesToint32Shiftexpression() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A5.1_T1.js", false); } [Fact] [Trait("Category", "11.7.2")] public void OperatorXYUsesTouint32Additiveexpression31() { RunTest(@"TestCases/ch11/11.7/11.7.2/S11.7.2_A5.2_T1.js", false); } } }
//----------------------------------------------------------------------- // <copyright file="AugmentedImageDatabase.cs" company="Google LLC"> // // Copyright 2018 Google LLC. 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; using GoogleARCoreInternal; using UnityEngine; #if UNITY_EDITOR using System.IO; using UnityEditor; #endif /// <summary> /// A database storing a list of images to be detected and tracked by ARCore. /// /// An image database supports up to 1000 images. Only one image database can be in use at any /// given time. /// </summary> public class AugmentedImageDatabase : ScriptableObject { private IntPtr m_ArAugmentedImageDatabase = IntPtr.Zero; [SerializeField] private List<AugmentedImageDatabaseEntry> m_Images = new List<AugmentedImageDatabaseEntry>(); [SuppressMessage("UnityRules.UnityStyleRules", "CS0169:FieldIsNeverUsedIssue", Justification = "Used in editor.")] [SerializeField] private byte[] m_RawData = null; // Fixes unused variable warning when not in editor. #pragma warning disable 414 [SerializeField] private bool m_IsRawDataDirty = true; [SerializeField] private string m_CliVersion = string.Empty; #pragma warning restore 414 /// <summary> /// Constructs a new <c>AugmentedImageDatabase</c>. /// </summary> public AugmentedImageDatabase() { IsDirty = true; } /// <summary> /// Gets the number of images in the database. /// </summary> public int Count { get { lock (m_Images) { return m_Images.Count; } } } /// <summary> /// Gets a value indicating whether the AugmentedImageDatabase is dirty and has to be reset /// in ArCore. /// </summary> internal bool IsDirty { get; private set; } /// <summary> /// Gets the native handle for an associated ArAugmentedImageDatabase. /// </summary> internal IntPtr NativeHandle { get { if (m_ArAugmentedImageDatabase == IntPtr.Zero) { var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null || InstantPreviewManager.IsProvidingPlatform) { return IntPtr.Zero; } m_ArAugmentedImageDatabase = nativeSession.AugmentedImageDatabaseApi.Create(m_RawData); } IsDirty = false; return m_ArAugmentedImageDatabase; } private set { m_ArAugmentedImageDatabase = value; } } /// <summary> /// Gets or sets the image at the specified <c>index</c>. /// /// You can only modify the database in the Unity editor. /// </summary> /// <param name="index">The zero-based index of the image entry to get or set.</param> /// <returns>The image entry at <c>index</c>.</returns> public AugmentedImageDatabaseEntry this[int index] { get { lock (m_Images) { return m_Images[index]; } } #if UNITY_EDITOR set { var oldValue = m_Images[index]; m_Images[index] = value; if (oldValue.TextureGUID != m_Images[index].TextureGUID || oldValue.Name != m_Images[index].Name || oldValue.Width != m_Images[index].Width) { m_IsRawDataDirty = true; } EditorUtility.SetDirty(this); } #endif } /// <summary> /// Adds an image to this database. /// /// This function takes time to perform non-trivial image processing (20ms - /// 30ms), and should be run on a background thread. /// </summary> /// <param name="name">The name of the image.</param> /// <param name="image">The image to be added.</param> /// <param name="width">The physical width of the image in meters, or 0 if the width is /// unknown.</param> /// <returns>The index of the added image in this database or -1 if there was an /// error.</returns> /// @deprecated Please use another 'AddImage' instead. [SuppressMemoryAllocationError(Reason = "Allocates memory for the image.")] public int AddImage(string name, Texture2D image, float width = 0) { return AddImage(name, new AugmentedImageSrc(image), width); } /// <summary> /// Adds an image to this database. /// /// This function takes time to perform non-trivial image processing (20ms - /// 30ms), and should be run on a background thread. /// </summary> /// <param name="name">The name of the image.</param> /// <param name="imageSrc">Source image to be added.</param> /// <param name="width">The physical width of the image in meters, or 0 if the width is /// unknown.</param> /// <returns>The index of the added image in this database or -1 if there was an /// error.</returns> [SuppressMemoryAllocationError(Reason = "Allocates memory for the image.")] public int AddImage(string name, AugmentedImageSrc imageSrc, float width = 0) { var nativeSession = LifecycleManager.Instance.NativeSession; if (nativeSession == null) { return -1; } int imageIndex = nativeSession.AugmentedImageDatabaseApi.AddAugmentedImageAtRuntime( NativeHandle, name, imageSrc, width); if (imageIndex != -1) { lock (m_Images) { m_Images.Add(new AugmentedImageDatabaseEntry(name, width)); IsDirty = true; } } return imageIndex; } #if UNITY_EDITOR /// <summary> /// Adds an image entry to the end of the database. /// </summary> /// <param name="entry">The image entry to add.</param> public void Add(AugmentedImageDatabaseEntry entry) { m_Images.Add(entry); m_IsRawDataDirty = true; EditorUtility.SetDirty(this); } /// <summary> /// Removes an image entry at a specified zero-based index. /// </summary> /// <param name="index">The index of the image entry to remove.</param> public void RemoveAt(int index) { m_Images.RemoveAt(index); m_IsRawDataDirty = true; EditorUtility.SetDirty(this); } /// @cond EXCLUDE_FROM_DOXYGEN /// <summary> /// Checks if the database needs to be rebuilt. /// </summary> /// <returns><c>true</c> if the database needs to be rebuilt, <c>false</c> /// otherwise.</returns> public bool IsBuildNeeded() { return m_IsRawDataDirty; } /// @endcond /// @cond EXCLUDE_FROM_DOXYGEN /// <summary> /// Rebuilds the database asset, if needed. /// </summary> /// <param name="error">An error string that will be set if the build was /// unsuccessful.</param> public void BuildIfNeeded(out string error) { error = ""; if (!m_IsRawDataDirty) { return; } string cliBinaryPath; if (!FindCliBinaryPath(out cliBinaryPath)) { return; } var tempDirectoryPath = FileUtil.GetUniqueTempPathInProject(); Directory.CreateDirectory(tempDirectoryPath); var inputImagesFile = Path.Combine(tempDirectoryPath, "inputImages"); string[] fileLines = new string[m_Images.Count]; for (int i = 0; i < m_Images.Count; i++) { var imagePath = AssetDatabase.GetAssetPath(m_Images[i].Texture); StringBuilder sb = new StringBuilder(); sb.Append(m_Images[i].Name).Append('|').Append(imagePath); if (m_Images[i].Width > 0) { sb.Append('|').Append(m_Images[i].Width); } fileLines[i] = sb.ToString(); } File.WriteAllLines(inputImagesFile, fileLines); var rawDatabasePath = Path.Combine(tempDirectoryPath, "out_database"); string output; #if !UNITY_EDITOR_WIN ShellHelper.RunCommand("chmod", "+x \"" + cliBinaryPath + "\"", out output, out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning(error); return; } #endif ShellHelper.RunCommand(cliBinaryPath, string.Format( "build-db --input_image_list_path {0} --output_db_path {1}", inputImagesFile, rawDatabasePath), out output, out error); if (!string.IsNullOrEmpty(error)) { return; } m_RawData = File.ReadAllBytes(rawDatabasePath + ".imgdb"); m_IsRawDataDirty = false; EditorUtility.SetDirty(this); // Force a save to make certain build process will get updated asset. AssetDatabase.SaveAssets(); const int BYTES_IN_KBYTE = 1024; Debug.LogFormat( "Built AugmentedImageDatabase '{0}' ({1} Images, {2} KBytes)", name, Count, m_RawData.Length/BYTES_IN_KBYTE); // TODO:: Remove this log when all errors/warnings are moved to stderr for CLI tool. Debug.Log(output); } /// @endcond /// @cond EXCLUDE_FROM_DOXYGEN /// <summary> /// Gets the image entries that require updating of the image quality score. /// </summary> /// <returns>A list of image entries that require updating of the image quality /// score.</returns> public List<AugmentedImageDatabaseEntry> GetDirtyQualityEntries() { var dirtyEntries = new List<AugmentedImageDatabaseEntry>(); string cliBinaryPath; if (!FindCliBinaryPath(out cliBinaryPath)) { return dirtyEntries; } string currentCliVersion; { string error; #if !UNITY_EDITOR_WIN string output; ShellHelper.RunCommand("chmod", "+x " + cliBinaryPath, out output, out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning(error); return dirtyEntries; } #endif ShellHelper.RunCommand(cliBinaryPath, "version", out currentCliVersion, out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning(error); return dirtyEntries; } } bool cliUpdated = m_CliVersion != currentCliVersion; // When CLI is updated, mark all entries dirty. if (cliUpdated) { for (int i = 0; i < m_Images.Count; ++i) { AugmentedImageDatabaseEntry updatedImage = m_Images[i]; updatedImage.Quality = string.Empty; m_Images[i] = updatedImage; } m_CliVersion = currentCliVersion; EditorUtility.SetDirty(this); } for (int i = 0; i < m_Images.Count; ++i) { if (!string.IsNullOrEmpty(m_Images[i].Quality)) { continue; } dirtyEntries.Add(m_Images[i]); } return dirtyEntries; } /// @endcond /// @cond EXCLUDE_FROM_DOXYGEN /// <summary> /// Finds the path to the command-line tool used to generate a database. /// </summary> /// <param name="path">The path to the command-line tool that will be set if a valid path /// was found.</param> /// <returns><c>true</c> if a valid path was found, <c>false</c> otherwise.</returns> public static bool FindCliBinaryPath(out string path) { var binaryName = ApiConstants.AugmentedImageCliBinaryName; string[] cliBinaryGuid = AssetDatabase.FindAssets(binaryName); if (cliBinaryGuid.Length == 0) { Debug.LogErrorFormat( "Could not find required tool for building AugmentedImageDatabase: {0}. " + "Was it removed from the ARCore SDK?", binaryName); path = string.Empty; return false; } // Remove the '/Assets' from the project path since it will be added in the path below. string projectPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6); path = Path.Combine(projectPath, AssetDatabase.GUIDToAssetPath(cliBinaryGuid[0])); return !string.IsNullOrEmpty(path); } /// @endcond /// <summary> /// Unity OnDestroy. /// </summary> private void OnDestroy() { if (m_ArAugmentedImageDatabase != IntPtr.Zero) { AugmentedImageDatabaseApi.Release(m_ArAugmentedImageDatabase); } } #endif } }
namespace Microsoft.Protocols.TestSuites.MS_OXCROPS { using System.Collections.Generic; using System.Text; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// This class is designed to verify the response buffer formats of Stream ROPs. /// </summary> [TestClass] public class S07_StreamROPs : TestSuiteBase { #region Class Initialization and Cleanup /// <summary> /// Class initialize. /// </summary> /// <param name="testContext">The session context handle</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Class cleanup. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test Cases /// <summary> /// This method tests the ROP buffers of RopOpenStream, RopReadStream, /// RopWriteStream, RopCommitStream and RopWriteAndCommitStream. /// </summary> [TestCategory("MSOXCROPS"), TestMethod()] public void MSOXCROPS_S07_TC01_TestRopsOpenReadWriteCommitStream() { this.CheckTransportIsSupported(); this.cropsAdapter.RpcConnect( Common.GetConfigurationPropertyValue("SutComputerName", this.Site), ConnectionType.PrivateMailboxServer, Common.GetConfigurationPropertyValue("UserEssdn", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site), Common.GetConfigurationPropertyValue("AdminUserName", this.Site), Common.GetConfigurationPropertyValue("PassWord", this.Site)); // Step 1: Preparations-Create message and then open a stream. #region Common operations for RopReadStream,RopWriteStream,RopCommitStream and RopWriteAndCommitStream // Common variable for RopWriteStream and RopWriteAndCommitStream. byte[] data = Encoding.ASCII.GetBytes(SampleStreamData + "\0"); // Log on to the private mailbox. RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call GetCreatedMessageHandle method to create a message."); // Create a message. uint messageHandle = GetCreatedMessageHandle(logonResponse.FolderIds[4], inputObjHandle); // Test RopOpenStream success response. #region Test RopOpenStream success response RopOpenStreamRequest openStreamRequest; RopOpenStreamResponse openStreamResponse; // Client defines a new property. PropertyTag tag; tag.PropertyId = TestSuiteBase.UserDefinedPropertyId; tag.PropertyType = (ushort)PropertyType.PtypString; openStreamRequest.RopId = (byte)RopId.RopOpenStream; openStreamRequest.LogonId = TestSuiteBase.LogonId; openStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; openStreamRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1; openStreamRequest.PropertyTag = tag; openStreamRequest.OpenModeFlags = (byte)StreamOpenModeFlags.Create; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopOpenStream request."); // Send the RopOpenStream request and verify success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( openStreamRequest, messageHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); openStreamResponse = (RopOpenStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, openStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); uint streamObjectHandle = responseSOHs[0][openStreamResponse.OutputHandleIndex]; #endregion // Test RopOpenStream failure response. #region Test RopOpenStream failure response openStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex1; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopOpenStream request."); // Send the RopOpenStream request and verify failure response. this.responseSOHs = cropsAdapter.ProcessSingleRop( openStreamRequest, messageHandle, ref this.response, ref this.rawData, RopResponseType.FailureResponse); openStreamResponse = (RopOpenStreamResponse)response; Site.Assert.AreNotEqual<uint>( TestSuiteBase.SuccessReturnValue, openStreamResponse.ReturnValue, "if ROP failure, the ReturnValue of its response is not 0(success)"); #endregion #endregion // Step 2: Verify RopReadStream Response when ByteCount is not equal to 0xBABE. #region Verify RopReadStream Response when ByteCount is not equal to 0xBABE. RopReadStreamRequest readStreamRequest; RopReadStreamResponse readStreamResponse; readStreamRequest.RopId = (byte)RopId.RopReadStream; readStreamRequest.LogonId = TestSuiteBase.LogonId; readStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; // Set ByteCount to a value other than 0xBABE, then verify the response. readStreamRequest.ByteCount = TestSuiteBase.ByteCountForRopReadStream; readStreamRequest.MaximumByteCount = TestSuiteBase.MaximumByteCount; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopReadStream request."); // Send the RopReadStream request and verify RopReadStream Response when ByteCount is not equal to 0xBABE. this.responseSOHs = cropsAdapter.ProcessSingleRop( readStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); readStreamResponse = (RopReadStreamResponse)response; if (readStreamRequest.ByteCount != TestSuiteBase.ByteCount) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R3227,the ByteCount:{0},the DataSize:{1}", readStreamRequest.ByteCount, readStreamResponse.DataSize); // Verify MS-OXCROPS requirement: MS-OXCROPS_R3227 // The maximum size is specified in the request buffer ByteCount field, must greater or equal than response DataSize field. bool isVerifyR3227 = readStreamRequest.ByteCount >= readStreamResponse.DataSize; Site.CaptureRequirementIfIsTrue( isVerifyR3227, 3227, @"[In RopReadStream ROP Response Buffer,DataSize (2 bytes),The maximum size is specified in the request buffer by one of the following:]The ByteCount field, when the value of the ByteCount value is not equal to 0xBABE."); } #endregion // Step 3: Verify RopReadStream Response when ByteCount is equal to 0xBABE. #region Verify RopReadStream Response when ByteCount is equal to 0xBABE. // Set ByteCount to 0xBABE, then verify the response. readStreamRequest.ByteCount = TestSuiteBase.ByteCount; this.responseSOHs = cropsAdapter.ProcessSingleRop( readStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); readStreamResponse = (RopReadStreamResponse)response; if (readStreamRequest.ByteCount == TestSuiteBase.ByteCount) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R3228,the MaximumByteCount:{0},the DataSize:{1}", readStreamRequest.MaximumByteCount, readStreamResponse.DataSize); // Verify MS-OXCROPS requirement: MS-OXCROPS_R3228 // The maximum size is specified in the request buffer MaximumByteCount field, must greater or equal than response DataSize field. bool isVerifyR3228 = readStreamRequest.MaximumByteCount >= readStreamResponse.DataSize; Site.CaptureRequirementIfIsTrue( isVerifyR3228, 3228, @"[In RopReadStream ROP Response Buffer,DataSize (2 bytes),The maximum size is specified in the request buffer by one of the following:]The MaximumByteCount field, when the value of the ByteCount field is equal to 0xBABE."); } #endregion // Step 4: Verify RopReadStream Response when MaximumByteCount is larger than 0x80000000. #region Verify RopReadStream Response when MaximumByteCount is larger than 0x80000000 // Set MaximumByteCount to be larger than 0x80000000. readStreamRequest.MaximumByteCount = TestSuiteBase.ExceedMaxCount; this.responseSOHs = cropsAdapter.ProcessSingleRop( readStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.RPCError); #endregion // Step 5: Send the RopWriteStream request and verify the success response. #region RopWriteStream Response RopWriteStreamRequest writeStreamRequest; RopWriteStreamResponse writeStreamResponse; writeStreamRequest.RopId = (byte)RopId.RopWriteStream; writeStreamRequest.LogonId = TestSuiteBase.LogonId; writeStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; writeStreamRequest.DataSize = (ushort)data.Length; writeStreamRequest.Data = data; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopWriteStream request."); // Send the RopWriteStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( writeStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); writeStreamResponse = (RopWriteStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, writeStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 6: Send the RopCommitStream request and verify the success response. #region RopCommitStream Response RopCommitStreamRequest commitStreamRequest; RopCommitStreamResponse commitStreamResponse; commitStreamRequest.RopId = (byte)RopId.RopCommitStream; commitStreamRequest.LogonId = TestSuiteBase.LogonId; commitStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5: Begin to send the RopCommitStream request."); // Send the RopCommitStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( commitStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); commitStreamResponse = (RopCommitStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, commitStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 7: Send the RopWriteAndCommitStream request and verify the success response. #region RopWriteAndCommitStream response RopWriteAndCommitStreamRequest writeAndCommitStreamRequest; writeAndCommitStreamRequest.RopId = (byte)RopId.RopWriteAndCommitStream; writeAndCommitStreamRequest.LogonId = TestSuiteBase.LogonId; writeAndCommitStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; writeAndCommitStreamRequest.DataSize = (ushort)data.Length; writeAndCommitStreamRequest.Data = data; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 6: Begin to send the RopWriteAndCommitStream request."); // Send the RopWriteAndCommitStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( writeAndCommitStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); // Refer to MS-OXCPRPT: Exchange 2003 and Exchange 2007 implement the RopWriteAndCommitStream ROP. if (Common.IsRequirementEnabled(752001, this.Site)) { // Because the response of RopWriteAndCommitStream is the same to RopWriteStream. RopWriteStreamResponse writeAndCommitStreamResponse; writeAndCommitStreamResponse = (RopWriteStreamResponse)response; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R752001"); // Verify MS-OXCROPS requirement: MS-OXCROPS_R752001 Site.CaptureRequirementIfAreEqual<uint>( TestSuiteBase.SuccessReturnValue, writeAndCommitStreamResponse.ReturnValue, 752001, @"[In Appendix A: Product Behavior] Implementation does implement the RopWriteAndCommitStream ROP. (Exchange 2007 follows this behavior.)"); Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, writeAndCommitStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); } #endregion } /// <summary> /// This method tests the ROP buffers of RopGetStreamSize, RopSetStreamSize and RopSeekStream. /// </summary> [TestCategory("MSOXCROPS"), TestMethod()] public void MSOXCROPS_S07_TC02_TestRopsGetSetStreamSizeAndSeekStream() { this.CheckTransportIsSupported(); this.cropsAdapter.RpcConnect( Common.GetConfigurationPropertyValue("SutComputerName", this.Site), ConnectionType.PrivateMailboxServer, Common.GetConfigurationPropertyValue("UserEssdn", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site), Common.GetConfigurationPropertyValue("AdminUserName", this.Site), Common.GetConfigurationPropertyValue("PassWord", this.Site)); // Step 1: Preparations-Create message and get its handle, open a stream and get its handle. #region Common operations for RopGetStreamSize,RopSetStreamSize and RopSeekStream // Log on to a private mailbox. RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call GetCreatedMessageHandle method to create a message and get its handle."); // Call GetCreatedMessageHandle method to create a message and get its handle. uint messageHandle = GetCreatedMessageHandle(logonResponse.FolderIds[4], inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call GetOpenedStreamHandle method to open stream and get its handle."); // Call GetOpenedStreamHandle method to open stream and get its handle. uint streamObjectHandle = this.GetOpenedStreamHandle(messageHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call WriteStream method to write stream."); // Call WriteStream method to write stream. this.WriteStream(streamObjectHandle); #endregion // Step 2: Send the RopGetStreamSize request and verify the success response. #region RopGetStreamSize success response RopGetStreamSizeRequest getStreamSizeRequest; RopGetStreamSizeResponse getStreamSizeResponse; getStreamSizeRequest.RopId = (byte)RopId.RopGetStreamSize; getStreamSizeRequest.LogonId = TestSuiteBase.LogonId; getStreamSizeRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopGetStreamSize request."); // Send the RopGetStreamSize request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( getStreamSizeRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); getStreamSizeResponse = (RopGetStreamSizeResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, getStreamSizeResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 3: Send the RopGetStreamSize request and verify the failure response. #region RopGetStreamSize failure response getStreamSizeRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex1; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopGetStreamSize request."); this.responseSOHs = cropsAdapter.ProcessSingleRop( getStreamSizeRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.FailureResponse); getStreamSizeResponse = (RopGetStreamSizeResponse)response; Site.Assert.AreNotEqual<uint>( TestSuiteBase.SuccessReturnValue, getStreamSizeResponse.ReturnValue, "if ROP failure, the ReturnValue of its response is not 0(success)"); #endregion // Step 4: Send the RopSetStreamSize request and verify the success response. #region RopSetStreamSize Response RopSetStreamSizeRequest setStreamSizeRequest; RopSetStreamSizeResponse setStreamSizeResponse; setStreamSizeRequest.RopId = (byte)RopId.RopSetStreamSize; setStreamSizeRequest.LogonId = TestSuiteBase.LogonId; setStreamSizeRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; // Change the original stream size to 0x00000000000000FF. setStreamSizeRequest.StreamSize = TestSuiteBase.StreamSize; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopSetStreamSize request."); // Send the RopSetStreamSize request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( setStreamSizeRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); setStreamSizeResponse = (RopSetStreamSizeResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, setStreamSizeResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 5: Send the RopSeekStream request and verify the success response. #region RopSeekStream success response RopSeekStreamRequest seekStreamRequest; RopSeekStreamResponse seekStreamResponse; seekStreamRequest.RopId = (byte)RopId.RopSeekStream; seekStreamRequest.LogonId = TestSuiteBase.LogonId; seekStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; seekStreamRequest.Origin = (byte)Origin.Beginning; // Defined by tester, less than the stream size. seekStreamRequest.Offset = TestSuiteBase.Offset; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5: Begin to send the RopSeekStream request."); // Send the RopSeekStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( seekStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); seekStreamResponse = (RopSeekStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, seekStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 6: Send the RopSeekStream request and verify the failure response. #region RopSeekStream failure response seekStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex1; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 6: Begin to send the RopSeekStream request."); this.responseSOHs = cropsAdapter.ProcessSingleRop( seekStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.FailureResponse); seekStreamResponse = (RopSeekStreamResponse)response; Site.Assert.AreNotEqual<uint>( TestSuiteBase.SuccessReturnValue, seekStreamResponse.ReturnValue, "if ROP failure, the ReturnValue of its response is not 0(success)"); #endregion } /// <summary> /// This method tests the ROP buffers of RopLockRegionStream and RopUnlockRegionStream. /// </summary> [TestCategory("MSOXCROPS"), TestMethod()] public void MSOXCROPS_S07_TC03_TestRopsLockAndUnlockRegionStream() { this.CheckTransportIsSupported(); this.cropsAdapter.RpcConnect( Common.GetConfigurationPropertyValue("SutComputerName", this.Site), ConnectionType.PrivateMailboxServer, Common.GetConfigurationPropertyValue("UserEssdn", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site), Common.GetConfigurationPropertyValue("AdminUserName", this.Site), Common.GetConfigurationPropertyValue("PassWord", this.Site)); // Step 1: Preparations-Create message and get its handle, open stream and get its handle. #region Common operations for RopLockRegionStream and RopUnlockRegionStream // Log on to a private mailbox. RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call GetCreatedMessageHandle method to create message and get its handle."); // Call GetCreatedMessageHandle method to create message and get its handle. uint messageHandle = GetCreatedMessageHandle(logonResponse.FolderIds[4], inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call GetOpenedStreamHandle method to open stream and get its handle."); // Call GetOpenedStreamHandle method to open stream and get its handle. uint streamObjectHandle = this.GetOpenedStreamHandle(messageHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call WriteStream method to write stream."); // Call WriteStream method to write stream. this.WriteStream(streamObjectHandle); #endregion // Refer to MS-OXCPRPT: Exchange 2003 and Exchange 2007 implement the RopLockRegionStream ROP. if (Common.IsRequirementEnabled(750001, this.Site)) { // Step 2: Send the RopLockRegionStream request and verify the success response. #region RopLockRegionStream Response RopLockRegionStreamRequest lockRegionStreamRequest = new RopLockRegionStreamRequest(); RopLockRegionStreamResponse lockRegionStreamResponse; lockRegionStreamRequest.RopId = (byte)RopId.RopLockRegionStream; lockRegionStreamRequest.LogonId = TestSuiteBase.LogonId; lockRegionStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; lockRegionStreamRequest.RegionOffset = TestSuiteBase.RegionOffset; // Defined by tester, less than the stream size. lockRegionStreamRequest.RegionSize = TestSuiteBase.RegionSize; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 2: Begin to send the RopLockRegionStream request."); // Send the RopLockRegionStream request and verify the failure response. this.responseSOHs = cropsAdapter.ProcessSingleRop( lockRegionStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); lockRegionStreamResponse = (RopLockRegionStreamResponse)response; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R750001"); // Verify MS-OXCROPS requirement: MS-OXCROPS_R750001 Site.CaptureRequirementIfAreEqual<uint>( TestSuiteBase.SuccessReturnValue, lockRegionStreamResponse.ReturnValue, 750001, @"[In Appendix A: Product Behavior] Implementation does implement the RopLockRegionStream ROP. (Exchange 2007 follows this behavior.)"); Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, lockRegionStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion } // Refer to MS-OXCPRPT: Exchange 2003 and Exchange 2007 implement the RopUnlockRegionStream ROP. if (Common.IsRequirementEnabled(751001, this.Site)) { // Step 3: Send the RopUnlockRegionStream request and verify the success response. #region RopUnlockRegionStream response RopUnlockRegionStreamRequest unlockRegionStreamRequest = new RopUnlockRegionStreamRequest(); RopUnlockRegionStreamResponse unlockRegionStreamResponse; unlockRegionStreamRequest.RopId = (byte)RopId.RopUnlockRegionStream; unlockRegionStreamRequest.LogonId = TestSuiteBase.LogonId; unlockRegionStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; // Beginning of the stream. unlockRegionStreamRequest.RegionOffset = TestSuiteBase.RegionOffset; // Defined by tester, less than the stream size. unlockRegionStreamRequest.RegionSize = TestSuiteBase.RegionSize; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 3: Begin to send the RopUnlockRegionStream request."); // Step 4: Send the RopUnlockRegionStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( unlockRegionStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); unlockRegionStreamResponse = (RopUnlockRegionStreamResponse)response; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R751001"); // Verify MS-OXCROPS requirement: MS-OXCROPS_R751001 Site.CaptureRequirementIfAreEqual<uint>( TestSuiteBase.SuccessReturnValue, unlockRegionStreamResponse.ReturnValue, 751001, @"[In Appendix A: Product Behavior] Implementation does implement the RopUnlockRegionStream ROP. (Exchange 2007 follows this behavior.)"); Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, unlockRegionStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion } } /// <summary> /// This method tests the ROP buffers of RopCloneStream and RopCopyToStream. /// </summary> [TestCategory("MSOXCROPS"), TestMethod()] public void MSOXCROPS_S07_TC04_TestRopsCloneAndCopyToStream() { this.CheckTransportIsSupported(); this.cropsAdapter.RpcConnect( Common.GetConfigurationPropertyValue("SutComputerName", this.Site), ConnectionType.PrivateMailboxServer, Common.GetConfigurationPropertyValue("UserEssdn", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site), Common.GetConfigurationPropertyValue("AdminUserName", this.Site), Common.GetConfigurationPropertyValue("PassWord", this.Site)); // Step 5: Preparations for RopCloneStream and RopCopyToStream. #region Common operations for RopCloneStream and RopCopyToStream // Log on to a private mailbox. RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call GetCreatedMessageHandle method to create message and get its handle."); // Call GetCreatedMessageHandle method to create message and get its handle. uint sourceMessageHandle = GetCreatedMessageHandle(logonResponse.FolderIds[4], inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call GetOpenedStreamHandle method to open stream and get its handle."); // Call GetOpenedStreamHandle method to open stream and get its handle. uint sourceStreamObjectHandle = this.GetOpenedStreamHandle(sourceMessageHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call WriteStream method to write stream."); // Call WriteStream method to write stream. this.WriteStream(sourceStreamObjectHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call CommitStream method to commit source stream."); // Call CommitStream method to commit source stream. this.CommitStream(sourceStreamObjectHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call SaveMessage method to save message."); // Call SaveMessage method to save message. this.SaveMessage(sourceMessageHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call GetOpenedStreamHandle method to open the source stream again."); // Open the source stream again. sourceStreamObjectHandle = this.GetOpenedStreamHandle(sourceMessageHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call GetCreatedMessageHandle method to create a second message."); // Create a second message. uint destinationMessageHandle = GetCreatedMessageHandle(logonResponse.FolderIds[4], inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5:Call GetOpenedStreamHandle method to open stream."); // Open stream, used as destination stream. uint destinationStreamObjectHandle = this.GetOpenedStreamHandle(destinationMessageHandle); // Copy stream, from source to destination. List<uint> handleList = new List<uint> { sourceStreamObjectHandle, destinationStreamObjectHandle }; #endregion // Refer to MS-OXCPRPT: Exchange 2003 and Exchange 2007 implement the RopCloneStream ROP. if (Common.IsRequirementEnabled(753001, this.Site)) { // Step 6: Send the RopCloneStream request and verify the success response. #region RopCloneStream response RopCloneStreamRequest cloneStreamRequest; RopCloneStreamResponse cloneStreamResponse; cloneStreamRequest.RopId = (byte)RopId.RopCloneStream; cloneStreamRequest.LogonId = TestSuiteBase.LogonId; cloneStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; cloneStreamRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 6: Begin to send the RopCloneStream request."); // Send the RopCloneStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRopWithMutipleServerObjects( cloneStreamRequest, handleList, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); cloneStreamResponse = (RopCloneStreamResponse)response; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R753001"); // Verify MS-OXCROPS requirement: MS-OXCROPS_R753001 Site.CaptureRequirementIfAreEqual<uint>( TestSuiteBase.SuccessReturnValue, cloneStreamResponse.ReturnValue, 753001, @"[In Appendix A: Product Behavior] Implementation does implement the RopCloneStream ROP. (Exchange 2007 follows this behavior.)"); Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, cloneStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion } // Refer to MS-OXCPRPT: The initial release version of Exchange 2010 does not implement the RopCopyToStream ROP. if (Common.IsRequirementEnabled(8670901, this.Site)) { // Step 7: Send the RopCopyToStream request and verify the success response. #region RopCopyToStream success response RopCopyToStreamRequest copyToStreamRequest; RopCopyToStreamResponse copyToStreamResponse; copyToStreamRequest.RopId = (byte)RopId.RopCopyToStream; copyToStreamRequest.LogonId = TestSuiteBase.LogonId; copyToStreamRequest.SourceHandleIndex = TestSuiteBase.SourceHandleIndex0; copyToStreamRequest.DestHandleIndex = TestSuiteBase.DestHandleIndex; // Set ByteCount to a value less than the length of original property. copyToStreamRequest.ByteCount = TestSuiteBase.ByteCountForRopCopyToStream; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 7: Begin to send the RopCopyToStream request."); // Send the RopCopyToStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRopWithMutipleServerObjects( copyToStreamRequest, handleList, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); copyToStreamResponse = (RopCopyToStreamResponse)response; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-OXCROPS_R8670901"); // Verify MS-OXCROPS requirement: MS-OXCROPS_R8670901 Site.CaptureRequirementIfAreEqual<uint>( TestSuiteBase.SuccessReturnValue, copyToStreamResponse.ReturnValue, 8670901, @"[In Appendix A: Product Behavior] Implementation does implement the RopCopyToStream ROP. (Exchange 2007 and Exchange 2013 follows this behavior.)"); Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, copyToStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 8: Send the RopCopyToStream request and verify the null destination failure response. #region RopCopyToStream null destination failure response handleList.RemoveAt(1); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 8: Begin to send the RopCopyToStream request."); this.responseSOHs = cropsAdapter.ProcessSingleRopWithMutipleServerObjects( copyToStreamRequest, handleList, ref this.response, ref this.rawData, RopResponseType.NullDestinationFailureResponse); copyToStreamResponse = (RopCopyToStreamResponse)response; Site.Assert.AreEqual<uint>( MS_OXCROPSAdapter.ReturnValueForRopMoveFolderResponseAndMoveCopyMessage, copyToStreamResponse.ReturnValue, "if ROP null destination failure, the ReturnValue of its response is 0x00000503"); #endregion } } /// <summary> /// This method tests the ROP buffers of RopWriteStreamExtended. /// </summary> [TestCategory("MSOXCROPS"), TestMethod()] public void MSOXCROPS_S07_TC05_TestRopWriteStreamExtended() { this.CheckTransportIsSupported(); if (Common.IsRequirementEnabled(3256018, this.Site)) { this.cropsAdapter.RpcConnect( Common.GetConfigurationPropertyValue("SutComputerName", this.Site), ConnectionType.PrivateMailboxServer, Common.GetConfigurationPropertyValue("UserEssdn", this.Site), Common.GetConfigurationPropertyValue("Domain", this.Site), Common.GetConfigurationPropertyValue("AdminUserName", this.Site), Common.GetConfigurationPropertyValue("PassWord", this.Site)); // Step 1: Preparations-Create message and then open a stream. #region Common operations for RopReadStream,RopWriteStreamExtended,RopCommitStream and RopWriteAndCommitStream // Common variable for RopWriteStream and RopWriteAndCommitStream. byte[] data = Encoding.ASCII.GetBytes(SampleStreamData + "\0"); // Log on to the private mailbox. RopLogonResponse logonResponse = Logon(LogonType.Mailbox, this.userDN, out inputObjHandle); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1:Call GetCreatedMessageHandle method to create a message."); // Create a message. uint messageHandle = GetCreatedMessageHandle(logonResponse.FolderIds[4], inputObjHandle); // Test RopOpenStream success response. #region Test RopOpenStream success response RopOpenStreamRequest openStreamRequest; RopOpenStreamResponse openStreamResponse; // Client defines a new property. PropertyTag tag; tag.PropertyId = TestSuiteBase.UserDefinedPropertyId; tag.PropertyType = (ushort)PropertyType.PtypString; openStreamRequest.RopId = (byte)RopId.RopOpenStream; openStreamRequest.LogonId = TestSuiteBase.LogonId; openStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; openStreamRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1; openStreamRequest.PropertyTag = tag; openStreamRequest.OpenModeFlags = (byte)StreamOpenModeFlags.Create; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 1: Begin to send the RopOpenStream request."); // Send the RopOpenStream request and verify success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( openStreamRequest, messageHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); openStreamResponse = (RopOpenStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, openStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); uint streamObjectHandle = responseSOHs[0][openStreamResponse.OutputHandleIndex]; #endregion #endregion // Step 2: Send the RopWriteStreamExtended request and verify the success response. #region RopWriteStreamExtended Response RopWriteStreamExtendedRequest writeStreamExtendedRequest; RopWriteStreamExtendedResponse writeStreamExtendedResponse; writeStreamExtendedRequest.RopId = (byte)RopId.RopWriteStreamExtended; writeStreamExtendedRequest.LogonId = TestSuiteBase.LogonId; writeStreamExtendedRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; writeStreamExtendedRequest.DataSize = (ushort)data.Length; writeStreamExtendedRequest.Data = data; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 4: Begin to send the RopWriteStreamExtended request."); // Send the RopWriteStreamExtended request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( writeStreamExtendedRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); writeStreamExtendedResponse = (RopWriteStreamExtendedResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, writeStreamExtendedResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion // Step 3: Send the RopCommitStream request and verify the success response. #region RopCommitStream Response RopCommitStreamRequest commitStreamRequest; RopCommitStreamResponse commitStreamResponse; commitStreamRequest.RopId = (byte)RopId.RopCommitStream; commitStreamRequest.LogonId = TestSuiteBase.LogonId; commitStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Step 5: Begin to send the RopCommitStream request."); // Send the RopCommitStream request and verify the success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( commitStreamRequest, streamObjectHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); commitStreamResponse = (RopCommitStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, commitStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); #endregion } else { Site.Assert.Inconclusive("Exchange Server 2010 does not support RopWriteStreamExtended ROP."); } } #endregion #region Common methods /// <summary> /// Get Opened Stream Handle. /// </summary> /// <param name="messageHandle">The message handle</param> /// <returns>Return the opened stream handle</returns> private uint GetOpenedStreamHandle(uint messageHandle) { RopOpenStreamRequest openStreamRequest; RopOpenStreamResponse openStreamResponse; PropertyTag tag; tag.PropertyId = this.propertyDictionary[PropertyNames.UserSpecified].PropertyId; tag.PropertyType = (ushort)PropertyType.PtypString; openStreamRequest.RopId = (byte)RopId.RopOpenStream; openStreamRequest.LogonId = TestSuiteBase.LogonId; openStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; openStreamRequest.OutputHandleIndex = TestSuiteBase.OutputHandleIndex1; openStreamRequest.PropertyTag = tag; openStreamRequest.OpenModeFlags = (byte)StreamOpenModeFlags.Create; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Begin to send the RopOpenStream request in GetOpenedStreamHandle method."); // Send the RopOpenStream request and verify success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( openStreamRequest, messageHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); openStreamResponse = (RopOpenStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, openStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); uint streamObjectHandle = responseSOHs[0][openStreamResponse.OutputHandleIndex]; return streamObjectHandle; } /// <summary> /// Write Stream. /// </summary> /// <param name="streamHandle">The opened stream handle</param> private void WriteStream(uint streamHandle) { RopWriteStreamRequest writeStreamRequest; RopWriteStreamResponse writeStreamResponse; byte[] data = Encoding.ASCII.GetBytes(SampleStreamData + "\0"); writeStreamRequest.RopId = (byte)RopId.RopWriteStream; writeStreamRequest.LogonId = TestSuiteBase.LogonId; writeStreamRequest.InputHandleIndex = TestSuiteBase.InputHandleIndex0; writeStreamRequest.DataSize = (ushort)data.Length; writeStreamRequest.Data = data; // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Begin to send the RopWriteStream request in WriteStream method."); // Send the RopWriteStream request and verify success response. this.responseSOHs = cropsAdapter.ProcessSingleRop( writeStreamRequest, streamHandle, ref this.response, ref this.rawData, RopResponseType.SuccessResponse); writeStreamResponse = (RopWriteStreamResponse)response; Site.Assert.AreEqual<uint>( TestSuiteBase.SuccessReturnValue, writeStreamResponse.ReturnValue, "if ROP succeeds, the ReturnValue of its response is 0(success)"); } #endregion } }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Reflection; using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.DescriptorProtos; namespace Google.ProtocolBuffers.Descriptors { /// <summary> /// Descriptor for a field or extension within a message in a .proto file. /// </summary> public sealed class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions>, IComparable<FieldDescriptor>, IFieldDescriptorLite { private readonly MessageDescriptor extensionScope; private EnumDescriptor enumType; private MessageDescriptor messageType; private MessageDescriptor containingType; private object defaultValue; private FieldType fieldType; private MappedType mappedType; private CSharpFieldOptions csharpFieldOptions; private readonly object optionsLock = new object(); internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, bool isExtension) : base(proto, file, ComputeFullName(file, parent, proto.Name), index) { if (proto.HasType) { fieldType = GetFieldTypeFromProtoType(proto.Type); mappedType = FieldTypeToMappedTypeMap[fieldType]; } if (FieldNumber <= 0) { throw new DescriptorValidationException(this, "Field numbers must be positive integers."); } if (isExtension) { if (!proto.HasExtendee) { throw new DescriptorValidationException(this, "FieldDescriptorProto.Extendee not set for extension field."); } containingType = null; // Will be filled in when cross-linking if (parent != null) { extensionScope = parent; } else { extensionScope = null; } } else { if (proto.HasExtendee) { throw new DescriptorValidationException(this, "FieldDescriptorProto.Extendee set for non-extension field."); } containingType = parent; extensionScope = null; } file.DescriptorPool.AddSymbol(this); } private CSharpFieldOptions BuildOrFakeCSharpOptions() { // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues if (File.Proto.Name == "google/protobuf/csharp_options.proto") { if (Name == "csharp_field_options") { return new CSharpFieldOptions.Builder {PropertyName = "CSharpFieldOptions"}.Build(); } if (Name == "csharp_file_options") { return new CSharpFieldOptions.Builder {PropertyName = "CSharpFileOptions"}.Build(); } } CSharpFieldOptions.Builder builder = CSharpFieldOptions.CreateBuilder(); if (Proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFieldOptions)) { builder.MergeFrom(Proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFieldOptions)); } if (!builder.HasPropertyName) { string fieldName = FieldType == FieldType.Group ? MessageType.Name : Name; string propertyName = NameHelpers.UnderscoresToPascalCase(fieldName); if (propertyName == ContainingType.Name) { propertyName += "_"; } builder.PropertyName = propertyName; } return builder.Build(); } /// <summary> /// Maps a field type as included in the .proto file to a FieldType. /// </summary> private static FieldType GetFieldTypeFromProtoType(FieldDescriptorProto.Types.Type type) { switch (type) { case FieldDescriptorProto.Types.Type.TYPE_DOUBLE: return FieldType.Double; case FieldDescriptorProto.Types.Type.TYPE_FLOAT: return FieldType.Float; case FieldDescriptorProto.Types.Type.TYPE_INT64: return FieldType.Int64; case FieldDescriptorProto.Types.Type.TYPE_UINT64: return FieldType.UInt64; case FieldDescriptorProto.Types.Type.TYPE_INT32: return FieldType.Int32; case FieldDescriptorProto.Types.Type.TYPE_FIXED64: return FieldType.Fixed64; case FieldDescriptorProto.Types.Type.TYPE_FIXED32: return FieldType.Fixed32; case FieldDescriptorProto.Types.Type.TYPE_BOOL: return FieldType.Bool; case FieldDescriptorProto.Types.Type.TYPE_STRING: return FieldType.String; case FieldDescriptorProto.Types.Type.TYPE_GROUP: return FieldType.Group; case FieldDescriptorProto.Types.Type.TYPE_MESSAGE: return FieldType.Message; case FieldDescriptorProto.Types.Type.TYPE_BYTES: return FieldType.Bytes; case FieldDescriptorProto.Types.Type.TYPE_UINT32: return FieldType.UInt32; case FieldDescriptorProto.Types.Type.TYPE_ENUM: return FieldType.Enum; case FieldDescriptorProto.Types.Type.TYPE_SFIXED32: return FieldType.SFixed32; case FieldDescriptorProto.Types.Type.TYPE_SFIXED64: return FieldType.SFixed64; case FieldDescriptorProto.Types.Type.TYPE_SINT32: return FieldType.SInt32; case FieldDescriptorProto.Types.Type.TYPE_SINT64: return FieldType.SInt64; default: throw new ArgumentException("Invalid type specified"); } } /// <summary> /// Returns the default value for a mapped type. /// </summary> private static object GetDefaultValueForMappedType(MappedType type) { switch (type) { case MappedType.Int32: return 0; case MappedType.Int64: return (long) 0; case MappedType.UInt32: return (uint) 0; case MappedType.UInt64: return (ulong) 0; case MappedType.Single: return (float) 0; case MappedType.Double: return (double) 0; case MappedType.Boolean: return false; case MappedType.String: return ""; case MappedType.ByteString: return ByteString.Empty; case MappedType.Message: return null; case MappedType.Enum: return null; default: throw new ArgumentException("Invalid type specified"); } } public bool IsRequired { get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_REQUIRED; } } public bool IsOptional { get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_OPTIONAL; } } public bool IsRepeated { get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_REPEATED; } } public bool IsPacked { get { return Proto.Options.Packed; } } /// <valule> /// Indicates whether or not the field had an explicitly-defined default value. /// </value> public bool HasDefaultValue { get { return Proto.HasDefaultValue; } } /// <value> /// The field's default value. Valid for all types except messages /// and groups. For all other types, the object returned is of the /// same class that would be returned by IMessage[this]. /// For repeated fields this will always be an empty immutable list compatible with IList[object]. /// For message fields it will always be null. For singular values, it will depend on the descriptor. /// </value> public object DefaultValue { get { if (MappedType == MappedType.Message) { throw new InvalidOperationException( "FieldDescriptor.DefaultValue called on an embedded message field."); } return defaultValue; } } /// <value> /// Indicates whether or not this field is an extension. /// </value> public bool IsExtension { get { return Proto.HasExtendee; } } /* * Get the field's containing type. For extensions, this is the type being * extended, not the location where the extension was defined. See * {@link #getExtensionScope()}. */ /// <summary> /// Get the field's containing type. For extensions, this is the type being /// extended, not the location where the extension was defined. See /// <see cref="ExtensionScope" />. /// </summary> public MessageDescriptor ContainingType { get { return containingType; } } /// <summary> /// Returns the C#-specific options for this field descriptor. This will always be /// completely filled in. /// </summary> public CSharpFieldOptions CSharpOptions { get { lock (optionsLock) { if (csharpFieldOptions == null) { csharpFieldOptions = BuildOrFakeCSharpOptions(); } } return csharpFieldOptions; } } /// <summary> /// For extensions defined nested within message types, gets /// the outer type. Not valid for non-extension fields. /// </summary> /// <example> /// <code> /// message Foo { /// extensions 1000 to max; /// } /// extend Foo { /// optional int32 baz = 1234; /// } /// message Bar { /// extend Foo { /// optional int32 qux = 4321; /// } /// } /// </code> /// The containing type for both <c>baz</c> and <c>qux</c> is <c>Foo</c>. /// However, the extension scope for <c>baz</c> is <c>null</c> while /// the extension scope for <c>qux</c> is <c>Bar</c>. /// </example> public MessageDescriptor ExtensionScope { get { if (!IsExtension) { throw new InvalidOperationException("This field is not an extension."); } return extensionScope; } } public MappedType MappedType { get { return mappedType; } } public FieldType FieldType { get { return fieldType; } } public bool IsCLSCompliant { get { return mappedType != MappedType.UInt32 && mappedType != MappedType.UInt64 && !NameHelpers.UnderscoresToPascalCase(Name).StartsWith("_"); } } public int FieldNumber { get { return Proto.Number; } } /// <summary> /// Compares this descriptor with another one, ordering in "canonical" order /// which simply means ascending order by field number. <paramref name="other"/> /// must be a field of the same type, i.e. the <see cref="ContainingType"/> of /// both fields must be the same. /// </summary> public int CompareTo(FieldDescriptor other) { if (other.containingType != containingType) { throw new ArgumentException("FieldDescriptors can only be compared to other FieldDescriptors " + "for fields of the same message type."); } return FieldNumber - other.FieldNumber; } /// <summary> /// Compares this descriptor with another one, ordering in "canonical" order /// which simply means ascending order by field number. <paramref name="other"/> /// must be a field of the same type, i.e. the <see cref="ContainingType"/> of /// both fields must be the same. /// </summary> public int CompareTo(IFieldDescriptorLite other) { return FieldNumber - other.FieldNumber; } IEnumLiteMap IFieldDescriptorLite.EnumType { get { return EnumType; } } bool IFieldDescriptorLite.MessageSetWireFormat { get { return ContainingType.Options.MessageSetWireFormat; } } /// <summary> /// For enum fields, returns the field's type. /// </summary> public EnumDescriptor EnumType { get { if (MappedType != MappedType.Enum) { throw new InvalidOperationException("EnumType is only valid for enum fields."); } return enumType; } } /// <summary> /// For embedded message and group fields, returns the field's type. /// </summary> public MessageDescriptor MessageType { get { if (MappedType != MappedType.Message) { throw new InvalidOperationException("MessageType is only valid for enum fields."); } return messageType; } } /// <summary> /// Immutable mapping from field type to mapped type. Built using the attributes on /// FieldType values. /// </summary> public static readonly IDictionary<FieldType, MappedType> FieldTypeToMappedTypeMap = MapFieldTypes(); private static IDictionary<FieldType, MappedType> MapFieldTypes() { var map = new Dictionary<FieldType, MappedType>(); foreach (FieldInfo field in typeof(FieldType).GetFields(BindingFlags.Static | BindingFlags.Public)) { FieldType fieldType = (FieldType) field.GetValue(null); FieldMappingAttribute mapping = (FieldMappingAttribute) field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0]; map[fieldType] = mapping.MappedType; } return Dictionaries.AsReadOnly(map); } /// <summary> /// Look up and cross-link all field types etc. /// </summary> internal void CrossLink() { if (Proto.HasExtendee) { IDescriptor extendee = File.DescriptorPool.LookupSymbol(Proto.Extendee, this); if (!(extendee is MessageDescriptor)) { throw new DescriptorValidationException(this, "\"" + Proto.Extendee + "\" is not a message type."); } containingType = (MessageDescriptor) extendee; if (!containingType.IsExtensionNumber(FieldNumber)) { throw new DescriptorValidationException(this, "\"" + containingType.FullName + "\" does not declare " + FieldNumber + " as an extension number."); } } if (Proto.HasTypeName) { IDescriptor typeDescriptor = File.DescriptorPool.LookupSymbol(Proto.TypeName, this); if (!Proto.HasType) { // Choose field type based on symbol. if (typeDescriptor is MessageDescriptor) { fieldType = FieldType.Message; mappedType = MappedType.Message; } else if (typeDescriptor is EnumDescriptor) { fieldType = FieldType.Enum; mappedType = MappedType.Enum; } else { throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a type."); } } if (MappedType == MappedType.Message) { if (!(typeDescriptor is MessageDescriptor)) { throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a message type."); } messageType = (MessageDescriptor) typeDescriptor; if (Proto.HasDefaultValue) { throw new DescriptorValidationException(this, "Messages can't have default values."); } } else if (MappedType == Descriptors.MappedType.Enum) { if (!(typeDescriptor is EnumDescriptor)) { throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not an enum type."); } enumType = (EnumDescriptor) typeDescriptor; } else { throw new DescriptorValidationException(this, "Field with primitive type has type_name."); } } else { if (MappedType == MappedType.Message || MappedType == MappedType.Enum) { throw new DescriptorValidationException(this, "Field with message or enum type missing type_name."); } } // We don't attempt to parse the default value until here because for // enums we need the enum type's descriptor. if (Proto.HasDefaultValue) { if (IsRepeated) { throw new DescriptorValidationException(this, "Repeated fields cannot have default values."); } try { switch (FieldType) { case FieldType.Int32: case FieldType.SInt32: case FieldType.SFixed32: defaultValue = TextFormat.ParseInt32(Proto.DefaultValue); break; case FieldType.UInt32: case FieldType.Fixed32: defaultValue = TextFormat.ParseUInt32(Proto.DefaultValue); break; case FieldType.Int64: case FieldType.SInt64: case FieldType.SFixed64: defaultValue = TextFormat.ParseInt64(Proto.DefaultValue); break; case FieldType.UInt64: case FieldType.Fixed64: defaultValue = TextFormat.ParseUInt64(Proto.DefaultValue); break; case FieldType.Float: defaultValue = TextFormat.ParseFloat(Proto.DefaultValue); break; case FieldType.Double: defaultValue = TextFormat.ParseDouble(Proto.DefaultValue); break; case FieldType.Bool: if (Proto.DefaultValue == "true") { defaultValue = true; } else if (Proto.DefaultValue == "false") { defaultValue = false; } else { throw new FormatException("Boolean values must be \"true\" or \"false\""); } break; case FieldType.String: defaultValue = Proto.DefaultValue; break; case FieldType.Bytes: try { defaultValue = TextFormat.UnescapeBytes(Proto.DefaultValue); } catch (FormatException e) { throw new DescriptorValidationException(this, "Couldn't parse default value: " + e.Message); } break; case FieldType.Enum: defaultValue = enumType.FindValueByName(Proto.DefaultValue); if (defaultValue == null) { throw new DescriptorValidationException(this, "Unknown enum default value: \"" + Proto.DefaultValue + "\""); } break; case FieldType.Message: case FieldType.Group: throw new DescriptorValidationException(this, "Message type had default value."); } } catch (FormatException e) { DescriptorValidationException validationException = new DescriptorValidationException(this, "Could not parse default value: \"" + Proto.DefaultValue + "\"", e); throw validationException; } } else { // Determine the default default for this field. if (IsRepeated) { defaultValue = Lists<object>.Empty; } else { switch (MappedType) { case MappedType.Enum: // We guarantee elsewhere that an enum type always has at least // one possible value. defaultValue = enumType.Values[0]; break; case MappedType.Message: defaultValue = null; break; default: defaultValue = GetDefaultValueForMappedType(MappedType); break; } } } if (!IsExtension) { File.DescriptorPool.AddFieldByNumber(this); } if (containingType != null && containingType.Options.MessageSetWireFormat) { if (IsExtension) { if (!IsOptional || FieldType != FieldType.Message) { throw new DescriptorValidationException(this, "Extensions of MessageSets must be optional messages."); } } else { throw new DescriptorValidationException(this, "MessageSets cannot have fields, only extensions."); } } } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Text; using Encog.App.Analyst.Script; using Encog.App.Analyst.Script.Prop; using Encog.App.Analyst.Util; using Encog.Util.CSV; namespace Encog.App.Analyst.Analyze { /// <summary> /// This class is used to perform an analysis of a CSV file. This will help Encog /// to determine how the fields should be normalized. /// </summary> public class PerformAnalysis { /// <summary> /// The file name to analyze. /// </summary> private readonly String _filename; /// <summary> /// The format of this file. /// </summary> private readonly AnalystFileFormat _format; /// <summary> /// True, if headers are present. /// </summary> private readonly bool _headers; /// <summary> /// The script to use. /// </summary> private readonly AnalystScript _script; /// <summary> /// The fields to analyze. /// </summary> private AnalyzedField[] _fields; /// <summary> /// Construct the analysis object. /// </summary> /// <param name="theScript">The script to use.</param> /// <param name="theFilename">The name of the file to analyze.</param> /// <param name="theHeaders">True if headers are present.</param> /// <param name="theFormat">The format of the file being analyzed.</param> public PerformAnalysis(AnalystScript theScript, String theFilename, bool theHeaders, AnalystFileFormat theFormat) { _filename = theFilename; _headers = theHeaders; _format = theFormat; _script = theScript; } /// <summary> /// Generate the header fields. /// </summary> /// <param name="csv">The CSV file to use.</param> private void GenerateFields(ReadCSV csv) { if (_headers) { GenerateFieldsFromHeaders(csv); } else { GenerateFieldsFromCount(csv); } } /// <summary> /// Generate the fields using counts, no headers provided. /// </summary> /// <param name="csv">The CSV file to use.</param> private void GenerateFieldsFromCount(ReadCSV csv) { _fields = new AnalyzedField[csv.ColumnCount]; for (int i = 0; i < _fields.Length; i++) { _fields[i] = new AnalyzedField(_script, "field:" + (i + 1)); } } /// <summary> /// Generate the fields using header values. /// </summary> /// <param name="csv">The CSV file to use.</param> private void GenerateFieldsFromHeaders(ReadCSV csv) { var h = new CSVHeaders(csv.ColumnNames); _fields = new AnalyzedField[csv.ColumnCount]; for (int i = 0; i < _fields.Length; i++) { if (i >= csv.ColumnCount) { throw new AnalystError( "CSV header count does not match column count"); } _fields[i] = new AnalyzedField(_script, h.GetHeader(i)); } } /// <summary> /// Perform the analysis. /// </summary> /// <param name="target">The Encog analyst object to analyze.</param> public void Process(EncogAnalyst target) { int count = 0; CSVFormat csvFormat = ConvertStringConst .ConvertToCSVFormat(_format); var csv = new ReadCSV(_filename, _headers, csvFormat); // pass one, calculate the min/max while (csv.Next()) { if (_fields == null) { GenerateFields(csv); } for (int i = 0; i < csv.ColumnCount; i++) { if (_fields != null) { _fields[i].Analyze1(csv.Get(i)); } } count++; } if (count == 0) { throw new AnalystError("Can't analyze file, it is empty."); } if (_fields != null) { foreach (AnalyzedField field in _fields) { field.CompletePass1(); } } csv.Close(); // pass two, standard deviation csv = new ReadCSV(_filename, _headers, csvFormat); while (csv.Next()) { for (int i = 0; i < csv.ColumnCount; i++) { if (_fields != null) { _fields[i].Analyze2(csv.Get(i)); } } } if (_fields != null) { foreach (AnalyzedField field in _fields) { field.CompletePass2(); } } csv.Close(); String str = _script.Properties.GetPropertyString( ScriptProperties.SetupConfigAllowedClasses) ?? ""; bool allowInt = str.Contains("int"); bool allowReal = str.Contains("real") || str.Contains("double"); bool allowString = str.Contains("string"); // remove any classes that did not qualify foreach (AnalyzedField field in _fields) { if (field.Class) { if (!allowInt && field.Integer) { field.Class = false; } if (!allowString && (!field.Integer && !field.Real)) { field.Class = false; } if (!allowReal && field.Real && !field.Integer) { field.Class = false; } } } // merge with existing if ((target.Script.Fields != null) && (_fields.Length == target.Script.Fields.Length)) { for (int i = 0; i < _fields.Length; i++) { // copy the old field name _fields[i].Name = target.Script.Fields[i].Name; if (_fields[i].Class) { IList<AnalystClassItem> t = _fields[i].AnalyzedClassMembers; IList<AnalystClassItem> s = target.Script.Fields[i].ClassMembers; if (s.Count == t.Count) { for (int j = 0; j < s.Count; j++) { if (t[j].Code.Equals(s[j].Code)) { t[j].Name = s[j].Name; } } } } } } // now copy the fields var df = new DataField[_fields.Length]; for (int i_4 = 0; i_4 < df.Length; i_4++) { df[i_4] = _fields[i_4].FinalizeField(); } target.Script.Fields = df; } /// <summary> /// </summary> public override sealed String ToString() { var result = new StringBuilder("["); result.Append(GetType().Name); result.Append(" filename="); result.Append(_filename); result.Append(", headers="); result.Append(_headers); result.Append("]"); return result.ToString(); } } }
namespace java.lang { [global::MonoJavaBridge.JavaClass()] public sealed partial class Long : java.lang.Number, Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Long() { InitJNI(); } internal Long(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _numberOfLeadingZeros13026; public static int numberOfLeadingZeros(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._numberOfLeadingZeros13026, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _numberOfTrailingZeros13027; public static int numberOfTrailingZeros(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._numberOfTrailingZeros13027, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _bitCount13028; public static int bitCount(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._bitCount13028, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _equals13029; public sealed override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.lang.Long._equals13029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._equals13029, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString13030; public sealed override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.lang.Long._toString13030)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._toString13030)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _toString13031; public static global::java.lang.String toString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._toString13031, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _toString13032; public static global::java.lang.String toString(long arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._toString13032, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode13033; public sealed override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Long._hashCode13033); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._hashCode13033); } internal static global::MonoJavaBridge.MethodId _reverseBytes13034; public static long reverseBytes(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._reverseBytes13034, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo13035; public int compareTo(java.lang.Long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Long._compareTo13035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._compareTo13035, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo13036; public int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Long._compareTo13036, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._compareTo13036, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLong13037; public static global::java.lang.Long getLong(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._getLong13037, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _getLong13038; public static global::java.lang.Long getLong(java.lang.String arg0, long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._getLong13038, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _getLong13039; public static global::java.lang.Long getLong(java.lang.String arg0, java.lang.Long arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._getLong13039, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _toHexString13040; public static global::java.lang.String toHexString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._toHexString13040, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _valueOf13041; public static global::java.lang.Long valueOf(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._valueOf13041, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _valueOf13042; public static global::java.lang.Long valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._valueOf13042, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _valueOf13043; public static global::java.lang.Long valueOf(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._valueOf13043, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _decode13044; public static global::java.lang.Long decode(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._decode13044, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Long; } internal static global::MonoJavaBridge.MethodId _reverse13045; public static long reverse(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._reverse13045, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _byteValue13046; public sealed override byte byteValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallByteMethod(this.JvmHandle, global::java.lang.Long._byteValue13046); else return @__env.CallNonVirtualByteMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._byteValue13046); } internal static global::MonoJavaBridge.MethodId _shortValue13047; public sealed override short shortValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::java.lang.Long._shortValue13047); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._shortValue13047); } internal static global::MonoJavaBridge.MethodId _intValue13048; public sealed override int intValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.lang.Long._intValue13048); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._intValue13048); } internal static global::MonoJavaBridge.MethodId _longValue13049; public sealed override long longValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::java.lang.Long._longValue13049); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._longValue13049); } internal static global::MonoJavaBridge.MethodId _floatValue13050; public sealed override float floatValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::java.lang.Long._floatValue13050); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._floatValue13050); } internal static global::MonoJavaBridge.MethodId _doubleValue13051; public sealed override double doubleValue() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::java.lang.Long._doubleValue13051); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::java.lang.Long.staticClass, global::java.lang.Long._doubleValue13051); } internal static global::MonoJavaBridge.MethodId _toOctalString13052; public static global::java.lang.String toOctalString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._toOctalString13052, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _toBinaryString13053; public static global::java.lang.String toBinaryString(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.Long.staticClass, global::java.lang.Long._toBinaryString13053, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _highestOneBit13054; public static long highestOneBit(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._highestOneBit13054, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _lowestOneBit13055; public static long lowestOneBit(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._lowestOneBit13055, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _rotateLeft13056; public static long rotateLeft(long arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._rotateLeft13056, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _rotateRight13057; public static long rotateRight(long arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._rotateRight13057, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _signum13058; public static int signum(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(java.lang.Long.staticClass, global::java.lang.Long._signum13058, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _parseLong13059; public static long parseLong(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._parseLong13059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _parseLong13060; public static long parseLong(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticLongMethod(java.lang.Long.staticClass, global::java.lang.Long._parseLong13060, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _Long13061; public Long(long arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Long.staticClass, global::java.lang.Long._Long13061, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _Long13062; public Long(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.lang.Long.staticClass, global::java.lang.Long._Long13062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static long MIN_VALUE { get { return -9223372036854775808L; } } public static long MAX_VALUE { get { return 9223372036854775807L; } } internal static global::MonoJavaBridge.FieldId _TYPE13063; public static global::java.lang.Class TYPE { get { return default(global::java.lang.Class); } } public static int SIZE { get { return 64; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.Long.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/Long")); global::java.lang.Long._numberOfLeadingZeros13026 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "numberOfLeadingZeros", "(J)I"); global::java.lang.Long._numberOfTrailingZeros13027 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "numberOfTrailingZeros", "(J)I"); global::java.lang.Long._bitCount13028 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "bitCount", "(J)I"); global::java.lang.Long._equals13029 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.lang.Long._toString13030 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "toString", "()Ljava/lang/String;"); global::java.lang.Long._toString13031 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toString", "(J)Ljava/lang/String;"); global::java.lang.Long._toString13032 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toString", "(JI)Ljava/lang/String;"); global::java.lang.Long._hashCode13033 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "hashCode", "()I"); global::java.lang.Long._reverseBytes13034 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "reverseBytes", "(J)J"); global::java.lang.Long._compareTo13035 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "compareTo", "(Ljava/lang/Long;)I"); global::java.lang.Long._compareTo13036 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::java.lang.Long._getLong13037 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "getLong", "(Ljava/lang/String;)Ljava/lang/Long;"); global::java.lang.Long._getLong13038 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "getLong", "(Ljava/lang/String;J)Ljava/lang/Long;"); global::java.lang.Long._getLong13039 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "getLong", "(Ljava/lang/String;Ljava/lang/Long;)Ljava/lang/Long;"); global::java.lang.Long._toHexString13040 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toHexString", "(J)Ljava/lang/String;"); global::java.lang.Long._valueOf13041 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "valueOf", "(J)Ljava/lang/Long;"); global::java.lang.Long._valueOf13042 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/Long;"); global::java.lang.Long._valueOf13043 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "valueOf", "(Ljava/lang/String;I)Ljava/lang/Long;"); global::java.lang.Long._decode13044 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "decode", "(Ljava/lang/String;)Ljava/lang/Long;"); global::java.lang.Long._reverse13045 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "reverse", "(J)J"); global::java.lang.Long._byteValue13046 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "byteValue", "()B"); global::java.lang.Long._shortValue13047 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "shortValue", "()S"); global::java.lang.Long._intValue13048 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "intValue", "()I"); global::java.lang.Long._longValue13049 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "longValue", "()J"); global::java.lang.Long._floatValue13050 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "floatValue", "()F"); global::java.lang.Long._doubleValue13051 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "doubleValue", "()D"); global::java.lang.Long._toOctalString13052 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toOctalString", "(J)Ljava/lang/String;"); global::java.lang.Long._toBinaryString13053 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "toBinaryString", "(J)Ljava/lang/String;"); global::java.lang.Long._highestOneBit13054 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "highestOneBit", "(J)J"); global::java.lang.Long._lowestOneBit13055 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "lowestOneBit", "(J)J"); global::java.lang.Long._rotateLeft13056 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "rotateLeft", "(JI)J"); global::java.lang.Long._rotateRight13057 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "rotateRight", "(JI)J"); global::java.lang.Long._signum13058 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "signum", "(J)I"); global::java.lang.Long._parseLong13059 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "parseLong", "(Ljava/lang/String;I)J"); global::java.lang.Long._parseLong13060 = @__env.GetStaticMethodIDNoThrow(global::java.lang.Long.staticClass, "parseLong", "(Ljava/lang/String;)J"); global::java.lang.Long._Long13061 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "<init>", "(J)V"); global::java.lang.Long._Long13062 = @__env.GetMethodIDNoThrow(global::java.lang.Long.staticClass, "<init>", "(Ljava/lang/String;)V"); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Runtime; using System.Threading.Tasks; namespace Scriban.Syntax { /// <summary> /// Base class for a loop statement /// </summary> public abstract partial class ScriptLoopStatementBase : ScriptStatement { protected virtual void BeforeLoop(TemplateContext context) { } /// <summary> /// Base implementation for a loop single iteration /// </summary> /// <param name="context">The context</param> /// <param name="state">The state of the loop</param> /// <returns></returns> protected abstract object LoopItem(TemplateContext context, LoopState state); protected virtual LoopState CreateLoopState() { return new LoopState(); } protected bool ContinueLoop(TemplateContext context) { // Return must bubble up to call site if (context.FlowState == ScriptFlowState.Return) { return false; } // If we need to break, restore to none state var result = context.FlowState != ScriptFlowState.Break; context.FlowState = ScriptFlowState.None; return result; } protected virtual void AfterLoop(TemplateContext context) { } public override object Evaluate(TemplateContext context) { // Notify the context that we enter a loop block (used for variable with scope Loop) object result = null; context.EnterLoop(this); try { result = EvaluateImpl(context); } finally { // Level scope block context.ExitLoop(this); if (context.FlowState != ScriptFlowState.Return) { // Revert to flow state to none unless we have a return that must be handled at a higher level context.FlowState = ScriptFlowState.None; } } return result; } protected abstract object EvaluateImpl(TemplateContext context); #if !SCRIBAN_NO_ASYNC protected abstract ValueTask<object> EvaluateImplAsync(TemplateContext context); protected abstract ValueTask<object> LoopItemAsync(TemplateContext context, LoopState state); protected virtual ValueTask BeforeLoopAsync(TemplateContext context) { return new ValueTask(); } protected virtual ValueTask AfterLoopAsync(TemplateContext context) { return new ValueTask(); } #endif /// <summary> /// Store the loop state /// </summary> protected class LoopState : IScriptObject { private int _length; private object _lengthObject; public int Index { get; set; } public int LocalIndex { get; set; } public bool IsFirst => Index == 0; public bool IsEven => (Index & 1) == 0; public bool IsOdd => !IsEven; public bool ValueChanged { get; set; } public bool IsLast { get; set; } public int Length { get => _length; set { _length = value; _lengthObject = value; } } public int Count { get; set; } public IEnumerable<string> GetMembers() { return Enumerable.Empty<string>(); } public virtual bool Contains(string member) { switch (member) { case "index": case "index0": case "first": case "even": case "odd": case "last": return true; case "length": return _lengthObject != null; case "rindex": case "rindex0": return _lengthObject != null; case "changed": return true; } return false; } public bool IsReadOnly { get; set; } public virtual bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object value) { value = null; var isLiquid = context.IsLiquid; switch (member) { case "index": value = isLiquid ? Index + 1 : Index; return true; case "length": value = _lengthObject; return _lengthObject != null; case "first": value = IsFirst ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "even": value = IsEven ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "odd": value = IsOdd ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "last": value = IsLast ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "changed": value = ValueChanged ? BoxHelper.TrueObject : BoxHelper.FalseObject; return true; case "rindex": if (_lengthObject != null) { value = isLiquid ? _length - Index : _length - Index - 1; } return _lengthObject != null; default: if (isLiquid) { if (member == "index0") { value = Index; return true; } if (member == "rindex0") { value = _length - Index - 1; return true; } } return false; } } public bool CanWrite(string member) { throw new System.NotImplementedException(); } public bool TrySetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly) { return false; } public bool Remove(string member) { return false; } public void SetReadOnly(string member, bool readOnly) { } public IScriptObject Clone(bool deep) { return (IScriptObject)MemberwiseClone(); } } } }
using System.Collections; using System.Collections.Generic; using System; using System.Data; using System.Drawing; using System.IO; using FluentNHibernate.Automapping.TestFixtures.ComponentTypes; using FluentNHibernate.Automapping.TestFixtures.CustomCompositeTypes; using FluentNHibernate.Automapping.TestFixtures.CustomTypes; using FluentNHibernate.Conventions.AcceptanceCriteria; using FluentNHibernate.Conventions.Inspections; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.Conventions; using Iesi.Collections.Generic; using NHibernate; using NHibernate.Engine; using NHibernate.SqlTypes; using NHibernate.Type; using NHibernate.UserTypes; namespace FluentNHibernate.Automapping.TestFixtures { public abstract class EntityBaseClassWithPrivateSetter { public int Id { get; private set; } } public class ClassThatInheritsIdFromParentWithPrivateSetter : EntityBaseClassWithPrivateSetter { } public abstract class EntityBase<TPK> { public virtual TPK Id { get; set; } } public class ClassUsingGenericBase : EntityBase<Guid> { public virtual string Name { get; set; } } public class ExampleCustomColumn { public int Id { get; set; } public int ExampleCustomColumnId { get; set; } public int CustomColumn { get { return 12; } } } public class ExampleInheritedClass : ExampleClass { public string ExampleProperty { get; set; } public int SomeNumber{ get; set; } public IList<ExampleClass> Children { get; private set; } public ExampleParentClass Component { get; set; } public IDictionary DictionaryChild { get; set; } } public class ExampleBaseClass { public virtual int Id { get; set; } } public class FirstInheritedClass : ExampleBaseClass { public string Property1 { get; set; } public int PropertyAlsoOnSiblingInheritedClass { get; set; } } public class SecondInheritedClass : ExampleBaseClass { public string Property2 { get; set; } public int PropertyAlsoOnSiblingInheritedClass { get; set; } } public class ClassWithDummyProperty { public virtual int Id { get; set; } public virtual string Dummy { get; set; } public virtual string Dummy1 { get; set; } public virtual string Dummy2 { get; set; } } public class AnotherClassWithDummyProperty { public virtual int Id { get; set; } public virtual string Dummy { get; set; } public virtual string Dummy1 { get; set; } public virtual string Dummy2 { get; set; } } public class ExampleClass { public virtual int Id { get; set; } public virtual int ExampleClassId { get; set; } public virtual string LineOne { get; set; } public TimeSpan Timestamp { get; set; } public ExampleEnum Enum { get; set; } public ExampleParentClass Parent { get; set; } public IDictionary Dictionary { get; set; } } public class PrivateIdSetterClass { public virtual int Id { get; private set; } } public enum ExampleEnum { enum1=1 } public class ExampleParentClass { public int ExampleParentClassId { get; set; } public virtual int Id { get; set; } public virtual IList<ExampleClass> Examples {get; set;} } public class ValidTimestampClass { public virtual int Id { get; set; } public virtual int Timestamp { get; set; } } public class ValidVersionClass { public virtual int Id { get; set; } public virtual long Version { get; set; } } public class InvalidTimestampClass { public virtual int Id { get; set; } public virtual DateTime Timestamp { get; set; } } public class InvalidVersionClass { public virtual int Id { get; set; } public virtual string Version { get; set; } } public class ClassWithUserType { public int Id { get; set; } public Custom Custom { get; set; } } public class ClassWithCompositeUserType { public int Id { get; set; } public DoubleString SomeStringTuple { get; set; } } public class Customer { public virtual int Id { get; set; } public virtual Address HomeAddress { get; set; } public virtual Address WorkAddress { get; set; } } public class ClassWithBitmap { public virtual int Id { get; set; } public virtual Bitmap Bitmap { get; set; } } public class ClassWithGuidId { public virtual Guid Id { get; set; } } public class ClassWithIntId { public virtual int Id { get; set; } } public class ClassWithLongId { public virtual long Id { get; set; } } public class ClassWithStringId { public virtual string Id { get; set; } } } namespace FluentNHibernate.Automapping.TestFixtures.ComponentTypes { public class Address { public int Number { get; set; } public string Street { get; set; } public Custom Custom { get; set; } public IList<Customer> Residents { get; set; } } } namespace FluentNHibernate.Automapping.TestFixtures.CustomTypes { public class Custom { } public class DoubleString { public string s1 { get; set; } public string s2 { get; set; } } public class CustomTypeConvention : UserTypeConvention<CustomUserType> {} public class CustomCompositeTypeConvention : IUserTypeConvention { public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { criteria.Expect(x => x.Type == typeof(DoubleString)); } public void Apply(IPropertyInstance instance) { instance.CustomType<DoubleStringType>(); } } public class CompositeTypeConventionWithCustomPrefix : IUserTypeConvention { public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { criteria.Expect(x => x.Type == typeof(DoubleString)); } public void Apply(IPropertyInstance instance) { instance.CustomType<DoubleStringType>(instance.Property.PropertyType.Name + "WithCustomPrefix_"); } } public class CustomUserType : IUserType { public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object x) { return x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { return null; } public void NullSafeSet(IDbCommand cmd, object value, int index) { } public object DeepCopy(object value) { return value; } public object Replace(object original, object target, object owner) { return original; } public object Assemble(object cached, object owner) { return cached; } public object Disassemble(object value) { return value; } public SqlType[] SqlTypes { get { return new[] {new SqlType(DbType.String)}; } } public Type ReturnedType { get { return typeof(Custom); } } public bool IsMutable { get { return true; } } } } namespace FluentNHibernate.Automapping.TestFixtures.CustomCompositeTypes { public class DoubleStringType : ICompositeUserType { public System.Type ReturnedClass { get { return typeof(string[]); } } public new bool Equals(object x, object y) { if (x == y) return true; if (x == null || y == null) return false; DoubleString lhs = (DoubleString)x; DoubleString rhs = (DoubleString)y; return lhs.s1 == rhs.s1 && lhs.s2 == rhs.s2; } public int GetHashCode(object x) { unchecked { DoubleString a = (DoubleString)x; return a.s1.GetHashCode() + 31 * a.s2.GetHashCode(); } } public Object DeepCopy(Object x) { if (x == null) return null; DoubleString result = new DoubleString(); DoubleString input = (DoubleString)x; result.s1 = input.s1; result.s2 = input.s2; return result; } public bool IsMutable { get { return true; } } public Object NullSafeGet(IDataReader rs, string[] names, ISessionImplementor session, Object owner) { string first = (string)NHibernateUtil.String.NullSafeGet(rs, names[0], session, owner); string second = (string)NHibernateUtil.String.NullSafeGet(rs, names[1], session, owner); return (first == null && second == null) ? null : new string[] { first, second }; } #if NH21 public void NullSafeSet(IDbCommand st, Object value, int index, ISessionImplementor session) { DoubleString ds = value as DoubleString ?? new DoubleString(); NHibernateUtil.String.NullSafeSet(st, ds.s1, index, session); NHibernateUtil.String.NullSafeSet(st, ds.s2, index + 1, session); } #else public void NullSafeSet(IDbCommand st, Object value, int index, bool[] unknown, ISessionImplementor session) { DoubleString ds = value as DoubleString ?? new DoubleString(); NHibernateUtil.String.NullSafeSet(st, ds.s1, index, session); NHibernateUtil.String.NullSafeSet(st, ds.s2, index + 1, session); } #endif public string[] PropertyNames { get { return new string[] { "s1", "s2" }; } } public IType[] PropertyTypes { get { return new IType[] { NHibernateUtil.String, NHibernateUtil.String }; } } public Object GetPropertyValue(Object component, int property) { return ((string[])component)[property]; } public void SetPropertyValue( Object component, int property, Object value) { ((string[])component)[property] = (string)value; } public object Assemble( object cached, ISessionImplementor session, object owner) { return DeepCopy(cached); } public object Disassemble(Object value, ISessionImplementor session) { return DeepCopy(value); } public object Replace(object original, object target, ISessionImplementor session, object owner) { return DeepCopy(original); } } } namespace FluentNHibernate.Automapping.TestFixtures.SuperTypes { public class SuperType { public int Id { get; set; } } public class ExampleCustomColumn : SuperType { public int ExampleCustomColumnId { get; set; } public int CustomColumn { get { return 12; } } } public class ExampleInheritedClass : ExampleClass { public string ExampleProperty { get; set; } public int SomeNumber{ get; set; } } public class ExampleClass : SuperType { public virtual int ExampleClassId { get; set; } public virtual string LineOne { get; set; } public DateTime Timestamp { get; set; } public ExampleEnum Enum { get; set; } public ExampleParentClass Parent { get; set; } } public enum ExampleEnum { enum1=1 } public class ExampleParentClass : SuperType { public int ExampleParentClassId { get; set; } public virtual IList<ExampleClass> Examples {get; set;} } public abstract class Base1 { public virtual int Id { get; protected set; } public abstract void Foo(int x); } public class Derived1 : Base1 { public virtual Decimal Rate { get; set; } public override void Foo(int x) { } public string GetSomething() { return Environment.NewLine; } } public class SecondLevel : Derived1 { public virtual Double SecondRate { get; set; } } public class ThirdLevel : SecondLevel { public virtual Boolean Flag { get; set; } public virtual TimeSpan Version { get; set; } } public class FourthLevel: ThirdLevel { public PublisherType publisherType { get; set; } public ToOne One { get; set; } public IList<ManyToMany> Many { get; set; } } public class ToOne { public virtual int Id { get; protected set; } public virtual string Name { get; set; } } public class ManyToMany { public virtual int Id { get; protected set; } public virtual Decimal Value { get; set; } public IList<FourthLevel> Levels { get; set; } } public enum PublisherType { Online, Offline, Mixed } }
using System; using UnityEngine; 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 bool m_UseHeadBob; [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 float m_StepCycle; private float m_NextStep; private bool m_Jumping; private AudioSource m_AudioSource; // Use this for initialization private void Start() { m_CharacterController = GetComponent<CharacterController>(); m_Camera = gameObject.GetComponentInChildren<Camera>(); m_StepCycle = 0f; m_NextStep = m_StepCycle/2f; m_Jumping = false; m_AudioSource = GetComponent<AudioSource>(); m_MouseLook.Init(transform, m_Camera.transform); } // Update is called once per frame private void Update() { RotateView(); // the jump state needs to read here to make sure it is not missed if (!m_Jump) { m_Jump = Input.GetButtonDown("Jump"); } if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) { PlayLandingSound(); m_MoveDir.y = 0f; m_Jumping = false; } if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) { m_MoveDir.y = 0f; } m_PreviouslyGrounded = m_CharacterController.isGrounded; } private void PlayLandingSound() { m_AudioSource.clip = m_LandSound; m_AudioSource.Play(); m_NextStep = m_StepCycle + .5f; } private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, m_CharacterController.height/2f, ~0, 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 m_AudioSource.PlayOneShot(m_AudioSource.clip); // move picked sound to index 0 so it's not picked next time } private void UpdateCameraPosition(float speed) { Vector3 newCameraPosition; if (!m_UseHeadBob) { return; } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { newCameraPosition = m_Camera.transform.localPosition; } else { newCameraPosition = m_Camera.transform.localPosition; } m_Camera.transform.localPosition = newCameraPosition; } private void GetInput(out float speed) { // Read input float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.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(); } } private void RotateView() { m_MouseLook.LookRotation(transform, m_Camera.transform); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; //dont move the rigidbody if the character is on top of it if (m_CollisionFlags == CollisionFlags.Below) { return; } if (body == null || body.isKinematic) { return; } body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); } } }
// Copyright (c) Microsoft 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.Azure.AcceptanceTestsAzureBodyDuration { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// DurationOperations operations. /// </summary> internal partial class DurationOperations : Microsoft.Rest.IServiceOperations<AutoRestDurationTestService>, IDurationOperations { /// <summary> /// Initializes a new instance of the DurationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DurationOperations(AutoRestDurationTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestDurationTestService /// </summary> public AutoRestDurationTestService Client { get; private set; } /// <summary> /// Get null duration value /// </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="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put a positive duration value /// </summary> /// <param name='durationBody'> /// </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 System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutPositiveDurationWithHttpMessagesAsync(System.TimeSpan durationBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("durationBody", durationBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(durationBody, this.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"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a positive duration value /// </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="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an invalid duration value /// </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="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//============================================================================= // System : EWSoftware Design Time Attributes and Editors // File : VersionBuilderConfigDlg.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 06/28/2010 // Note : Copyright 2007-2010, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains the form used to edit the version builder plug-in // configuration. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.3 12/01/2007 EFW Created the code // 1.8.0.0 08/13/2008 EFW Updated to support the new project format // 1.9.0.0 06/27/2010 EFW Added support for /rip option //============================================================================= using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using SandcastleBuilder.Utils; namespace SandcastleBuilder.PlugIns { /// <summary> /// This form is used to edit the <see cref="VersionBuilderPlugIn"/> /// configuration. /// </summary> internal partial class VersionBuilderConfigDlg : Form { #region Private data members //===================================================================== private VersionSettingsCollection items; private XmlDocument config; // The configuration private SandcastleProject project; #endregion #region Properties //===================================================================== /// <summary> /// This is used to return the configuration information /// </summary> public string Configuration { get { return config.OuterXml; } } #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="currentProject">The current project</param> /// <param name="currentConfig">The current XML configuration /// XML fragment</param> public VersionBuilderConfigDlg(SandcastleProject currentProject, string currentConfig) { XPathNavigator navigator, root, node; string ripOldApis; InitializeComponent(); project = currentProject; lnkCodePlexSHFB.Links[0].LinkData = "http://SHFB.CodePlex.com"; lbVersionInfo.DisplayMember = lbVersionInfo.ValueMember = "ListDescription"; items = new VersionSettingsCollection(); // Load the current settings config = new XmlDocument(); config.LoadXml(currentConfig); navigator = config.CreateNavigator(); root = navigator.SelectSingleNode("configuration"); if(root.IsEmptyElement) return; node = root.SelectSingleNode("currentProject"); if(node != null) { txtLabel.Text = node.GetAttribute("label", String.Empty); txtVersion.Text = node.GetAttribute("version", String.Empty); ripOldApis = node.GetAttribute("ripOldApis", String.Empty); // This wasn't in earlier versions if(!String.IsNullOrEmpty(ripOldApis)) chkRipOldAPIs.Checked = Convert.ToBoolean(ripOldApis, CultureInfo.InvariantCulture); } items.FromXml(currentProject, root); if(items.Count == 0) pgProps.Enabled = btnDelete.Enabled = false; else { // Binding the collection to the list box caused some // odd problems with the property grid so we'll add the // items to the list box directly. foreach(VersionSettings vs in items) lbVersionInfo.Items.Add(vs); lbVersionInfo.SelectedIndex = 0; } } #endregion #region Event handlers //===================================================================== /// <summary> /// Close without saving /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } /// <summary> /// Add a new help file builder project to the version settings. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnAddFile_Click(object sender, EventArgs e) { VersionSettings newItem; int idx = 0; using(OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "Select the help file builder project(s)"; dlg.Filter = "Sandcastle Help File Builder Project Files (*.shfbproj)|*.shfbproj|All Files (*.*)|*.*"; dlg.InitialDirectory = Directory.GetCurrentDirectory(); dlg.DefaultExt = "shfbproj"; dlg.Multiselect = true; // If selected, add the file(s) if(dlg.ShowDialog() == DialogResult.OK) { foreach(string file in dlg.FileNames) { newItem = new VersionSettings(); newItem.HelpFileProject = new FilePath(file, project); // It will end up on the last one added idx = lbVersionInfo.Items.Add(newItem); } pgProps.Enabled = btnDelete.Enabled = true; lbVersionInfo.SelectedIndex = idx; } } } /// <summary> /// Delete a version settings item /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnDelete_Click(object sender, EventArgs e) { int idx = lbVersionInfo.SelectedIndex; if(idx == -1) lbVersionInfo.SelectedIndex = 0; else { lbVersionInfo.Items.RemoveAt(idx); if(lbVersionInfo.Items.Count == 0) pgProps.Enabled = btnDelete.Enabled = false; else if(idx < lbVersionInfo.Items.Count) lbVersionInfo.SelectedIndex = idx; else lbVersionInfo.SelectedIndex = lbVersionInfo.Items.Count - 1; } } /// <summary> /// Update the property grid with the selected item /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void lbVersionInfo_SelectedIndexChanged(object sender, EventArgs e) { if(lbVersionInfo.SelectedItem != null) { VersionSettings vs = (VersionSettings)lbVersionInfo.SelectedItem; pgProps.SelectedObject = vs; } else pgProps.SelectedObject = null; pgProps.Refresh(); } /// <summary> /// Refresh the list box item when a property changes /// </summary> /// <param name="s">The sender of the event</param> /// <param name="e">The event arguments</param> private void pgProps_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { lbVersionInfo.Refresh(lbVersionInfo.SelectedIndex); } /// <summary> /// Validate the configuration and save it /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void btnOK_Click(object sender, EventArgs e) { Dictionary<int, string> projects = new Dictionary<int, string>(); VersionSettings vs; XmlAttribute attr; XmlNode root, node; string hash; bool isValid = true; txtLabel.Text = txtLabel.Text.Trim(); txtVersion.Text = txtVersion.Text.Trim(); epErrors.Clear(); epErrors.SetIconAlignment(lbVersionInfo, ErrorIconAlignment.BottomRight); if(txtVersion.Text.Length == 0) { epErrors.SetError(txtVersion, "A version for the containing project is required"); isValid = false; } items.Clear(); hash = txtLabel.Text + txtVersion.Text; projects.Add(hash.GetHashCode(), "@CurrentProject"); for(int idx = 0; idx < lbVersionInfo.Items.Count; idx++) { vs = (VersionSettings)lbVersionInfo.Items[idx]; // There can't be duplicate IDs or projects if(projects.ContainsKey(vs.GetHashCode()) || projects.ContainsValue(vs.HelpFileProject)) { epErrors.SetError(lbVersionInfo, "Label + Version values and project filenames must be unique"); isValid = false; break; } if(vs.Version == txtVersion.Text) { epErrors.SetError(lbVersionInfo, "A prior version cannot match the current project's version"); isValid = false; break; } items.Add(vs); projects.Add(vs.GetHashCode(), vs.HelpFileProject); } if(!isValid) return; // Store the changes root = config.SelectSingleNode("configuration"); node = root.SelectSingleNode("currentProject"); if(node == null) { node = config.CreateNode(XmlNodeType.Element, "currentProject", null); root.AppendChild(node); attr = config.CreateAttribute("label"); node.Attributes.Append(attr); attr = config.CreateAttribute("version"); node.Attributes.Append(attr); attr = config.CreateAttribute("ripOldApis"); node.Attributes.Append(attr); } else { // This wasn't in older versions so add it if it is missing if(node.Attributes["ripOldApis"] == null) { attr = config.CreateAttribute("ripOldApis"); node.Attributes.Append(attr); } } node.Attributes["label"].Value = txtLabel.Text; node.Attributes["version"].Value = txtVersion.Text; node.Attributes["ripOldApis"].Value = chkRipOldAPIs.Checked.ToString(); items.ToXml(config, root); this.DialogResult = DialogResult.OK; this.Close(); } /// <summary> /// Launch the URL in the web browser /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void lnkCodePlexSHFB_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { System.Diagnostics.Process.Start((string)e.Link.LinkData); } catch(Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); MessageBox.Show("Unable to launch link target. Reason: " + ex.Message, Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Media; using Android.OS; using Android.Support.V4.Media.Session; using Plugin.MediaManager.Abstractions; using Plugin.MediaManager.Abstractions.EventArguments; namespace Plugin.MediaManager { [Service] [IntentFilter(new[] { ActionPlay, ActionPause, ActionStop, ActionTogglePlayback, ActionNext, ActionPrevious })] public class MediaPlayerService : MediaServiceBase, MediaPlayer.IOnBufferingUpdateListener, MediaPlayer.IOnCompletionListener, MediaPlayer.IOnErrorListener, MediaPlayer.IOnPreparedListener, MediaPlayer.IOnSeekCompleteListener { private MediaPlayer _mediaPlayer; private TimeSpan _buffered = TimeSpan.Zero; public override TimeSpan Position { get { if (_mediaPlayer == null || (MediaPlayerState != PlaybackStateCompat.StatePlaying && MediaPlayerState != PlaybackStateCompat.StatePaused)) return TimeSpan.FromSeconds(-1); else return TimeSpan.FromMilliseconds(_mediaPlayer.CurrentPosition); } } public override TimeSpan Duration { get { if (_mediaPlayer == null || (MediaPlayerState != PlaybackStateCompat.StatePlaying && MediaPlayerState != PlaybackStateCompat.StatePaused)) return TimeSpan.Zero; else return TimeSpan.FromMilliseconds(_mediaPlayer.Duration); } } public override TimeSpan Buffered { get { if (_mediaPlayer == null) return TimeSpan.Zero; else return _buffered; } } public override void InitializePlayer() { DisposeMediaPlayer(); _mediaPlayer = new MediaPlayer(); SetMediaPlayerOptions(); } public override void InitializePlayerWithUrl(string audioUrl) { Android.Net.Uri uri = Android.Net.Uri.Parse(Android.Net.Uri.Encode(audioUrl)); _mediaPlayer = MediaPlayer.Create(ApplicationContext, uri); SetMediaPlayerOptions(); } public override void SetMediaPlayerOptions() { //Tell our player to sream music _mediaPlayer.SetAudioStreamType(Stream.Music); //Wake mode will be partial to keep the CPU still running under lock screen _mediaPlayer.SetWakeMode(ApplicationContext, WakeLockFlags.Partial); _mediaPlayer.SetOnBufferingUpdateListener(this); _mediaPlayer.SetOnCompletionListener(this); _mediaPlayer.SetOnErrorListener(this); _mediaPlayer.SetOnPreparedListener(this); } [Obsolete("deprecated")] public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { HandleIntent(intent); return base.OnStartCommand(intent, flags, startId); } #region ****************** MediaPlayer Actions ****************** public override async Task Play(IMediaFile mediaFile = null) { await base.Play(mediaFile); try { _mediaPlayer.PrepareAsync(); } catch (Java.Lang.IllegalStateException) { _mediaPlayer.Reset(); await SetMediaPlayerDataSource(); _mediaPlayer.PrepareAsync(); } } public override Task TogglePlayPause(bool forceToPlay) { return Task.Run(() => { if (_mediaPlayer != null) { if (_mediaPlayer.IsPlaying && !forceToPlay) { _mediaPlayer.Pause(); } else { _mediaPlayer.Start(); } } }); } public override void SetVolume(float leftVolume, float rightVolume) { _mediaPlayer?.SetVolume(leftVolume, rightVolume); } public override async Task<bool> SetMediaPlayerDataSource() { try { if (Build.VERSION.SdkInt < BuildVersionCodes.Honeycomb) try { await SetMediaPlayerDataSourcePreHoneyComb(); } catch (Exception e) { await SetMediaPlayerDataSourcePostHoneyComb(); } else await SetMediaPlayerDataSourcePostHoneyComb(); } catch (Exception e) { try { await SetMediaPlayerDataSourceUsingFileDescriptor(); } catch (Exception ex) { String uri = GetUriFromPath(ApplicationContext, CurrentFile.Url); _mediaPlayer.Reset(); try { await _mediaPlayer.SetDataSourceAsync(ApplicationContext, Android.Net.Uri.Parse(uri), RequestHeaders); } catch (Exception) { return false; } } } return true; } public override Task Play(IEnumerable<IMediaFile> mediaFiles) { throw new NotImplementedException(); } public override async Task Seek(TimeSpan position) { await Task.Run(() => { _mediaPlayer?.SeekTo(Convert.ToInt32(position.TotalMilliseconds)); }); } public override async Task Pause() { await Task.Run(() => { if (_mediaPlayer == null) return; if (_mediaPlayer.IsPlaying) _mediaPlayer.Pause(); if (!TransientPaused) ManuallyPaused = true; }); await base.Pause(); } public override async Task Stop() { try { if (_mediaPlayer == null) return; if (_mediaPlayer.IsPlaying) { _mediaPlayer.Stop(); } _mediaPlayer.Reset(); } catch (Java.Lang.IllegalStateException ex) { Console.WriteLine(ex.Message); } await base.Stop(); } #endregion #region ****************** MediaPlayer Listener ****************** public void OnCompletion(MediaPlayer mp) { OnMediaFinished(new MediaFinishedEventArgs(CurrentFile)); } public bool OnError(MediaPlayer mp, MediaError what, int extra) { SessionManager.UpdatePlaybackState(PlaybackStateCompat.StateError, Position.Seconds, Enum.GetName(typeof(MediaError), what)); Stop(); return true; } public void OnSeekComplete(MediaPlayer mp) { //TODO: Implement buffering on seeking } public void OnPrepared(MediaPlayer mp) { mp.Start(); SessionManager.UpdatePlaybackState(PlaybackStateCompat.StatePlaying, Position.Seconds); } public void OnBufferingUpdate(MediaPlayer mp, int percent) { int duration = 0; if (MediaPlayerState == PlaybackStateCompat.StatePlaying || MediaPlayerState == PlaybackStateCompat.StatePaused) duration = mp.Duration; int newBufferedTime = duration * percent / 100; if (newBufferedTime != Convert.ToInt32(Buffered.TotalSeconds)) { _buffered = TimeSpan.FromSeconds(newBufferedTime); } } #endregion #region ********************* Private Methods ******************* private async Task SetMediaPlayerDataSourcePreHoneyComb() { _mediaPlayer.Reset(); await _mediaPlayer.SetDataSourceAsync(CurrentFile.Url); } private async Task SetMediaPlayerDataSourcePostHoneyComb() { _mediaPlayer?.Reset(); Android.Net.Uri uri = Android.Net.Uri.Parse(CurrentFile.Url); var dataSourceAsync = _mediaPlayer?.SetDataSourceAsync(ApplicationContext, uri, RequestHeaders); if (dataSourceAsync != null) await dataSourceAsync; } private async Task SetMediaPlayerDataSourceUsingFileDescriptor() { Java.IO.File file = new Java.IO.File(CurrentFile.Url); Java.IO.FileInputStream inputStream = new Java.IO.FileInputStream(file); _mediaPlayer?.Reset(); var dataSourceAsync = _mediaPlayer?.SetDataSourceAsync(inputStream.FD); if (dataSourceAsync != null) await dataSourceAsync; inputStream.Close(); } #endregion public override void OnDestroy() { if (_mediaPlayer != null) { _mediaPlayer.Release(); _mediaPlayer = null; } base.OnDestroy(); } private void DisposeMediaPlayer() { _mediaPlayer?.Reset(); _mediaPlayer?.Release(); _mediaPlayer?.Dispose(); _mediaPlayer = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using ThreadState = System.Threading.ThreadState; namespace System.IO.Ports.Tests { public class WriteLine_Generic : PortsTest { //Set bounds for random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the write method and the testcase fails. private const double maxPercentageDifference = .15; //The string used when we expect the ReadCall to throw an exception for something other //then the contents of the string itself private const string DEFAULT_STRING = "DEFAULT_STRING"; //The string size used when veryifying BytesToWrite private static readonly int s_STRING_SIZE_BYTES_TO_WRITE = TCSupport.MinimumBlockingByteCount; //The string size used when veryifying Handshake private static readonly int s_STRING_SIZE_HANDSHAKE = TCSupport.MinimumBlockingByteCount; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void WriteWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Case WriteWithoutOpen : Verifying write method throws System.InvalidOperationException without a call to Open()"); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Case WriteAfterFailedOpen : Verifying write method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verifying a write method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void WriteAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Case WriteAfterClose : Verifying write method throws exception after a call to Close()"); com.Open(); com.Close(); VerifyWriteException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasNullModem))] public void SimpleTimeout() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] XOffBuffer = new byte[1]; XOffBuffer[0] = 19; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.XOnXOff; Debug.WriteLine("Case SimpleTimeout : Verifying WriteTimeout={0}", com1.WriteTimeout); com1.Open(); com2.Open(); com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); com2.Close(); VerifyTimeout(com1); } } [OuterLoop("Slow test")] [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com.Handshake = Handshake.RequestToSendXOnXOff; com.Encoding = Encoding.Unicode; Debug.WriteLine("Case SuccessiveReadTimeout : Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); try { com.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void SuccessiveReadTimeoutWithWriteSucceeding() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); Thread t = new Thread(asyncEnableRts.EnableRTS); int waitTime; com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Handshake = Handshake.RequestToSend; com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Case SuccessiveReadTimeoutWithWriteSucceeding : Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); com1.Open(); //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed //before the timeout is reached t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start Thread.Sleep(50); waitTime += 50; } try { com1.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } asyncEnableRts.Stop(); while (t.IsAlive) Thread.Sleep(100); VerifyTimeout(com1); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWrite() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE); Thread t = new Thread(asyncWriteRndStr.WriteRndStr); int numNewLineBytes; int waitTime; Debug.WriteLine("Case BytesToWrite : Verifying BytesToWrite with one call to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 500; numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); //Write a random string asynchronously so we can verify some things while the write call is blocking t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start Thread.Sleep(50); waitTime += 50; } TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes); //Wait for write method to timeout while (t.IsAlive) Thread.Sleep(100); } } [ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))] public void BytesToWriteSuccessive() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_BYTES_TO_WRITE); Thread t1 = new Thread(asyncWriteRndStr.WriteRndStr); Thread t2 = new Thread(asyncWriteRndStr.WriteRndStr); int numNewLineBytes; int waitTime; Debug.WriteLine("Case BytesToWriteSuccessive : Verifying BytesToWrite with successive calls to Write"); com.Handshake = Handshake.RequestToSend; com.Open(); com.WriteTimeout = 1000; numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); //Write a random string asynchronously so we can verify some things while the write call is blocking t1.Start(); waitTime = 0; while (t1.ThreadState == ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start Thread.Sleep(50); waitTime += 50; } TCSupport.WaitForWriteBufferToLoad(com, s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes); //Write a random string asynchronously so we can verify some things while the write call is blocking t2.Start(); waitTime = 0; while (t2.ThreadState == ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start Thread.Sleep(50); waitTime += 50; } TCSupport.WaitForWriteBufferToLoad(com, (s_STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2); //Wait for both write methods to timeout while (t1.IsAlive || t2.IsAlive) Thread.Sleep(100); } } [ConditionalFact(nameof(HasNullModem))] public void Handshake_None() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, s_STRING_SIZE_HANDSHAKE); Thread t = new Thread(asyncWriteRndStr.WriteRndStr); int waitTime; //Write a random string asynchronously so we can verify some things while the write call is blocking Debug.WriteLine("Case Handshake_None : Verifying Handshake=None"); com.Open(); t.Start(); waitTime = 0; while (t.ThreadState == ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start Thread.Sleep(50); waitTime += 50; } //Wait for both write methods to timeout while (t.IsAlive) Thread.Sleep(100); Assert.Equal(0, com.BytesToWrite); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSend() { Debug.WriteLine("Case Handshake_RequestToSend : Verifying Handshake=RequestToSend"); Verify_Handshake(Handshake.RequestToSend); } [ConditionalFact(nameof(HasNullModem))] public void Handshake_XOnXOff() { Debug.WriteLine("Case Handshake_XOnXOff : Verifying Handshake=XOnXOff"); Verify_Handshake(Handshake.XOnXOff); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Handshake_RequestToSendXOnXOff() { Debug.WriteLine("Case Handshake_RequestToSendXOnXOff : Verifying Handshake=RequestToSendXOnXOff"); Verify_Handshake(Handshake.RequestToSendXOnXOff); } private class AsyncEnableRts { private bool _stop; public void EnableRTS() { lock (this) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) Monitor.Wait(this); com2.RtsEnable = false; } } } public void Stop() { lock (this) { _stop = true; Monitor.Pulse(this); } } } private class AsyncWriteRndStr { private readonly SerialPort _com; private readonly int _strSize; public AsyncWriteRndStr(SerialPort com, int strSize) { _com = com; _strSize = strSize; } public void WriteRndStr() { string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); try { _com.WriteLine(stringToWrite); } catch (TimeoutException) { } } } #endregion #region Verification for Test Cases private static void VerifyWriteException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.WriteLine(DEFAULT_STRING)); } private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; try { com.WriteLine(DEFAULT_STRING); //Warm up write method } catch (TimeoutException) { } Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); try { com.WriteLine(DEFAULT_STRING); } catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; int numNewLineBytes; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.WriteTimeout = 3000; com1.Handshake = handshake; com1.Open(); com2.Open(); numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); //Setup to ensure write will block with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } //Write a random string asynchronously so we can verify some things while the write call is blocking string randomLine = TCSupport.GetRandomString(s_STRING_SIZE_HANDSHAKE, TCSupport.CharacterOptions.Surrogates); byte[] randomLineBytes = com1.Encoding.GetBytes(randomLine); Task task = Task.Run(() => com1.WriteLine(randomLine)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, randomLineBytes.Length + numNewLineBytes); //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); } //Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOnBuffer, 0, 1); } //Wait till write finishes TCSupport.WaitForTaskCompletion(task); Assert.Equal(0, com1.BytesToWrite); //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding); } } } #endregion } }
using System; using System.Collections; using System.Reflection; using Hydra.Framework; using Hydra.Framework.Types; namespace Hydra.Framework { // //********************************************************************** /// <summary> /// Resolves a <see cref="System.Type"/> by name. /// </summary> //********************************************************************** // public class TypeResolver : ITypeResolver { // //********************************************************************** /// <summary> /// Resolves the supplied <paramref name="typeName"/> to a /// <see cref="System.Type"/> instance. /// </summary> /// <param name="typeName">The unresolved name of a <see cref="System.Type"/>.</param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the supplied <paramref name="typeName"/> could not be resolved /// to a <see cref="System.Type"/>. /// </exception> //********************************************************************** // public Type Resolve(string typeName) { Type type = ResolveGenericType(typeName); if (type == null) { type = ResolveType(typeName); } return type; } // //********************************************************************** /// <summary> /// Resolves the supplied generic <paramref name="typeName"/>, /// substituting recursively all its type parameters., /// to a <see cref="System.Type"/> instance. /// </summary> /// <param name="typeName">The (possibly generic) name of a <see cref="System.Type"/>.</param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the supplied <paramref name="typeName"/> could not be resolved /// to a <see cref="System.Type"/>. /// </exception> //********************************************************************** // private Type ResolveGenericType(string typeName) { if (string.IsNullOrEmpty(typeName)) { throw BuildTypeLoadException(typeName); } GenericArgumentsInfo genericInfo = new GenericArgumentsInfo(typeName); Type type = null; try { if (genericInfo.ContainsGenericArguments) { type = ObjectUtils.ResolveType(genericInfo.GenericTypeName); if (!genericInfo.IsGenericDefinition) { string[] unresolvedGenericArgs = genericInfo.GetGenericArguments(); Type[] genericArgs = new Type[unresolvedGenericArgs.Length]; for (int i = 0; i < unresolvedGenericArgs.Length; i++) { genericArgs[i] = ObjectUtils.ResolveType(unresolvedGenericArgs[i]); } type = type.MakeGenericType(genericArgs); } } } catch (Exception ex) { if (ex is TypeLoadException) { throw; } throw BuildTypeLoadException(typeName, ex); } return type; } // //********************************************************************** /// <summary> /// Resolves the supplied <paramref name="typeName"/> to a /// <see cref="System.Type"/> /// instance. /// </summary> /// <param name="typeName">The (possibly partially assembly qualified) name of a /// <see cref="System.Type"/>.</param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the supplied <paramref name="typeName"/> could not be resolved /// to a <see cref="System.Type"/>. /// </exception> //********************************************************************** // private Type ResolveType(string typeName) { if (string.IsNullOrEmpty(typeName)) { throw BuildTypeLoadException(typeName); } TypeAssemblyInfo typeInfo = new TypeAssemblyInfo(typeName); Type type = null; try { type = (typeInfo.IsAssemblyQualified) ? LoadTypeDirectlyFromAssembly(typeInfo) : LoadTypeByIteratingOverAllLoadedAssemblies(typeInfo); } catch (Exception ex) { throw BuildTypeLoadException(typeName, ex); } if (type == null) { throw BuildTypeLoadException(typeName); } return type; } // //********************************************************************** /// <summary> /// Uses <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> /// to load an <see cref="System.Reflection.Assembly"/> and then the attendant /// <see cref="System.Type"/> referred to by the <paramref name="typeInfo"/> /// parameter. /// </summary> /// <param name="typeInfo">The assembly and type to be loaded.</param> /// <returns> /// A <see cref="System.Type"/>, or <see lang="null"/>. /// </returns> /// <remarks> /// <p> /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> is /// deprecated in .NET 2.0, but is still used here (even when this class is /// compiled for .NET 2.0); /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> will /// still resolve (non-.NET Framework) local assemblies when given only the /// display name of an assembly (the behaviour for .NET Framework assemblies /// and strongly named assemblies is documented in the docs for the /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> method). /// </p> /// </remarks> /// <exception cref="System.Exception"> /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> /// </exception> //********************************************************************** // private static Type LoadTypeDirectlyFromAssembly(TypeAssemblyInfo typeInfo) { Type type = null; Assembly assembly = Assembly.LoadWithPartialName(typeInfo.AssemblyName); if (assembly != null) { type = assembly.GetType(typeInfo.TypeName, true, true); } return type; } // //********************************************************************** /// <summary> /// Uses <see cref="M:System.AppDomain.CurrentDomain.GetAssemblies()"/> /// to load the attendant <see cref="System.Type"/> referred to by /// the <paramref name="typeInfo"/> parameter. /// </summary> /// <param name="typeInfo">The type to be loaded.</param> /// <returns> /// A <see cref="System.Type"/>, or <see lang="null"/>. /// </returns> //********************************************************************** // private static Type LoadTypeByIteratingOverAllLoadedAssemblies(TypeAssemblyInfo typeInfo) { Type type = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { type = assembly.GetType(typeInfo.TypeName, false, false); if (type != null) { break; } } return type; } // //********************************************************************** /// <summary> /// Builds the type load exception. /// </summary> /// <param name="typeName">StateName of the type.</param> /// <returns></returns> //********************************************************************** // private static TypeLoadException BuildTypeLoadException(string typeName) { return new TypeLoadException("Could not load type from string value '" + typeName + "'."); } // //********************************************************************** /// <summary> /// Builds the type load exception. /// </summary> /// <param name="typeName">StateName of the type.</param> /// <param name="ex">The ex.</param> /// <returns></returns> //********************************************************************** // private static TypeLoadException BuildTypeLoadException(string typeName, Exception ex) { return new TypeLoadException("Could not load type from string value '" + typeName + "'.", ex); } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using MetroFramework.Drawing.Html.Adapters; using MetroFramework.Drawing.Html.Adapters.Entities; using MetroFramework.Drawing.Html.Core.Handlers; namespace MetroFramework.Drawing.Html.Core.Dom { /// <summary> /// Represents a word inside an inline box /// </summary> /// <remarks> /// Because of performance, words of text are the most atomic /// element in the project. It should be characters, but come on, /// imagine the performance when drawing char by char on the device.<br/> /// It may change for future versions of the library. /// </remarks> internal abstract class CssRect { #region Fields and Consts /// <summary> /// the CSS box owner of the word /// </summary> private readonly CssBox _ownerBox; /// <summary> /// Rectangle /// </summary> private RRect _rect; /// <summary> /// If the word is selected this points to the selection handler for more data /// </summary> private SelectionHandler _selection; #endregion /// <summary> /// Init. /// </summary> /// <param name="owner">the CSS box owner of the word</param> protected CssRect(CssBox owner) { _ownerBox = owner; } /// <summary> /// Gets the Box where this word belongs. /// </summary> public CssBox OwnerBox { get { return _ownerBox; } } /// <summary> /// Gets or sets the bounds of the rectangle /// </summary> public RRect Rectangle { get { return _rect; } set { _rect = value; } } /// <summary> /// Left of the rectangle /// </summary> public double Left { get { return _rect.X; } set { _rect.X = value; } } /// <summary> /// Top of the rectangle /// </summary> public double Top { get { return _rect.Y; } set { _rect.Y = value; } } /// <summary> /// Width of the rectangle /// </summary> public double Width { get { return _rect.Width; } set { _rect.Width = value; } } /// <summary> /// Get the full width of the word including the spacing. /// </summary> public double FullWidth { get { return _rect.Width + ActualWordSpacing; } } /// <summary> /// Gets the actual width of whitespace between words. /// </summary> public double ActualWordSpacing { get { return (OwnerBox != null ? (HasSpaceAfter ? OwnerBox.ActualWordSpacing : 0) + (IsImage ? OwnerBox.ActualWordSpacing : 0) : 0); } } /// <summary> /// Height of the rectangle /// </summary> public double Height { get { return _rect.Height; } set { _rect.Height = value; } } /// <summary> /// Gets or sets the right of the rectangle. When setting, it only affects the Width of the rectangle. /// </summary> public double Right { get { return Rectangle.Right; } set { Width = value - Left; } } /// <summary> /// Gets or sets the bottom of the rectangle. When setting, it only affects the Height of the rectangle. /// </summary> public double Bottom { get { return Rectangle.Bottom; } set { Height = value - Top; } } /// <summary> /// If the word is selected this points to the selection handler for more data /// </summary> public SelectionHandler Selection { get { return _selection; } set { _selection = value; } } /// <summary> /// was there a whitespace before the word chars (before trim) /// </summary> public virtual bool HasSpaceBefore { get { return false; } } /// <summary> /// was there a whitespace after the word chars (before trim) /// </summary> public virtual bool HasSpaceAfter { get { return false; } } /// <summary> /// Gets the image this words represents (if one exists) /// </summary> public virtual RImage Image { get { return null; } // ReSharper disable ValueParameterNotUsed set { } // ReSharper restore ValueParameterNotUsed } /// <summary> /// Gets if the word represents an image. /// </summary> public virtual bool IsImage { get { return false; } } /// <summary> /// Gets a bool indicating if this word is composed only by spaces. /// Spaces include tabs and line breaks /// </summary> public virtual bool IsSpaces { get { return true; } } /// <summary> /// Gets if the word is composed by only a line break /// </summary> public virtual bool IsLineBreak { get { return false; } } /// <summary> /// Gets the text of the word /// </summary> public virtual string Text { get { return null; } } /// <summary> /// is the word is currently selected /// </summary> public bool Selected { get { return _selection != null; } } /// <summary> /// the selection start index if the word is partially selected (-1 if not selected or fully selected) /// </summary> public int SelectedStartIndex { get { return _selection != null ? _selection.GetSelectingStartIndex(this) : -1; } } /// <summary> /// the selection end index if the word is partially selected (-1 if not selected or fully selected) /// </summary> public int SelectedEndIndexOffset { get { return _selection != null ? _selection.GetSelectedEndIndexOffset(this) : -1; } } /// <summary> /// the selection start offset if the word is partially selected (-1 if not selected or fully selected) /// </summary> public double SelectedStartOffset { get { return _selection != null ? _selection.GetSelectedStartOffset(this) : -1; } } /// <summary> /// the selection end offset if the word is partially selected (-1 if not selected or fully selected) /// </summary> public double SelectedEndOffset { get { return _selection != null ? _selection.GetSelectedEndOffset(this) : -1; } } /// <summary> /// Gets or sets an offset to be considered in measurements /// </summary> internal double LeftGlyphPadding { get { return OwnerBox != null ? OwnerBox.ActualFont.LeftPadding : 0; } } /// <summary> /// Represents this word for debugging purposes /// </summary> /// <returns></returns> public override string ToString() { return string.Format("{0} ({1} char{2})", Text.Replace(' ', '-').Replace("\n", "\\n"), Text.Length, Text.Length != 1 ? "s" : string.Empty); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BTCPayServer; using BTCPayServer.Abstractions.Models; using BTCPayServer.Client.Models; using BTCPayServer.Data; using BTCPayServer.Events; using BTCPayServer.HostedServices; using BTCPayServer.Logging; using BTCPayServer.Payments; using BTCPayServer.Services; using BTCPayServer.Services.Notifications; using BTCPayServer.Services.Notifications.Blobs; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NBitcoin; using NBitcoin.Payment; using NBitcoin.RPC; using NBXplorer.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NewBlockEvent = BTCPayServer.Events.NewBlockEvent; using PayoutData = BTCPayServer.Data.PayoutData; using StoreData = BTCPayServer.Data.StoreData; public class BitcoinLikePayoutHandler : IPayoutHandler { private readonly BTCPayNetworkProvider _btcPayNetworkProvider; private readonly ExplorerClientProvider _explorerClientProvider; private readonly BTCPayNetworkJsonSerializerSettings _jsonSerializerSettings; private readonly ApplicationDbContextFactory _dbContextFactory; private readonly EventAggregator _eventAggregator; private readonly NotificationSender _notificationSender; private readonly Logs Logs; public BitcoinLikePayoutHandler(BTCPayNetworkProvider btcPayNetworkProvider, ExplorerClientProvider explorerClientProvider, BTCPayNetworkJsonSerializerSettings jsonSerializerSettings, ApplicationDbContextFactory dbContextFactory, EventAggregator eventAggregator, NotificationSender notificationSender, Logs logs) { _btcPayNetworkProvider = btcPayNetworkProvider; _explorerClientProvider = explorerClientProvider; _jsonSerializerSettings = jsonSerializerSettings; _dbContextFactory = dbContextFactory; _eventAggregator = eventAggregator; _notificationSender = notificationSender; this.Logs = logs; } public bool CanHandle(PaymentMethodId paymentMethod) { return paymentMethod?.PaymentType == BitcoinPaymentType.Instance && _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethod.CryptoCode)?.ReadonlyWallet is false; } public async Task TrackClaim(PaymentMethodId paymentMethodId, IClaimDestination claimDestination) { var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode); var explorerClient = _explorerClientProvider.GetExplorerClient(network); if (claimDestination is IBitcoinLikeClaimDestination bitcoinLikeClaimDestination) await explorerClient.TrackAsync(TrackedSource.Create(bitcoinLikeClaimDestination.Address)); } public Task<(IClaimDestination destination, string error)> ParseClaimDestination(PaymentMethodId paymentMethodId, string destination) { var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode); destination = destination.Trim(); try { if (destination.StartsWith($"{network.NBitcoinNetwork.UriScheme}:", StringComparison.OrdinalIgnoreCase)) { return Task.FromResult<(IClaimDestination, string)>((new UriClaimDestination(new BitcoinUrlBuilder(destination, network.NBitcoinNetwork)), null)); } return Task.FromResult<(IClaimDestination, string)>((new AddressClaimDestination(BitcoinAddress.Create(destination, network.NBitcoinNetwork)), null)); } catch { return Task.FromResult<(IClaimDestination, string)>( (null, "A valid address was not provided")); } } public (bool valid, string error) ValidateClaimDestination(IClaimDestination claimDestination, PullPaymentBlob pullPaymentBlob) { return (true, null); } public IPayoutProof ParseProof(PayoutData payout) { if (payout?.Proof is null) return null; var paymentMethodId = payout.GetPaymentMethodId(); if (paymentMethodId is null) { return null; } var raw = JObject.Parse(Encoding.UTF8.GetString(payout.Proof)); if (raw.TryGetValue("proofType", StringComparison.InvariantCultureIgnoreCase, out var proofType) && proofType.Value<string>() == ManualPayoutProof.Type) { return raw.ToObject<ManualPayoutProof>(); } var res = raw.ToObject<PayoutTransactionOnChainBlob>( JsonSerializer.Create(_jsonSerializerSettings.GetSerializer(paymentMethodId.CryptoCode))); var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode); if (res == null) return null; res.LinkTemplate = network.BlockExplorerLink; return res; } public void StartBackgroundCheck(Action<Type[]> subscribe) { subscribe(new[] { typeof(NewOnChainTransactionEvent), typeof(NewBlockEvent) }); } public async Task BackgroundCheck(object o) { if (o is NewOnChainTransactionEvent newTransaction && newTransaction.NewTransactionEvent.TrackedSource is AddressTrackedSource addressTrackedSource) { await UpdatePayoutsAwaitingForPayment(newTransaction, addressTrackedSource); } if (o is NewBlockEvent || o is NewOnChainTransactionEvent) { await UpdatePayoutsInProgress(); } } public Task<decimal> GetMinimumPayoutAmount(PaymentMethodId paymentMethodId, IClaimDestination claimDestination) { if (_btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode)? .NBitcoinNetwork? .Consensus? .ConsensusFactory? .CreateTxOut() is TxOut txout && claimDestination is IBitcoinLikeClaimDestination bitcoinLikeClaimDestination) { txout.ScriptPubKey = bitcoinLikeClaimDestination.Address.ScriptPubKey; return Task.FromResult(txout.GetDustThreshold().ToDecimal(MoneyUnit.BTC)); } return Task.FromResult(0m); } public Dictionary<PayoutState, List<(string Action, string Text)>> GetPayoutSpecificActions() { return new Dictionary<PayoutState, List<(string Action, string Text)>>() { {PayoutState.AwaitingPayment, new List<(string Action, string Text)>() { ("reject-payment", "Reject payout transaction") }} }; } public async Task<StatusMessageModel> DoSpecificAction(string action, string[] payoutIds, string storeId) { switch (action) { case "mark-paid": await using (var context = _dbContextFactory.CreateContext()) { var payouts = (await context.Payouts .Include(p => p.PullPaymentData) .Include(p => p.PullPaymentData.StoreData) .Where(p => payoutIds.Contains(p.Id)) .Where(p => p.PullPaymentData.StoreId == storeId && !p.PullPaymentData.Archived && p.State == PayoutState.AwaitingPayment) .ToListAsync()).Where(data => PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) && CanHandle(paymentMethodId)) .Select(data => (data, ParseProof(data) as PayoutTransactionOnChainBlob)).Where(tuple => tuple.Item2 != null && tuple.Item2.TransactionId != null && tuple.Item2.Accounted == false); foreach (var valueTuple in payouts) { valueTuple.Item2.Accounted = true; valueTuple.data.State = PayoutState.InProgress; SetProofBlob(valueTuple.data, valueTuple.Item2); } await context.SaveChangesAsync(); } return new StatusMessageModel() { Message = "Payout payments have been marked confirmed", Severity = StatusMessageModel.StatusSeverity.Success }; case "reject-payment": await using (var context = _dbContextFactory.CreateContext()) { var payouts = (await context.Payouts .Include(p => p.PullPaymentData) .Include(p => p.PullPaymentData.StoreData) .Where(p => payoutIds.Contains(p.Id)) .Where(p => p.PullPaymentData.StoreId == storeId && !p.PullPaymentData.Archived && p.State == PayoutState.AwaitingPayment) .ToListAsync()).Where(data => PaymentMethodId.TryParse(data.PaymentMethodId, out var paymentMethodId) && CanHandle(paymentMethodId)) .Select(data => (data, ParseProof(data) as PayoutTransactionOnChainBlob)).Where(tuple => tuple.Item2 != null && tuple.Item2.TransactionId != null && tuple.Item2.Accounted == true); foreach (var valueTuple in payouts) { valueTuple.Item2.TransactionId = null; SetProofBlob(valueTuple.data, valueTuple.Item2); } await context.SaveChangesAsync(); } return new StatusMessageModel() { Message = "Payout payments have been unmarked", Severity = StatusMessageModel.StatusSeverity.Success }; } return null; } public Task<IEnumerable<PaymentMethodId>> GetSupportedPaymentMethods(StoreData storeData) { return Task.FromResult(storeData.GetEnabledPaymentIds(_btcPayNetworkProvider) .Where(id => id.PaymentType == BitcoinPaymentType.Instance)); } public async Task<IActionResult> InitiatePayment(PaymentMethodId paymentMethodId, string[] payoutIds) { await using var ctx = this._dbContextFactory.CreateContext(); ctx.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var pmi = paymentMethodId.ToString(); var payouts = await ctx.Payouts.Include(data => data.PullPaymentData) .Where(data => payoutIds.Contains(data.Id) && pmi == data.PaymentMethodId && data.State == PayoutState.AwaitingPayment) .ToListAsync(); var pullPaymentIds = payouts.Select(data => data.PullPaymentDataId).Distinct().ToArray(); var storeId = payouts.First().PullPaymentData.StoreId; var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(paymentMethodId.CryptoCode); List<string> bip21 = new List<string>(); foreach (var payout in payouts) { if (payout.Proof != null) { continue; } var blob = payout.GetBlob(_jsonSerializerSettings); if (payout.GetPaymentMethodId() != paymentMethodId) continue; var claim = await ParseClaimDestination(paymentMethodId, blob.Destination); switch (claim.destination) { case UriClaimDestination uriClaimDestination: uriClaimDestination.BitcoinUrl.Amount = new Money(blob.CryptoAmount.Value, MoneyUnit.BTC); bip21.Add(uriClaimDestination.ToString()); break; case AddressClaimDestination addressClaimDestination: bip21.Add(network.GenerateBIP21(addressClaimDestination.Address.ToString(), new Money(blob.CryptoAmount.Value, MoneyUnit.BTC)).ToString()); break; } } if (bip21.Any()) return new RedirectToActionResult("WalletSend", "UIWallets", new { walletId = new WalletId(storeId, paymentMethodId.CryptoCode).ToString(), bip21 }); return new RedirectToActionResult("Payouts", "UIWallets", new { walletId = new WalletId(storeId, paymentMethodId.CryptoCode).ToString(), pullPaymentId = pullPaymentIds.Length == 1 ? pullPaymentIds.First() : null }); } private async Task UpdatePayoutsInProgress() { try { await using var ctx = _dbContextFactory.CreateContext(); var payouts = await ctx.Payouts .Include(p => p.PullPaymentData) .Where(p => p.State == PayoutState.InProgress) .ToListAsync(); foreach (var payout in payouts) { var proof = ParseProof(payout) as PayoutTransactionOnChainBlob; var payoutBlob = payout.GetBlob(this._jsonSerializerSettings); if (proof is null || proof.Accounted is false) { continue; } foreach (var txid in proof.Candidates.ToList()) { var explorer = _explorerClientProvider.GetExplorerClient(payout.GetPaymentMethodId().CryptoCode); var tx = await explorer.GetTransactionAsync(txid); if (tx is null) { proof.Candidates.Remove(txid); } else if (tx.Confirmations >= payoutBlob.MinimumConfirmation) { payout.State = PayoutState.Completed; proof.TransactionId = tx.TransactionHash; break; } else { var rebroadcasted = await explorer.BroadcastAsync(tx.Transaction); if (rebroadcasted.RPCCode == RPCErrorCode.RPC_TRANSACTION_ERROR || rebroadcasted.RPCCode == RPCErrorCode.RPC_TRANSACTION_REJECTED) { proof.Candidates.Remove(txid); } else { payout.State = PayoutState.InProgress; proof.TransactionId = tx.TransactionHash; continue; } } } if (proof.TransactionId is null && !proof.Candidates.Contains(proof.TransactionId)) { proof.TransactionId = null; } if (proof.Candidates.Count == 0) { payout.State = PayoutState.AwaitingPayment; } else if (proof.TransactionId is null) { proof.TransactionId = proof.Candidates.First(); } if (payout.State == PayoutState.Completed) proof.Candidates = null; SetProofBlob(payout, proof); } await ctx.SaveChangesAsync(); } catch (Exception ex) { Logs.PayServer.LogWarning(ex, "Error while processing an update in the pull payment hosted service"); } } private async Task UpdatePayoutsAwaitingForPayment(NewOnChainTransactionEvent newTransaction, AddressTrackedSource addressTrackedSource) { try { var network = _btcPayNetworkProvider.GetNetwork<BTCPayNetwork>(newTransaction.CryptoCode); var destinationSum = newTransaction.NewTransactionEvent.Outputs.Sum(output => output.Value.GetValue(network)); var destination = addressTrackedSource.Address.ToString(); var paymentMethodId = new PaymentMethodId(newTransaction.CryptoCode, BitcoinPaymentType.Instance); await using var ctx = _dbContextFactory.CreateContext(); var payouts = await ctx.Payouts .Include(o => o.PullPaymentData) .ThenInclude(o => o.StoreData) .Where(p => p.State == PayoutState.AwaitingPayment) .Where(p => p.PaymentMethodId == paymentMethodId.ToString()) #pragma warning disable CA1307 // Specify StringComparison .Where(p => destination.Equals(p.Destination)) #pragma warning restore CA1307 // Specify StringComparison .ToListAsync(); var payoutByDestination = payouts.ToDictionary(p => p.Destination); if (!payoutByDestination.TryGetValue(destination, out var payout)) return; var payoutBlob = payout.GetBlob(_jsonSerializerSettings); if (payoutBlob.CryptoAmount is null || // The round up here is not strictly necessary, this is temporary to fix existing payout before we // were properly roundup the crypto amount destinationSum != BTCPayServer.Extensions.RoundUp(payoutBlob.CryptoAmount.Value, network.Divisibility)) return; var derivationSchemeSettings = payout.PullPaymentData.StoreData .GetDerivationSchemeSettings(_btcPayNetworkProvider, newTransaction.CryptoCode).AccountDerivation; var storeWalletMatched = (await _explorerClientProvider.GetExplorerClient(newTransaction.CryptoCode) .GetTransactionAsync(derivationSchemeSettings, newTransaction.NewTransactionEvent.TransactionData.TransactionHash)); //if the wallet related to the store related to the payout does not have the tx: it is external var isInternal = storeWalletMatched is { }; var proof = ParseProof(payout) as PayoutTransactionOnChainBlob ?? new PayoutTransactionOnChainBlob() { Accounted = isInternal }; var txId = newTransaction.NewTransactionEvent.TransactionData.TransactionHash; if (!proof.Candidates.Add(txId)) return; if (isInternal) { payout.State = PayoutState.InProgress; var walletId = new WalletId(payout.PullPaymentData.StoreId, newTransaction.CryptoCode); _eventAggregator.Publish(new UpdateTransactionLabel(walletId, newTransaction.NewTransactionEvent.TransactionData.TransactionHash, UpdateTransactionLabel.PayoutTemplate(payout.Id, payout.PullPaymentDataId, walletId.ToString()))); } else { await _notificationSender.SendNotification(new StoreScope(payout.PullPaymentData.StoreId), new ExternalPayoutTransactionNotification() { PaymentMethod = payout.PaymentMethodId, PayoutId = payout.Id, StoreId = payout.PullPaymentData.StoreId }); } proof.TransactionId ??= txId; SetProofBlob(payout, proof); await ctx.SaveChangesAsync(); } catch (Exception ex) { Logs.PayServer.LogWarning(ex, "Error while processing a transaction in the pull payment hosted service"); } } private void SetProofBlob(PayoutData data, PayoutTransactionOnChainBlob blob) { var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(blob, _jsonSerializerSettings.GetSerializer(data.GetPaymentMethodId().CryptoCode))); // We only update the property if the bytes actually changed, this prevent from hammering the DB too much if (data.Proof is null || bytes.Length != data.Proof.Length || !bytes.SequenceEqual(data.Proof)) { data.Proof = bytes; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections; using System.Threading.Tasks; using Microsoft.Azure.Management.HybridCompute.Models; using Microsoft.Azure.Management.HybridCompute.Tests.Helpers; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.Azure.Management.HybridCompute.Tests { public class HybridMachineExtensionTests : TestBase,IDisposable { private const string CUSTOM_SCRIPT_EXTENSION_NAME = "customScript"; private const string DEPENDENCY_AGENT_EXTENSION_NAME = "dependencyAgent"; private const string RESOURCE_GROUP_NAME = "csharp-sdk-test"; private const string MACHINE_NAME = "thinkpad"; private MockContext _context; private HybridComputeManagementClient _client; private Machine _machine; private bool _isLinux; private void Initialize() { _client = this.GetHybridComputeManagementClient(_context); _machine = _client.Machines.Get(RESOURCE_GROUP_NAME, MACHINE_NAME); _isLinux = _machine.OsName.IndexOf("linux", StringComparison.OrdinalIgnoreCase) >= 0; } private void PopulateExtensions() { // Create two extensions if (_isLinux) { MachineExtension extension = new MachineExtension { Location = _machine.Location, Settings = new Hashtable { { "commandToExecute", "echo 'hi'" }, }, TypeHandlerVersion = "2.1", Publisher = "Microsoft.Azure.Extensions", MachineExtensionType = "CustomScript", }; _client.MachineExtensions.CreateOrUpdate(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME, extension); extension = new MachineExtension { Location = _machine.Location, Publisher = "Microsoft.Azure.Monitoring.DependencyAgent", MachineExtensionType = "DependencyAgentLinux", }; _client.MachineExtensions.CreateOrUpdate(RESOURCE_GROUP_NAME, MACHINE_NAME, DEPENDENCY_AGENT_EXTENSION_NAME, extension); } else { MachineExtension extension = new MachineExtension { Location = _machine.Location, Settings = new Hashtable { { "commandToExecute", "echo 'hi'" }, }, TypeHandlerVersion = "1.10", Publisher = "Microsoft.Compute", MachineExtensionType = "CustomScriptExtension", }; _client.MachineExtensions.CreateOrUpdate(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME, extension); extension = new MachineExtension { Location = _machine.Location, Publisher = "Microsoft.Azure.Monitoring.DependencyAgent", MachineExtensionType = "DependencyAgentWindows", }; _client.MachineExtensions.CreateOrUpdate(RESOURCE_GROUP_NAME, MACHINE_NAME, DEPENDENCY_AGENT_EXTENSION_NAME, extension); } } public void Dispose() { foreach (MachineExtension extension in _client.MachineExtensions.List(RESOURCE_GROUP_NAME, MACHINE_NAME)) { _client.MachineExtensions.Delete(RESOURCE_GROUP_NAME, MACHINE_NAME, extension.Name); } _context.Dispose(); } [Fact] public void MachineExtensions_Get() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); MachineExtension extension = _client.MachineExtensions.Get(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME); Assert.Equal(CUSTOM_SCRIPT_EXTENSION_NAME, extension.Name); Assert.Equal(_machine.Location, extension.Location); Assert.NotNull(extension.Settings); } [Fact] public async Task MachineExtensions_GetAsync() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); MachineExtension extension = await _client.MachineExtensions.GetAsync(RESOURCE_GROUP_NAME, MACHINE_NAME, DEPENDENCY_AGENT_EXTENSION_NAME).ConfigureAwait(false); Assert.Equal(DEPENDENCY_AGENT_EXTENSION_NAME, extension.Name); Assert.Equal(_machine.Location, extension.Location); Assert.Equal("Microsoft.Azure.Monitoring.DependencyAgent", extension.Publisher); } [Fact] public void MachineExtensions_List() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); IPage<MachineExtension> extensions = _client.MachineExtensions.List(RESOURCE_GROUP_NAME, MACHINE_NAME); Assert.Collection(extensions, customScript => { Assert.Equal(CUSTOM_SCRIPT_EXTENSION_NAME, customScript.Name); Assert.Equal(_machine.Location, customScript.Location); Assert.NotNull(customScript.Settings); }, dependencyAgent => { Assert.Equal(DEPENDENCY_AGENT_EXTENSION_NAME, dependencyAgent.Name); Assert.Equal(_machine.Location, dependencyAgent.Location); Assert.Equal("Microsoft.Azure.Monitoring.DependencyAgent", dependencyAgent.Publisher); }); } [Fact] public async Task MachineExtensions_ListAsync() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); IPage<MachineExtension> extensions = await _client.MachineExtensions.ListAsync(RESOURCE_GROUP_NAME, MACHINE_NAME).ConfigureAwait(false); Assert.Collection(extensions, customScript => { Assert.Equal(CUSTOM_SCRIPT_EXTENSION_NAME, customScript.Name); Assert.Equal(_machine.Location, customScript.Location); Assert.NotNull(customScript.Settings); }, dependencyAgent => { Assert.Equal(DEPENDENCY_AGENT_EXTENSION_NAME, dependencyAgent.Name); Assert.Equal(_machine.Location, dependencyAgent.Location); Assert.Equal("Microsoft.Azure.Monitoring.DependencyAgent", dependencyAgent.Publisher); }); } [Fact] public void MachineExtensions_CreateOrUpdate() { _context = MockContext.Start(GetType().FullName); Initialize(); const string extensionName = "custom"; MachineExtension extension = _isLinux ? new MachineExtension { Location = _machine.Location, Settings = new Hashtable { { "commandToExecute", "echo 'hi'" }, }, TypeHandlerVersion = "2.1", Publisher = "Microsoft.Azure.Extensions", MachineExtensionType = "CustomScript", } : new MachineExtension { Location = _machine.Location, Settings = new Hashtable { { "commandToExecute", "echo 'hi'" }, }, TypeHandlerVersion = "1.10", Publisher = "Microsoft.Compute", MachineExtensionType = "CustomScriptExtension", }; MachineExtension extensionFromCreate = _client.MachineExtensions.CreateOrUpdate(RESOURCE_GROUP_NAME, MACHINE_NAME, extensionName, extension); Assert.Equal(extensionName, extensionFromCreate.Name); Assert.Equal(_machine.Location, extensionFromCreate.Location); Assert.Equal("echo 'hi'", ((JObject) extensionFromCreate.Settings).Value<string>("commandToExecute")); MachineExtension extensionFromGet = _client.MachineExtensions.Get(RESOURCE_GROUP_NAME, MACHINE_NAME, extensionName); Assert.Equal(extensionName, extensionFromGet.Name); Assert.Equal(_machine.Location, extensionFromGet.Location); Assert.Equal("echo 'hi'", ((JObject) extensionFromGet.Settings).Value<string>("commandToExecute")); } [Fact] public async Task MachineExtensions_CreateOrUpdateAsync() { _context = MockContext.Start(GetType().FullName); Initialize(); const string extensionName = "custom"; MachineExtension extension = _isLinux ? new MachineExtension { Location = _machine.Location, Settings = new Hashtable { { "commandToExecute", "echo 'hi'" }, }, TypeHandlerVersion = "2.1", Publisher = "Microsoft.Azure.Extensions", MachineExtensionType = "CustomScript", } : new MachineExtension { Location = _machine.Location, Settings = new Hashtable { { "commandToExecute", "echo 'hi'" }, }, TypeHandlerVersion = "1.10", Publisher = "Microsoft.Compute", MachineExtensionType = "CustomScriptExtension", }; MachineExtension extensionFromCreate = await _client.MachineExtensions.CreateOrUpdateAsync(RESOURCE_GROUP_NAME, MACHINE_NAME, extensionName, extension).ConfigureAwait(false); Assert.Equal(extensionName, extensionFromCreate.Name); Assert.Equal(_machine.Location, extensionFromCreate.Location); Assert.Equal("echo 'hi'", ((JObject) extensionFromCreate.Settings).Value<string>("commandToExecute")); MachineExtension extensionFromGet = await _client.MachineExtensions.GetAsync(RESOURCE_GROUP_NAME, MACHINE_NAME, extensionName).ConfigureAwait(false); Assert.Equal(extensionName, extensionFromGet.Name); Assert.Equal(_machine.Location, extensionFromGet.Location); Assert.Equal("echo 'hi'", ((JObject) extensionFromGet.Settings).Value<string>("commandToExecute")); } [Fact] public void MachineExtensions_Delete() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); _client.MachineExtensions.Delete(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME); Assert.Throws<CloudException>(() => _client.MachineExtensions.Get(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME)); } [Fact] public async Task MachineExtensions_DeleteAsync() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); await _client.MachineExtensions.DeleteAsync(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME).ConfigureAwait(false); Assert.Throws<CloudException>(() => _client.MachineExtensions.Get(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME)); } [Fact] public void MachineExtensions_Update() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); const string newCommand = "echo 'goodbye'"; MachineExtensionUpdate extensionUpdate = _isLinux ? new MachineExtensionUpdate { Settings = new Hashtable { { "commandToExecute", newCommand }, }, } : new MachineExtensionUpdate { Settings = new Hashtable { { "commandToExecute", newCommand }, }, }; MachineExtension extension = _client.MachineExtensions.Update(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME, extensionUpdate); Assert.Equal(newCommand, ((JObject) extension.Settings).Value<string>("commandToExecute")); } [Fact] public async Task MachineExtensions_UpdateAsync() { _context = MockContext.Start(GetType().FullName); Initialize(); PopulateExtensions(); const string newCommand = "echo 'goodbye'"; MachineExtensionUpdate extensionUpdate = _isLinux ? new MachineExtensionUpdate { Settings = new Hashtable { { "commandToExecute", newCommand }, }, } : new MachineExtensionUpdate { Settings = new Hashtable { { "commandToExecute", newCommand }, }, }; MachineExtension extension = await _client.MachineExtensions.UpdateAsync(RESOURCE_GROUP_NAME, MACHINE_NAME, CUSTOM_SCRIPT_EXTENSION_NAME, extensionUpdate).ConfigureAwait(false); Assert.Equal(newCommand, ((JObject) extension.Settings).Value<string>("commandToExecute")); } } }
// 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.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; namespace System.Diagnostics { /// <summary>Base class used for all tests that need to spawn a remote process.</summary> public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase { /// <summary>A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.</summary> public const int FailWaitTimeoutMilliseconds = 60 * 1000; /// <summary>The exit code returned when the test process exits successfully.</summary> public const int SuccessExitCode = 42; /// <summary>The name of the test console app.</summary> protected static readonly string TestConsoleApp = "RemoteExecutorConsoleApp.exe"; /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Action method, RemoteInvokeOptions options = null) { // There's no exit code to check options = options ?? new RemoteInvokeOptions(); options.CheckExitCode = false; return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<int> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<Task<int>> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg">The argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, Task<int>> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, Task<int>> method, string arg1, string arg2, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg">The argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, int> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, int> method, string arg1, string arg2, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, int> method, string arg1, string arg2, string arg3, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="arg5">The fifth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, string arg5, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="args">The arguments to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false); } private static MethodInfo GetMethodInfo(Delegate d) { // RemoteInvoke doesn't support marshaling state on classes associated with // the delegate supplied (often a display class of a lambda). If such fields // are used, odd errors result, e.g. NullReferenceExceptions during the remote // execution. Try to ward off the common cases by proactively failing early // if it looks like such fields are needed. if (d.Target != null) { // The only fields on the type should be compiler-defined (any fields of the compiler's own // making generally include '<' and '>', as those are invalid in C# source). Note that this logic // may need to be revised in the future as the compiler changes, as this relies on the specifics of // actually how the compiler handles lifted fields for lambdas. Type targetType = d.Target.GetType(); Assert.All( targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}")); } return d.GetMethodInfo(); } /// <summary>A cleanup handle to the Process created for the remote invocation.</summary> public sealed class RemoteInvokeHandle : IDisposable { public RemoteInvokeHandle(Process process, RemoteInvokeOptions options, string assemblyName = null, string className = null, string methodName = null) { Process = process; Options = options; AssemblyName = assemblyName; ClassName = className; MethodName = methodName; } public Process Process { get; set; } public RemoteInvokeOptions Options { get; private set; } public string AssemblyName { get; private set; } public string ClassName { get; private set; } public string MethodName { get; private set; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { Assert.True(disposing, $"A test {AssemblyName}!{ClassName}.{MethodName} forgot to Dispose() the result of RemoteInvoke()"); if (Process != null) { // A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid // needing to do this in every derived test and keep each test much simpler. try { Assert.True(Process.WaitForExit(Options.TimeOut), $"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}"); if (File.Exists(Options.ExceptionFile)) { throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile)); } if (Options.CheckExitCode) { int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode); int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode); Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}"); } } finally { if (File.Exists(Options.ExceptionFile)) { File.Delete(Options.ExceptionFile); } // Cleanup try { Process.Kill(); } catch { } // ignore all cleanup errors Process.Dispose(); Process = null; } } } // https://github.com/dotnet/corefx/issues/27366 //~RemoteInvokeHandle() //{ // Finalizer flags tests that omitted the explicit Dispose() call; they must have it, or they aren't // waiting on the remote execution // Dispose(disposing: false); //} private sealed class RemoteExecutionException : XunitException { internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { } } } } /// <summary>Options used with RemoteInvoke.</summary> public sealed class RemoteInvokeOptions { private bool _runAsSudo; public bool Start { get; set; } = true; public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo(); public bool EnableProfiling { get; set; } = true; public bool CheckExitCode { get; set; } = true; public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds; public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode; public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); public bool RunAsSudo { get { return _runAsSudo; } set { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { throw new PlatformNotSupportedException(); } _runAsSudo = value; } } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Data.SqlClient; using System.Collections; using System.Collections.Generic; using DSL.POS.DataAccessLayer.Common.Imp; using DSL.POS.DataAccessLayer.Interface; using DSL.POS.DTO.DTO; using DSL.POS.Common.Utility; namespace DSL.POS.DataAccessLayer.Imp { /// <summary> /// Summary description for ProductCategoryBLImp /// </summary> /// public class ProductCategoryDALImp : CommonDALImp, IProductCategoryDAL { // Error Handling Developed By Samad // 05/12/06 ClsErrorHandle cls = new ClsErrorHandle(); private void getPKCode(ProductCategoryInfoDTO obj) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); string strPKCode = null; int PKSL = 0; string sqlSelect = "Select isnull(Max(PC_Code),0)+1 From ProductCategoryInfo"; SqlCommand objCmd = sqlConn.CreateCommand(); objCmd.CommandText = sqlSelect; try { sqlConn.Open(); PKSL = (int)objCmd.ExecuteScalar(); } catch(Exception Exp) { throw Exp; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } strPKCode = PKSL.ToString("00"); obj.PC_Code = strPKCode; } public override void Save(object obj) { ProductCategoryInfoDTO oProductCategoryInfoDTO = (ProductCategoryInfoDTO)obj; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); if (oProductCategoryInfoDTO.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { String sql = "Insert Into ProductCategoryInfo(PC_Code,PC_Description,EntryBy,EntryDate) values(@PC_Code,@PC_Description,@EntryBy,@EntryDate)"; try { getPKCode(oProductCategoryInfoDTO); objCmd.CommandText = sql; objCmd.Parameters.Add(new SqlParameter("@PC_Code", SqlDbType.VarChar, 2)); objCmd.Parameters.Add(new SqlParameter("@PC_Description", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 5)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime)); objCmd.Parameters["@PC_Code"].Value = Convert.ToString(oProductCategoryInfoDTO.PC_Code); objCmd.Parameters["@PC_Description"].Value = Convert.ToString(oProductCategoryInfoDTO.PC_Description); objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oProductCategoryInfoDTO.EntryBy); objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oProductCategoryInfoDTO.EntryDate); sqlConn.Open(); objCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Close(); sqlConn.Dispose(); } } else { String sql = "Update ProductCategoryInfo set PC_Description=@PC_Description,EntryBy=@EntryBy,EntryDate=@EntryDate where PC_PK=@PC_PK "; try { objCmd.CommandText = sql; objCmd.Parameters.Add("@PC_Description", SqlDbType.VarChar, 50); objCmd.Parameters.Add("@EntryBy", SqlDbType.VarChar, 50); objCmd.Parameters.Add("@EntryDate", SqlDbType.DateTime); objCmd.Parameters.Add("@PC_PK", SqlDbType.UniqueIdentifier, 16); objCmd.Parameters["@PC_Description"].Value = Convert.ToString(oProductCategoryInfoDTO.PC_Description); objCmd.Parameters["@EntryBy"].Value = Convert.ToString(oProductCategoryInfoDTO.EntryBy); objCmd.Parameters["@EntryDate"].Value = Convert.ToDateTime(oProductCategoryInfoDTO.EntryDate); objCmd.Parameters["@PC_PK"].Value = (Guid)oProductCategoryInfoDTO.PrimaryKey; sqlConn.Open(); objCmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } } } public ProductCategoryDALImp() { // // TODO: Add constructor logic here // } public override void Delete(object obj) { ProductCategoryInfoDTO oProductCategoryInfoDTO = (ProductCategoryInfoDTO)obj; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); String sql = "Delete ProductCategoryInfo where PC_PK=@PC_PK "; SqlCommand objCmdDelete = sqlConn.CreateCommand(); objCmdDelete.CommandText = sql; try { objCmdDelete.Parameters.Add("@PC_PK", SqlDbType.UniqueIdentifier, 16); objCmdDelete.Parameters["@PC_PK"].Value = (Guid)oProductCategoryInfoDTO.PrimaryKey; sqlConn.Open(); objCmdDelete.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } finally { objCmdDelete.Dispose(); objCmdDelete.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } } public List<ProductCategoryInfoDTO> GetProductCategoryInfo() { List<ProductCategoryInfoDTO> productCategoriList = new List<ProductCategoryInfoDTO>(); SqlConnection objmycon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objcmd = new SqlCommand(); SqlDataReader DR; objcmd.Connection = objmycon; objcmd.CommandText = "SELECT PC_PK, PC_Code, PC_Description,EntryBy,EntryDate FROM ProductCategoryInfo ORDER BY PC_Code"; try { objmycon.Open(); DR = objcmd.ExecuteReader(); while (DR.Read()) { ProductCategoryInfoDTO ProcInfo = new ProductCategoryInfoDTO();//(Guid)DR[0],(string)DR[1],(string)DR[1]); ProcInfo.PrimaryKey = (Guid)DR[0]; ProcInfo.PC_Code = (string)DR[1]; ProcInfo.PC_Description = (string)DR[2]; productCategoriList.Add(ProcInfo); } DR.Close(); } catch (Exception Exp) { throw Exp; } finally { objmycon.Close(); } return productCategoriList; } public ProductCategoryInfoDTO FindByPK(Guid pk) { ProductCategoryInfoDTO pcDTO = new ProductCategoryInfoDTO(); string sqlSelect = "SELECT PC_PK, PC_Code, PC_Description,EntryBy,EntryDate FROM ProductCategoryInfo WHERE PC_PK=@PC_PK"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); try { objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; objCmd.Parameters.Add("@PC_PK", SqlDbType.UniqueIdentifier, 16); objCmd.Parameters["@PC_PK"].Value = pk; sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { pcDTO = Populate(thisReader); } thisReader.Close(); thisReader.Dispose(); } catch (Exception Exp) { throw Exp; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return pcDTO; } public ProductCategoryInfoDTO Populate(SqlDataReader reader) { try { ProductCategoryInfoDTO dto = new ProductCategoryInfoDTO(); dto.PrimaryKey = (Guid)reader["PC_PK"]; dto.PC_Code = (string)reader["PC_Code"]; dto.PC_Description = (string)reader["PC_Description"]; dto.EntryBy = (string)reader["EntryBy"]; dto.EntryDate = (DateTime)reader["EntryDate"]; return dto; } catch (Exception Exp) { throw Exp; } } } }
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 SampleServer.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
//------------------------------------------------------------------------------ // <copyright file="ColumnBinding.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.OleDb { using System; using System.Diagnostics; using System.Data; using System.Data.Common; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; sealed internal class ColumnBinding { // shared with other ColumnBindings private readonly OleDbDataReader _dataReader; // HCHAPTER private readonly RowBinding _rowbinding; // for native buffer interaction private readonly Bindings _bindings; // unique to this ColumnBinding private readonly OleDbParameter _parameter; // output value private readonly int _parameterChangeID; private readonly int _offsetStatus; private readonly int _offsetLength; private readonly int _offsetValue; private readonly int _ordinal; private readonly int _maxLen; private readonly short _wType; private readonly byte _precision; private readonly int _index; private readonly int _indexForAccessor; // HCHAPTER private readonly int _indexWithinAccessor; // HCHAPTER private readonly bool _ifIRowsetElseIRow; // unique per current input value private int _valueBindingOffset; private int _valueBindingSize; internal StringMemHandle _sptr; private GCHandle _pinnedBuffer; // value is cached via property getters so the original may be released // for Value, ValueByteArray, ValueString, ValueVariant private object _value; internal ColumnBinding(OleDbDataReader dataReader, int index, int indexForAccessor, int indexWithinAccessor, OleDbParameter parameter, RowBinding rowbinding, Bindings bindings, tagDBBINDING binding, int offset, bool ifIRowsetElseIRow) { Debug.Assert(null != rowbinding, "null rowbinding"); Debug.Assert(null != bindings, "null bindings"); Debug.Assert(ODB.SizeOf_tagDBBINDING <= offset, "invalid offset" + offset); _dataReader = dataReader; _rowbinding = rowbinding; _bindings = bindings; _index = index; _indexForAccessor = indexForAccessor; _indexWithinAccessor = indexWithinAccessor; if (null != parameter) { _parameter = parameter; _parameterChangeID = parameter.ChangeID; } _offsetStatus = binding.obStatus.ToInt32() + offset; _offsetLength = binding.obLength.ToInt32() + offset; _offsetValue = binding.obValue.ToInt32() + offset; Debug.Assert(0 <= _offsetStatus, "negative _offsetStatus"); Debug.Assert(0 <= _offsetLength, "negative _offsetLength"); Debug.Assert(0 <= _offsetValue, "negative _offsetValue"); _ordinal = binding.iOrdinal.ToInt32(); _maxLen = binding.cbMaxLen.ToInt32(); _wType = binding.wType; _precision = binding.bPrecision; _ifIRowsetElseIRow = ifIRowsetElseIRow; SetSize(Bindings.ParamSize.ToInt32()); } internal Bindings Bindings { get { _bindings.CurrentIndex = IndexWithinAccessor; return _bindings; } } internal RowBinding RowBinding { get { return _rowbinding; } } internal int ColumnBindingOrdinal { get { return _ordinal; } } private int ColumnBindingMaxLen { get { return _maxLen; } } private byte ColumnBindingPrecision { get { return _precision; } } private short DbType { get { return _wType; } } private Type ExpectedType { get { return NativeDBType.FromDBType(DbType, false, false).dataType; } } internal int Index { get { return _index; } } internal int IndexForAccessor { get { return _indexForAccessor; } } internal int IndexWithinAccessor { get { return _indexWithinAccessor; } } private int ValueBindingOffset { // offset within the value of where to start copying get { return _valueBindingOffset; } } private int ValueBindingSize { // maximum size of the value to copy get { return _valueBindingSize; } } internal int ValueOffset { // offset within the native buffer to put the value get { return _offsetValue; } } private OleDbDataReader DataReader() { Debug.Assert(null != _dataReader, "null DataReader"); return _dataReader; } internal bool IsParameterBindingInvalid(OleDbParameter parameter) { Debug.Assert((null != _parameter) && (null != parameter), "null parameter"); return ((_parameter.ChangeID != _parameterChangeID) || (_parameter != parameter)); } internal bool IsValueNull() { return ((DBStatus.S_ISNULL == StatusValue()) || (((NativeDBType.VARIANT == DbType) || (NativeDBType.PROPVARIANT == DbType)) && (Convert.IsDBNull(ValueVariant())))); } private int LengthValue() { int length; if (_ifIRowsetElseIRow) { length = RowBinding.ReadIntPtr(_offsetLength).ToInt32(); } else { // WebData 94427 length = Bindings.DBColumnAccess[IndexWithinAccessor].cbDataLen.ToInt32(); } return Math.Max(length, 0); } private void LengthValue(int value) { Debug.Assert(0 <= value, "negative LengthValue"); RowBinding.WriteIntPtr(_offsetLength, (IntPtr)value); } internal OleDbParameter Parameter() { Debug.Assert(null != _parameter, "null parameter"); return _parameter; } internal void ResetValue() { _value = null; StringMemHandle sptr = _sptr; _sptr = null; if (null != sptr) { sptr.Dispose(); } if (_pinnedBuffer.IsAllocated) { _pinnedBuffer.Free(); } } internal DBStatus StatusValue() { if (_ifIRowsetElseIRow) { return (DBStatus) RowBinding.ReadInt32(_offsetStatus); } else { // WebData 94427 return (DBStatus) Bindings.DBColumnAccess[IndexWithinAccessor].dwStatus; } } internal void StatusValue(DBStatus value) { #if DEBUG switch(value) { case DBStatus.S_OK: case DBStatus.S_ISNULL: case DBStatus.S_DEFAULT: break; default: Debug.Assert(false, "unexpected StatusValue"); break; } #endif RowBinding.WriteInt32(_offsetStatus, (int)value); } internal void SetOffset(int offset) { if (0 > offset) { throw ADP.InvalidOffsetValue(offset); } _valueBindingOffset = Math.Max(offset, 0); } internal void SetSize(int size) { _valueBindingSize = Math.Max(size, 0); } private void SetValueDBNull() { LengthValue(0); StatusValue(DBStatus.S_ISNULL); RowBinding.WriteInt64(ValueOffset, 0); // safe because AlignDataSize forces 8 byte blocks } private void SetValueEmpty() { LengthValue(0); StatusValue(DBStatus.S_DEFAULT); RowBinding.WriteInt64(ValueOffset, 0); // safe because AlignDataSize forces 8 byte blocks } internal Object Value() { object value = _value; if (null == value) { switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.EMPTY: case NativeDBType.NULL: value = DBNull.Value; break; case NativeDBType.I2: value = Value_I2(); // Int16 break; case NativeDBType.I4: value = Value_I4(); // Int32 break; case NativeDBType.R4: value = Value_R4(); // Single break; case NativeDBType.R8: value = Value_R8(); // Double break; case NativeDBType.CY: value = Value_CY(); // Decimal break; case NativeDBType.DATE: value = Value_DATE(); // DateTime break; case NativeDBType.BSTR: value = Value_BSTR(); // String break; case NativeDBType.IDISPATCH: value = Value_IDISPATCH(); // Object break; case NativeDBType.ERROR: value = Value_ERROR(); // Int32 break; case NativeDBType.BOOL: value = Value_BOOL(); // Boolean break; case NativeDBType.VARIANT: value = Value_VARIANT(); // Object break; case NativeDBType.IUNKNOWN: value = Value_IUNKNOWN(); // Object break; case NativeDBType.DECIMAL: value = Value_DECIMAL(); // Decimal break; case NativeDBType.I1: value = (short) Value_I1(); // SByte->Int16 break; case NativeDBType.UI1: value = Value_UI1(); // Byte break; case NativeDBType.UI2: value = (int) Value_UI2(); // UInt16->Int32 break; case NativeDBType.UI4: value = (long) Value_UI4(); // UInt32->Int64 break; case NativeDBType.I8: value = Value_I8(); // Int64 break; case NativeDBType.UI8: value = (Decimal) Value_UI8(); // UInt64->Decimal break; case NativeDBType.FILETIME: value = Value_FILETIME(); // DateTime break; case NativeDBType.GUID: value = Value_GUID(); // Guid break; case NativeDBType.BYTES: value = Value_BYTES(); // Byte[] break; case NativeDBType.WSTR: value = Value_WSTR(); // String break; case NativeDBType.NUMERIC: value = Value_NUMERIC(); // Decimal break; case NativeDBType.DBDATE: value = Value_DBDATE(); // DateTime break; case NativeDBType.DBTIME: value = Value_DBTIME(); // TimeSpan break; case NativeDBType.DBTIMESTAMP: value = Value_DBTIMESTAMP(); // DateTime break; case NativeDBType.PROPVARIANT: value = Value_VARIANT(); // Object break; case NativeDBType.HCHAPTER: value = Value_HCHAPTER(); // OleDbDataReader break; case (NativeDBType.BYREF | NativeDBType.BYTES): value = Value_ByRefBYTES(); break; case (NativeDBType.BYREF | NativeDBType.WSTR): value = Value_ByRefWSTR(); break; default: throw ODB.GVtUnknown(DbType); #if DEBUG case NativeDBType.STR: Debug.Assert(false, "should have bound as WSTR"); goto default; case NativeDBType.VARNUMERIC: Debug.Assert(false, "should have bound as NUMERIC"); goto default; case NativeDBType.UDT: Debug.Assert(false, "UDT binding should not have been encountered"); goto default; case (NativeDBType.BYREF | NativeDBType.STR): Debug.Assert(false, "should have bound as BYREF|WSTR"); goto default; #endif } break; case DBStatus.S_TRUNCATED: switch(DbType) { case NativeDBType.BYTES: value = Value_BYTES(); break; case NativeDBType.WSTR: value = Value_WSTR(); break; case (NativeDBType.BYREF | NativeDBType.BYTES): value = Value_ByRefBYTES(); break; case (NativeDBType.BYREF | NativeDBType.WSTR): value = Value_ByRefWSTR(); break; default: throw ODB.GVtUnknown(DbType); #if DEBUG case NativeDBType.STR: Debug.Assert(false, "should have bound as WSTR"); goto default; case (NativeDBType.BYREF | NativeDBType.STR): Debug.Assert(false, "should have bound as BYREF|WSTR"); goto default; #endif } break; case DBStatus.S_ISNULL: case DBStatus.S_DEFAULT: value = DBNull.Value; break; default: throw CheckTypeValueStatusValue(); // MDAC 71644 } _value = value; } return value; } internal void Value(object value) { if (null == value) { SetValueEmpty(); } else if (Convert.IsDBNull(value)) { SetValueDBNull(); } else switch (DbType) { case NativeDBType.EMPTY: SetValueEmpty(); break; case NativeDBType.NULL: // language null - no representation, use DBNull SetValueDBNull(); break; case NativeDBType.I2: Value_I2((Int16) value); break; case NativeDBType.I4: Value_I4((Int32) value); break; case NativeDBType.R4: Value_R4((Single) value); break; case NativeDBType.R8: Value_R8((Double) value); break; case NativeDBType.CY: Value_CY((Decimal) value); break; case NativeDBType.DATE: Value_DATE((DateTime) value); break; case NativeDBType.BSTR: Value_BSTR((String) value); break; case NativeDBType.IDISPATCH: Value_IDISPATCH(value); break; case NativeDBType.ERROR: Value_ERROR((Int32) value); break; case NativeDBType.BOOL: Value_BOOL((Boolean) value); break; case NativeDBType.VARIANT: Value_VARIANT(value); break; case NativeDBType.IUNKNOWN: Value_IUNKNOWN(value); break; case NativeDBType.DECIMAL: Value_DECIMAL((Decimal) value); break; case NativeDBType.I1: if (value is Int16) { // MDAC 60430 Value_I1(Convert.ToSByte((Int16)value, CultureInfo.InvariantCulture)); } else { Value_I1((SByte) value); } break; case NativeDBType.UI1: Value_UI1((Byte) value); break; case NativeDBType.UI2: if (value is Int32) { Value_UI2(Convert.ToUInt16((Int32)value, CultureInfo.InvariantCulture)); } else { Value_UI2((UInt16) value); } break; case NativeDBType.UI4: if (value is Int64) { Value_UI4(Convert.ToUInt32((Int64)value, CultureInfo.InvariantCulture)); } else { Value_UI4((UInt32) value); } break; case NativeDBType.I8: Value_I8((Int64) value); break; case NativeDBType.UI8: if (value is Decimal) { Value_UI8(Convert.ToUInt64((Decimal)value, CultureInfo.InvariantCulture)); } else { Value_UI8((UInt64) value); } break; case NativeDBType.FILETIME: Value_FILETIME((DateTime) value); break; case NativeDBType.GUID: Value_GUID((Guid) value); break; case NativeDBType.BYTES: Value_BYTES((Byte[]) value); break; case NativeDBType.WSTR: if (value is string) { Value_WSTR((String) value); } else { Value_WSTR((char[]) value); } break; case NativeDBType.NUMERIC: Value_NUMERIC((Decimal) value); break; case NativeDBType.DBDATE: Value_DBDATE((DateTime) value); break; case NativeDBType.DBTIME: Value_DBTIME((TimeSpan) value); break; case NativeDBType.DBTIMESTAMP: Value_DBTIMESTAMP((DateTime) value); break; case NativeDBType.PROPVARIANT: Value_VARIANT(value); break; case (NativeDBType.BYREF | NativeDBType.BYTES): Value_ByRefBYTES((Byte[]) value); break; case (NativeDBType.BYREF | NativeDBType.WSTR): if (value is string) { Value_ByRefWSTR((String) value); } else { Value_ByRefWSTR((char[])value); } break; default: Debug.Assert(false, "unknown DBTYPE"); throw ODB.SVtUnknown(DbType); #if DEBUG case NativeDBType.STR: Debug.Assert(false, "Should have bound as WSTR"); goto default; case NativeDBType.UDT: Debug.Assert(false, "UDT binding should not have been encountered"); goto default; case NativeDBType.HCHAPTER: Debug.Assert(false, "not allowed to set HCHAPTER"); goto default; case NativeDBType.VARNUMERIC: Debug.Assert(false, "should have bound as NUMERIC"); goto default; case (NativeDBType.BYREF | NativeDBType.STR): Debug.Assert(false, "should have bound as BYREF|WSTR"); goto default; #endif } } internal Boolean Value_BOOL() { Debug.Assert((NativeDBType.BOOL == DbType), "Value_BOOL"); Debug.Assert((DBStatus.S_OK == StatusValue()), "Value_BOOL"); Int16 value = RowBinding.ReadInt16(ValueOffset); return (0 != value); } private void Value_BOOL(Boolean value) { Debug.Assert((NativeDBType.BOOL == DbType), "Value_BOOL"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt16(ValueOffset, (short)(value ? ODB.VARIANT_TRUE : ODB.VARIANT_FALSE)); } private String Value_BSTR() { Debug.Assert((NativeDBType.BSTR == DbType), "Value_BSTR"); Debug.Assert((DBStatus.S_OK == StatusValue()), "Value_BSTR"); string value = ""; RowBinding bindings = RowBinding; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { bindings.DangerousAddRef(ref mustRelease); IntPtr ptr = bindings.ReadIntPtr(ValueOffset); if (ADP.PtrZero != ptr) { value = Marshal.PtrToStringBSTR(ptr); } } finally { if (mustRelease) { bindings.DangerousRelease(); } } return value; } private void Value_BSTR(String value) { Debug.Assert((null != value), "Value_BSTR null"); Debug.Assert((NativeDBType.BSTR == DbType), "Value_BSTR"); LengthValue(value.Length * 2); /* bytecount*/ StatusValue(DBStatus.S_OK); RowBinding.SetBstrValue(ValueOffset, value); } private Byte[] Value_ByRefBYTES() { Debug.Assert(((NativeDBType.BYREF | NativeDBType.BYTES) == DbType), "Value_ByRefBYTES"); Debug.Assert((DBStatus.S_OK == StatusValue()), "Value_ByRefBYTES"); byte[] value = null; RowBinding bindings = RowBinding; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { bindings.DangerousAddRef(ref mustRelease); IntPtr ptr = bindings.ReadIntPtr(ValueOffset); if (ADP.PtrZero != ptr) { value = new byte[LengthValue()]; Marshal.Copy(ptr, value, 0, value.Length); } } finally { if (mustRelease) { bindings.DangerousRelease(); } } return ((null != value) ? value : new byte[0]); } private void Value_ByRefBYTES(Byte[] value) { Debug.Assert(null != value, "Value_ByRefBYTES null"); Debug.Assert((NativeDBType.BYREF | NativeDBType.BYTES) == DbType, "Value_ByRefBYTES"); // we expect the provider/server to apply the silent truncation when binding BY_REF // if (value.Length < ValueBindingOffset) { throw "Offset must refer to a location within the value" } int length = ((ValueBindingOffset < value.Length) ? (value.Length - ValueBindingOffset) : 0); LengthValue(((0 < ValueBindingSize) ? Math.Min(ValueBindingSize, length) : length)); StatusValue(DBStatus.S_OK); IntPtr ptr = ADP.PtrZero; if (0 < length) { // avoid pinning empty byte[] _pinnedBuffer = GCHandle.Alloc(value, GCHandleType.Pinned); ptr = _pinnedBuffer.AddrOfPinnedObject(); ptr = ADP.IntPtrOffset(ptr, ValueBindingOffset); } RowBinding.SetByRefValue(ValueOffset, ptr); } private String Value_ByRefWSTR() { Debug.Assert((NativeDBType.BYREF | NativeDBType.WSTR) == DbType, "Value_ByRefWSTR"); Debug.Assert((DBStatus.S_OK == StatusValue()) || (DBStatus.S_TRUNCATED == StatusValue()), "Value_ByRefWSTR"); string value = ""; RowBinding bindings = RowBinding; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { bindings.DangerousAddRef(ref mustRelease); IntPtr ptr = bindings.ReadIntPtr(ValueOffset); if (ADP.PtrZero != ptr) { int charCount = LengthValue() / 2; value = Marshal.PtrToStringUni(ptr, charCount); } } finally { if (mustRelease) { bindings.DangerousRelease(); } } return value; } private void Value_ByRefWSTR(String value) { Debug.Assert(null != value, "Value_ByRefWSTR null"); Debug.Assert((NativeDBType.BYREF | NativeDBType.WSTR) == DbType, "Value_ByRefWSTR"); // we expect the provider/server to apply the silent truncation when binding BY_REF // if (value.Length < ValueBindingOffset) { throw "Offset must refer to a location within the value" } int length = ((ValueBindingOffset < value.Length) ? (value.Length - ValueBindingOffset) : 0); LengthValue(((0 < ValueBindingSize) ? Math.Min(ValueBindingSize, length) : length) * 2); /* charcount->bytecount*/ StatusValue(DBStatus.S_OK); IntPtr ptr = ADP.PtrZero; if (0 < length) { // avoid pinning empty string, i.e String.Empty _pinnedBuffer = GCHandle.Alloc(value, GCHandleType.Pinned); ptr = _pinnedBuffer.AddrOfPinnedObject(); ptr = ADP.IntPtrOffset(ptr, ValueBindingOffset); } RowBinding.SetByRefValue(ValueOffset, ptr); } private void Value_ByRefWSTR(char[] value) { Debug.Assert(null != value, "Value_ByRefWSTR null"); Debug.Assert((NativeDBType.BYREF | NativeDBType.WSTR) == DbType, "Value_ByRefWSTR"); // we expect the provider/server to apply the silent truncation when binding BY_REF // if (value.Length < ValueBindingOffset) { throw "Offset must refer to a location within the value" } int length = ((ValueBindingOffset < value.Length) ? (value.Length - ValueBindingOffset) : 0); LengthValue(((0 < ValueBindingSize) ? Math.Min(ValueBindingSize, length) : length) * 2); /* charcount->bytecount*/ StatusValue(DBStatus.S_OK); IntPtr ptr = ADP.PtrZero; if (0 < length) { // avoid pinning empty char[] _pinnedBuffer = GCHandle.Alloc(value, GCHandleType.Pinned); ptr = _pinnedBuffer.AddrOfPinnedObject(); ptr = ADP.IntPtrOffset(ptr, ValueBindingOffset); } RowBinding.SetByRefValue(ValueOffset, ptr); } private Byte[] Value_BYTES() { Debug.Assert(NativeDBType.BYTES == DbType, "Value_BYTES"); Debug.Assert((DBStatus.S_OK == StatusValue()) || (DBStatus.S_TRUNCATED == StatusValue()), "Value_BYTES"); int byteCount = Math.Min(LengthValue(), ColumnBindingMaxLen); byte[] value = new byte[byteCount]; RowBinding.ReadBytes(ValueOffset, value, 0, byteCount); return value; } private void Value_BYTES(Byte[] value) { Debug.Assert(null != value, "Value_BYTES null"); // we silently truncate when the user has specified a given Size int bytecount = ((ValueBindingOffset < value.Length) ? Math.Min(value.Length - ValueBindingOffset, ColumnBindingMaxLen) : 0); // 70232 LengthValue(bytecount); StatusValue(DBStatus.S_OK); if (0 < bytecount) { RowBinding.WriteBytes(ValueOffset, value, ValueBindingOffset, bytecount); } } private Decimal Value_CY() { Debug.Assert(NativeDBType.CY == DbType, "Value_CY"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_CY"); return Decimal.FromOACurrency(RowBinding.ReadInt64(ValueOffset)); } private void Value_CY(Decimal value) { Debug.Assert(NativeDBType.CY == DbType, "Value_CY"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt64(ValueOffset, Decimal.ToOACurrency(value)); } private DateTime Value_DATE() { Debug.Assert(NativeDBType.DATE == DbType, "Value_DATE"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_DATE"); return DateTime.FromOADate(RowBinding.ReadDouble(ValueOffset)); } private void Value_DATE(DateTime value) { Debug.Assert(NativeDBType.DATE == DbType, "Value_DATE"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteDouble(ValueOffset, value.ToOADate()); } private DateTime Value_DBDATE() { Debug.Assert(NativeDBType.DBDATE == DbType, "Value_DBDATE"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_DBDATE"); return RowBinding.ReadDate(ValueOffset); } private void Value_DBDATE(DateTime value) { Debug.Assert(NativeDBType.DBDATE == DbType, "Value_DATE"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteDate(ValueOffset, value); } private TimeSpan Value_DBTIME() { Debug.Assert(NativeDBType.DBTIME == DbType, "Value_DBTIME"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_DBTIME"); return RowBinding.ReadTime(ValueOffset); } private void Value_DBTIME(TimeSpan value) { Debug.Assert(NativeDBType.DBTIME == DbType, "Value_DBTIME"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteTime(ValueOffset, value); } private DateTime Value_DBTIMESTAMP() { Debug.Assert(NativeDBType.DBTIMESTAMP == DbType, "Value_DBTIMESTAMP"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_DBTIMESTAMP"); return RowBinding.ReadDateTime(ValueOffset); } private void Value_DBTIMESTAMP(DateTime value) { Debug.Assert(NativeDBType.DBTIMESTAMP == DbType, "Value_DBTIMESTAMP"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteDateTime(ValueOffset, value); } private Decimal Value_DECIMAL() { Debug.Assert(NativeDBType.DECIMAL == DbType, "Value_DECIMAL"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_DECIMAL"); int[] buffer = new int[4]; RowBinding.ReadInt32Array(ValueOffset, buffer, 0, 4); return new Decimal( buffer[2], // low buffer[3], // mid buffer[1], // high (0 != (buffer[0] & unchecked((int)0x80000000))), // sign unchecked((byte)((buffer[0] & unchecked((int)0x00FF0000)) >> 16))); // scale, MDAC 95080 } private void Value_DECIMAL(Decimal value) { Debug.Assert(NativeDBType.DECIMAL == DbType, "Value_DECIMAL"); /* pending breaking change approval if (_precision < ((System.Data.SqlTypes.SqlDecimal) value).Precision) { // WebData 87236 throw ADP.ParameterValueOutOfRange(value); } */ LengthValue(0); StatusValue(DBStatus.S_OK); int[] tmp = Decimal.GetBits(value); int[] buffer = new int[4] { tmp[3], tmp[2], tmp[0], tmp[1] }; RowBinding.WriteInt32Array(ValueOffset, buffer, 0, 4); } private Int32 Value_ERROR() { Debug.Assert(NativeDBType.ERROR == DbType, "Value_ERROR"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_ERROR"); return RowBinding.ReadInt32(ValueOffset); } private void Value_ERROR(Int32 value) { Debug.Assert(NativeDBType.ERROR == DbType, "Value_ERROR"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt32(ValueOffset, value); } private DateTime Value_FILETIME() { Debug.Assert(NativeDBType.FILETIME == DbType, "Value_FILETIME"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_FILETIME"); Int64 tmp = RowBinding.ReadInt64(ValueOffset); return DateTime.FromFileTime(tmp); } private void Value_FILETIME(DateTime value) { Debug.Assert(NativeDBType.FILETIME == DbType, "Value_FILETIME"); LengthValue(0); StatusValue(DBStatus.S_OK); Int64 tmp = value.ToFileTime(); RowBinding.WriteInt64(ValueOffset, tmp); } internal Guid Value_GUID() { Debug.Assert(NativeDBType.GUID == DbType, "Value_GUID"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_GUID"); return RowBinding.ReadGuid(ValueOffset); } private void Value_GUID(Guid value) { Debug.Assert(NativeDBType.GUID == DbType, "Value_GUID"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteGuid(ValueOffset, value); } internal OleDbDataReader Value_HCHAPTER() { Debug.Assert(NativeDBType.HCHAPTER == DbType, "Value_HCHAPTER"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_HCHAPTER"); return DataReader().ResetChapter(IndexForAccessor, IndexWithinAccessor, RowBinding, ValueOffset); } private SByte Value_I1() { Debug.Assert(NativeDBType.I1 == DbType, "Value_I1"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_I1"); byte value = RowBinding.ReadByte(ValueOffset); return unchecked((SByte)value); } private void Value_I1(SByte value) { Debug.Assert(NativeDBType.I1 == DbType, "Value_I1"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteByte(ValueOffset, unchecked((Byte) value)); } internal Int16 Value_I2() { Debug.Assert(NativeDBType.I2 == DbType, "Value_I2"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_I2"); return RowBinding.ReadInt16(ValueOffset); } private void Value_I2(Int16 value) { Debug.Assert(NativeDBType.I2 == DbType, "Value_I2"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt16(ValueOffset, value); } private Int32 Value_I4() { Debug.Assert(NativeDBType.I4 == DbType, "Value_I4"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_I4"); return RowBinding.ReadInt32(ValueOffset); } private void Value_I4(Int32 value) { Debug.Assert(NativeDBType.I4 == DbType, "Value_I4"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt32(ValueOffset, value); } private Int64 Value_I8() { Debug.Assert(NativeDBType.I8 == DbType, "Value_I8"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_I8"); return RowBinding.ReadInt64(ValueOffset); } private void Value_I8(Int64 value) { Debug.Assert(NativeDBType.I8 == DbType, "Value_I8"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt64(ValueOffset, value); } private object Value_IDISPATCH() { Debug.Assert(NativeDBType.IDISPATCH == DbType, "Value_IDISPATCH"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_IDISPATCH"); object value; RowBinding bindings = RowBinding; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { bindings.DangerousAddRef(ref mustRelease); IntPtr ptr = bindings.ReadIntPtr(ValueOffset); value = Marshal.GetObjectForIUnknown(ptr); } finally { if (mustRelease) { bindings.DangerousRelease(); } } return value; } private void Value_IDISPATCH(object value) { // (new System.Security.NamedPermissionSet("FullTrust")).Demand(); // MDAC 80727 Debug.Assert(NativeDBType.IDISPATCH == DbType, "Value_IDISPATCH"); LengthValue(0); StatusValue(DBStatus.S_OK); IntPtr ptr = Marshal.GetIDispatchForObject(value); // MDAC 80727 RowBinding.WriteIntPtr(ValueOffset, ptr); } private object Value_IUNKNOWN() { Debug.Assert(NativeDBType.IUNKNOWN == DbType, "Value_IUNKNOWN"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_IUNKNOWN"); object value; RowBinding bindings = RowBinding; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { bindings.DangerousAddRef(ref mustRelease); IntPtr ptr = bindings.ReadIntPtr(ValueOffset); value = Marshal.GetObjectForIUnknown(ptr); } finally { if (mustRelease) { bindings.DangerousRelease(); } } return value; } private void Value_IUNKNOWN(object value) { // (new System.Security.NamedPermissionSet("FullTrust")).Demand(); // MDAC 80727 Debug.Assert(NativeDBType.IUNKNOWN == DbType, "Value_IUNKNOWN"); LengthValue(0); StatusValue(DBStatus.S_OK); IntPtr ptr = Marshal.GetIUnknownForObject(value); // MDAC 80727 RowBinding.WriteIntPtr(ValueOffset, ptr); } private Decimal Value_NUMERIC() { Debug.Assert(NativeDBType.NUMERIC == DbType, "Value_NUMERIC"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_NUMERIC"); return RowBinding.ReadNumeric(ValueOffset); } private void Value_NUMERIC(Decimal value) { Debug.Assert(NativeDBType.NUMERIC == DbType, "Value_NUMERIC"); /* pending breaking change approval if (_precision < ((System.Data.SqlTypes.SqlDecimal) value).Precision) { // WebData 87236 throw ADP.ParameterValueOutOfRange(value); } */ LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteNumeric(ValueOffset, value, ColumnBindingPrecision); } private Single Value_R4() { Debug.Assert(NativeDBType.R4 == DbType, "Value_R4"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_R4"); return RowBinding.ReadSingle(ValueOffset); } private void Value_R4(Single value) { Debug.Assert(NativeDBType.R4 == DbType, "Value_R4"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteSingle(ValueOffset,value); } private Double Value_R8() { Debug.Assert(NativeDBType.R8 == DbType, "Value_R8"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_R8"); return RowBinding.ReadDouble(ValueOffset); } private void Value_R8(Double value) { Debug.Assert(NativeDBType.R8 == DbType, "Value_I4"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteDouble(ValueOffset, value); } private Byte Value_UI1() { Debug.Assert(NativeDBType.UI1 == DbType, "Value_UI1"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_UI1"); return RowBinding.ReadByte(ValueOffset); } private void Value_UI1(Byte value) { Debug.Assert(NativeDBType.UI1 == DbType, "Value_UI1"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteByte(ValueOffset, value); } internal UInt16 Value_UI2() { Debug.Assert(NativeDBType.UI2 == DbType, "Value_UI2"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_UI2"); return unchecked((UInt16) RowBinding.ReadInt16(ValueOffset)); } private void Value_UI2(UInt16 value) { Debug.Assert(NativeDBType.UI2 == DbType, "Value_UI2"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt16(ValueOffset, unchecked((Int16) value)); } internal UInt32 Value_UI4() { Debug.Assert(NativeDBType.UI4 == DbType, "Value_UI4"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_UI4"); return unchecked((UInt32) RowBinding.ReadInt32(ValueOffset)); } private void Value_UI4(UInt32 value) { Debug.Assert(NativeDBType.UI4 == DbType, "Value_UI4"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt32(ValueOffset, unchecked((Int32) value)); } internal UInt64 Value_UI8() { Debug.Assert(NativeDBType.UI8 == DbType, "Value_UI8"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_UI8"); return unchecked((UInt64) RowBinding.ReadInt64(ValueOffset)); } private void Value_UI8(UInt64 value) { Debug.Assert(NativeDBType.UI8 == DbType, "Value_UI8"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.WriteInt64(ValueOffset, unchecked((Int64) value)); } private String Value_WSTR() { Debug.Assert(NativeDBType.WSTR == DbType, "Value_WSTR"); Debug.Assert((DBStatus.S_OK == StatusValue()) || (DBStatus.S_TRUNCATED == StatusValue()), "Value_WSTR"); Debug.Assert(2 < ColumnBindingMaxLen, "Value_WSTR"); int byteCount = Math.Min(LengthValue(), ColumnBindingMaxLen-2); return RowBinding.PtrToStringUni(ValueOffset, byteCount / 2); } private void Value_WSTR(String value) { Debug.Assert(null != value, "Value_BYTES null"); Debug.Assert(NativeDBType.WSTR == DbType, "Value_WSTR"); // we silently truncate when the user has specified a given Size int charCount = ((ValueBindingOffset < value.Length) ? Math.Min(value.Length - ValueBindingOffset, (ColumnBindingMaxLen-2)/2) : 0); // 70232 LengthValue(charCount*2); StatusValue(DBStatus.S_OK); if (0 < charCount) { char[] chars = value.ToCharArray(ValueBindingOffset, charCount); RowBinding.WriteCharArray(ValueOffset, chars, ValueBindingOffset, charCount); } } private void Value_WSTR(char[] value) { Debug.Assert(null != value, "Value_BYTES null"); Debug.Assert(NativeDBType.WSTR == DbType, "Value_WSTR"); // we silently truncate when the user has specified a given Size int charCount = ((ValueBindingOffset < value.Length) ? Math.Min(value.Length - ValueBindingOffset, (ColumnBindingMaxLen-2)/2) : 0); // 70232 LengthValue(charCount*2); StatusValue(DBStatus.S_OK); if (0 < charCount) { RowBinding.WriteCharArray(ValueOffset, value, ValueBindingOffset, charCount); } } private object Value_VARIANT() { Debug.Assert((NativeDBType.VARIANT == DbType) || (NativeDBType.PROPVARIANT == DbType), "Value_VARIANT"); Debug.Assert(DBStatus.S_OK == StatusValue(), "Value_VARIANT"); return RowBinding.GetVariantValue(ValueOffset); } private void Value_VARIANT(object value) { Debug.Assert((NativeDBType.VARIANT == DbType) || (NativeDBType.PROPVARIANT == DbType), "Value_VARIANT"); LengthValue(0); StatusValue(DBStatus.S_OK); RowBinding.SetVariantValue(ValueOffset, value); } internal Boolean ValueBoolean() { Boolean value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.BOOL: value = Value_BOOL(); break; case NativeDBType.VARIANT: value = (Boolean) ValueVariant(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Boolean)); } return value; } internal byte[] ValueByteArray() { byte[] value = (byte[]) _value; if (null == value) { switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.BYTES: value = Value_BYTES(); // String break; case NativeDBType.VARIANT: value = (byte[])ValueVariant(); // Object break; case (NativeDBType.BYREF | NativeDBType.BYTES): value = Value_ByRefBYTES(); break; default: throw ODB.ConversionRequired(); } break; case DBStatus.S_TRUNCATED: switch(DbType) { case NativeDBType.BYTES: value = Value_BYTES(); break; case (NativeDBType.BYREF | NativeDBType.BYTES): value = Value_ByRefBYTES(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(byte[])); } _value = value; } return value; } internal Byte ValueByte() { Byte value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.UI1: value = Value_UI1(); break; case NativeDBType.VARIANT: value = (Byte) ValueVariant(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Byte)); } return value; } internal OleDbDataReader ValueChapter() { OleDbDataReader value = (OleDbDataReader) _value; if (null == value) { switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.HCHAPTER: value = Value_HCHAPTER(); // OleDbDataReader break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(String)); } _value = value; } return value; } internal DateTime ValueDateTime() { DateTime value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.DATE: value = Value_DATE(); break; case NativeDBType.DBDATE: value = Value_DBDATE(); break; case NativeDBType.DBTIMESTAMP: value = Value_DBTIMESTAMP(); break; case NativeDBType.FILETIME: value = Value_FILETIME(); break; case NativeDBType.VARIANT: value = (DateTime) ValueVariant(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Int16)); } return value; } internal Decimal ValueDecimal() { Decimal value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.CY: value = Value_CY(); break; case NativeDBType.DECIMAL: value = Value_DECIMAL(); break; case NativeDBType.NUMERIC: value = Value_NUMERIC(); break; case NativeDBType.UI8: value = (Decimal)Value_UI8(); break; case NativeDBType.VARIANT: value = (Decimal) ValueVariant(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Int16)); } return value; } internal Guid ValueGuid() { Guid value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.GUID: value = Value_GUID(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Int16)); } return value; } internal Int16 ValueInt16() { Int16 value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.I2: value = Value_I2(); break; case NativeDBType.I1: value = (Int16) Value_I1(); break; case NativeDBType.VARIANT: object variant = ValueVariant(); if (variant is SByte) { value = (Int16)(SByte) variant; } else { value = (Int16) variant; } break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Int16)); } return value; } internal Int32 ValueInt32() { Int32 value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.I4: value = Value_I4(); break; case NativeDBType.UI2: value = (Int32) Value_UI2(); break; case NativeDBType.VARIANT: object variant = ValueVariant(); if (variant is UInt16) { value = (Int32)(UInt16) variant; } else { value = (Int32) variant; } break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Int32)); } return value; } internal Int64 ValueInt64() { Int64 value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.I8: value = Value_I8(); break; case NativeDBType.UI4: value = (Int64) Value_UI4(); break; case NativeDBType.VARIANT: object variant = ValueVariant(); if (variant is UInt32) { value = (Int64)(UInt32) variant; } else { value = (Int64) variant; } break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Int64)); } return value; } internal Single ValueSingle() { Single value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.R4: value = Value_R4(); break; case NativeDBType.VARIANT: value = (Single) ValueVariant(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Single)); } return value; } internal Double ValueDouble() { Double value; switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.R8: value = Value_R8(); break; case NativeDBType.VARIANT: value = (Double) ValueVariant(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(Double)); } return value; } internal string ValueString() { string value = (String) _value; if (null == value) { switch(StatusValue()) { case DBStatus.S_OK: switch(DbType) { case NativeDBType.BSTR: value = Value_BSTR(); // String break; case NativeDBType.VARIANT: value = (String) ValueVariant(); // Object break; case NativeDBType.WSTR: value = Value_WSTR(); // String break; case (NativeDBType.BYREF | NativeDBType.WSTR): value = Value_ByRefWSTR(); break; default: throw ODB.ConversionRequired(); } break; case DBStatus.S_TRUNCATED: switch(DbType) { case NativeDBType.WSTR: value = Value_WSTR(); break; case (NativeDBType.BYREF | NativeDBType.WSTR): value = Value_ByRefWSTR(); break; default: throw ODB.ConversionRequired(); } break; default: throw CheckTypeValueStatusValue(typeof(String)); } _value = value; } return value; } private object ValueVariant() { object value = _value; if (null == value) { value = Value_VARIANT(); _value = value; } return value; } private Exception CheckTypeValueStatusValue() { // MDAC 71644 return CheckTypeValueStatusValue(ExpectedType); } private Exception CheckTypeValueStatusValue(Type expectedType) { // MDAC 71644 switch (StatusValue()) { case DBStatus.S_OK: Debug.Assert(false, "CheckStatusValue: unhandled data with ok status"); goto case DBStatus.E_CANTCONVERTVALUE; case DBStatus.S_TRUNCATED: Debug.Assert(false, "CheckStatusValue: unhandled data with truncated status"); goto case DBStatus.E_CANTCONVERTVALUE; case DBStatus.E_BADACCESSOR: return ODB.BadAccessor(); case DBStatus.E_CANTCONVERTVALUE: return ODB.CantConvertValue(); // case DBStatus.S_ISNULL: // database null return ADP.InvalidCast(); // case DBStatus.E_SIGNMISMATCH: return ODB.SignMismatch(expectedType); case DBStatus.E_DATAOVERFLOW: return ODB.DataOverflow(expectedType); case DBStatus.E_CANTCREATE: return ODB.CantCreate(expectedType); case DBStatus.E_UNAVAILABLE: return ODB.Unavailable(expectedType); default: return ODB.UnexpectedStatusValue(StatusValue()); } } } }
//********************************************************* // // 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; using System; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Devices.PointOfService; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace CashDrawerSample { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario2_CloseDrawer : Page { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; CashDrawer drawer = null; ClaimedCashDrawer claimedDrawer = null; public Scenario2_CloseDrawer() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { ResetScenarioState(); base.OnNavigatedTo(e); } /// <summary> /// Invoked before the page is unloaded and is no longer the current source of a Frame. /// </summary> /// <param name="e">Event data describing the navigation that was requested.</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { ResetScenarioState(); base.OnNavigatedFrom(e); } /// <summary> /// Event handler for Initialize Drawer button. /// Claims and enables the default cash drawer. /// </summary> /// <param name="sender">Button that was clicked.</param> /// <param name="e">Event data associated with click event.</param> private async void InitDrawerButton_Click(object sender, RoutedEventArgs e) { if (await CreateDefaultCashDrawerObject()) { if (await ClaimCashDrawer()) { if (await EnableCashDrawer()) { drawer.StatusUpdated += drawer_StatusUpdated; InitDrawerButton.IsEnabled = false; DrawerWaitButton.IsEnabled = true; UpdateStatusOutput(drawer.Status.StatusKind); rootPage.NotifyUser("Successfully enabled cash drawer. Device ID: " + claimedDrawer.DeviceId, NotifyType.StatusMessage); } else { rootPage.NotifyUser("Failed to enable cash drawer.", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Failed to claim cash drawer.", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Cash drawer not found. Please connect a cash drawer.", NotifyType.ErrorMessage); } } /// <summary> /// Set up an alarm and wait for the drawer to close. /// </summary> /// <param name="sender">Button that was clicked.</param> /// <param name="e">Event data associated with click event.</param> private async void WaitForDrawerCloseButton_Click(object sender, RoutedEventArgs e) { if (claimedDrawer == null) { rootPage.NotifyUser("Drawer must be initialized.", NotifyType.ErrorMessage); return; } var alarm = claimedDrawer.CloseAlarm; if (alarm == null) { rootPage.NotifyUser("Failed to create drawer alarm.", NotifyType.ErrorMessage); return; } // TimeSpan specifies a time period as (hours, minutes, seconds) alarm.AlarmTimeout = new TimeSpan(0, 0, 30); alarm.BeepDelay = new TimeSpan(0, 0, 3); alarm.BeepDuration = new TimeSpan(0, 0, 1); alarm.BeepFrequency = 700; alarm.AlarmTimeoutExpired += drawer_AlarmExpired; rootPage.NotifyUser("Waiting for drawer to close.", NotifyType.StatusMessage); if (await alarm.StartAsync()) rootPage.NotifyUser("Successfully waited for drawer close.", NotifyType.StatusMessage); else rootPage.NotifyUser("Failed to wait for drawer close.", NotifyType.ErrorMessage); } /// <summary> /// Creates the default cash drawer. /// </summary> /// <returns>True if the cash drawer was created, false otherwise.</returns> private async Task<bool> CreateDefaultCashDrawerObject() { rootPage.NotifyUser("Creating cash drawer object.", NotifyType.StatusMessage); if (drawer == null) { drawer = await CashDrawer.GetDefaultAsync(); if (drawer == null) return false; } return true; } /// <summary> /// Attempt to claim the connected cash drawer. /// </summary> /// <returns>True if the cash drawer was successfully claimed, false otherwise.</returns> private async Task<bool> ClaimCashDrawer() { if (drawer == null) return false; if (claimedDrawer == null) { claimedDrawer = await drawer.ClaimDrawerAsync(); if (claimedDrawer == null) return false; } return true; } /// <summary> /// Attempt to enabled the claimed cash drawer. /// </summary> /// <returns>True if the cash drawer was successfully enabled, false otherwise.</returns> private async Task<bool> EnableCashDrawer() { if (claimedDrawer == null) return false; if (claimedDrawer.IsEnabled) return true; return await claimedDrawer.EnableAsync(); } /// <summary> /// Event callback for device status updates. /// </summary> /// <param name="drawer">CashDrawer object sending the status update event.</param> /// <param name="e">Event data associated with the status update.</param> private async void drawer_StatusUpdated(CashDrawer drawer, CashDrawerStatusUpdatedEventArgs e) { await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { UpdateStatusOutput(e.Status.StatusKind); rootPage.NotifyUser("Status updated event: " + e.Status.StatusKind.ToString(), NotifyType.StatusMessage); }); } /// <summary> /// Event callback for the alarm expiring. /// </summary> /// <param name="alarm">CashDrawerCloseAlarm that has expired.</param> /// <param name="sender">Unused by AlarmTimeoutExpired events.</param> private async void drawer_AlarmExpired(CashDrawerCloseAlarm alarm, object sender) { await MainPage.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Alarm expired. Still waiting for drawer to be closed.", NotifyType.StatusMessage); }); } /// <summary> /// Reset the scenario to its initial state. /// </summary> private void ResetScenarioState() { drawer = null; if (claimedDrawer != null) { claimedDrawer.Dispose(); claimedDrawer = null; } UpdateStatusOutput(CashDrawerStatusKind.Offline); InitDrawerButton.IsEnabled = true; DrawerWaitButton.IsEnabled = false; rootPage.NotifyUser("Click the init drawer button to begin.", NotifyType.StatusMessage); } /// <summary> /// Update the cash drawer text block. /// </summary> /// <param name="status">Cash drawer status to be displayed.</param> private void UpdateStatusOutput(CashDrawerStatusKind status) { DrawerStatusBlock.Text = status.ToString(); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Common { using System; using System.Collections.Generic; using System.Text; using System.Threading; using NLog.Internal; /// <summary> /// Helpers for asynchronous operations. /// </summary> public static class AsyncHelpers { internal static int GetManagedThreadId() { #if NETSTANDARD1_3 return System.Environment.CurrentManagedThreadId; #else return Thread.CurrentThread.ManagedThreadId; #endif } internal static void StartAsyncTask(AsyncHelpersTask asyncTask, object state) { var asyncDelegate = asyncTask.AsyncDelegate; #if NETSTANDARD1_0 System.Threading.Tasks.Task.Factory.StartNew(asyncDelegate, state, CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default); #else ThreadPool.QueueUserWorkItem(asyncDelegate, state); #endif } internal static void WaitForDelay(TimeSpan delay) { #if NETSTANDARD1_3 System.Threading.Tasks.Task.Delay(delay).Wait(); #else Thread.Sleep(delay); #endif } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemSequentially<T>(IEnumerable<T> items, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); IEnumerator<T> enumerator = items.GetEnumerator(); void InvokeNext(Exception ex) { if (ex != null) { asyncContinuation(ex); return; } if (!enumerator.MoveNext()) { enumerator.Dispose(); asyncContinuation(null); return; } action(enumerator.Current, PreventMultipleCalls(InvokeNext)); } InvokeNext(null); } /// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); int remaining = repeatCount; void InvokeNext(Exception ex) { if (ex != null) { asyncContinuation(ex); return; } if (remaining-- <= 0) { asyncContinuation(null); return; } action(PreventMultipleCalls(InvokeNext)); } InvokeNext(null); } /// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation continuation = ex => { if (ex != null) { // if got exception from from original invocation, don't execute action asyncContinuation(ex); return; } // call the action and continue action(PreventMultipleCalls(asyncContinuation)); }; return continuation; } /// <summary> /// Attaches a timeout to a continuation which will invoke the continuation when the specified /// timeout has elapsed. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <param name="timeout">The timeout.</param> /// <returns>Wrapped continuation.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Continuation will be disposed of elsewhere.")] public static AsyncContinuation WithTimeout(AsyncContinuation asyncContinuation, TimeSpan timeout) { return new TimeoutContinuation(asyncContinuation, timeout).Function; } /// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel<T>(IEnumerable<T> values, AsyncContinuation asyncContinuation, AsynchronousAction<T> action) { action = ExceptionGuard(action); var items = new List<T>(values); int remaining = items.Count; var exceptions = new List<Exception>(); InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count); if (remaining == 0) { asyncContinuation(null); return; } AsyncContinuation continuation = ex => { InternalLogger.Trace("Continuation invoked: {0}", ex); if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } var r = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", r); if (r == 0) { asyncContinuation(GetCombinedException(exceptions)); } }; foreach (T item in items) { T itemCopy = item; StartAsyncTask(new AsyncHelpersTask(s => { var preventMultipleCalls = PreventMultipleCalls(continuation); try { action(itemCopy, preventMultipleCalls); } catch (Exception ex) { InternalLogger.Error(ex, "ForEachItemInParallel - Unhandled Exception"); if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } preventMultipleCalls.Invoke(ex); } }), null); } } /// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> public static void RunSynchronously(AsynchronousAction action) { var ev = new ManualResetEvent(false); Exception lastException = null; action(PreventMultipleCalls(ex => { lastException = ex; ev.Set(); })); ev.WaitOne(); if (lastException != null) { throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); } } /// <summary> /// Wraps the continuation with a guard which will only make sure that the continuation function /// is invoked only once. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> /// <returns>Wrapped asynchronous continuation.</returns> public static AsyncContinuation PreventMultipleCalls(AsyncContinuation asyncContinuation) { if (asyncContinuation.Target is SingleCallContinuation) { return asyncContinuation; } return new SingleCallContinuation(asyncContinuation).Function; } /// <summary> /// Gets the combined exception from all exceptions in the list. /// </summary> /// <param name="exceptions">The exceptions.</param> /// <returns>Combined exception or null if no exception was thrown.</returns> public static Exception GetCombinedException(IList<Exception> exceptions) { if (exceptions.Count == 0) { return null; } if (exceptions.Count == 1) { return exceptions[0]; } var sb = new StringBuilder(); string separator = string.Empty; string newline = EnvironmentHelper.NewLine; foreach (var ex in exceptions) { sb.Append(separator); sb.Append(ex.ToString()); sb.Append(newline); separator = newline; } return new NLogRuntimeException("Got multiple exceptions:\r\n" + sb); } private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { return cont => { try { action(cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } private static AsynchronousAction<T> ExceptionGuard<T>(AsynchronousAction<T> action) { return (T argument, AsyncContinuation cont) => { try { action(argument, cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } /// <summary> /// Disposes the Timer, and waits for it to leave the Timer-callback-method /// </summary> /// <param name="timer">The Timer object to dispose</param> /// <param name="timeout">Timeout to wait (TimeSpan.Zero means dispose without waiting)</param> /// <returns>Timer disposed within timeout (true/false)</returns> internal static bool WaitForDispose(this Timer timer, TimeSpan timeout) { timer.Change(Timeout.Infinite, Timeout.Infinite); if (timeout != TimeSpan.Zero) { ManualResetEvent waitHandle = new ManualResetEvent(false); if (timer.Dispose(waitHandle) && !waitHandle.WaitOne((int)timeout.TotalMilliseconds)) { return false; // Return without waiting for timer, and without closing waitHandle (Avoid ObjectDisposedException) } waitHandle.Close(); } else { timer.Dispose(); } return true; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPerson { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPerson() : base() { FormClosed += frmPerson_FormClosed; KeyPress += frmPerson_KeyPress; Resize += frmPerson_Resize; Load += frmPerson_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.CheckBox chkController; private System.Windows.Forms.TextBox withEventsField_txtComm; public System.Windows.Forms.TextBox txtComm { get { return withEventsField_txtComm; } set { if (withEventsField_txtComm != null) { withEventsField_txtComm.Enter -= txtComm_Enter; withEventsField_txtComm.KeyPress -= txtComm_KeyPress; withEventsField_txtComm.Leave -= txtComm_Leave; } withEventsField_txtComm = value; if (withEventsField_txtComm != null) { withEventsField_txtComm.Enter += txtComm_Enter; withEventsField_txtComm.KeyPress += txtComm_KeyPress; withEventsField_txtComm.Leave += txtComm_Leave; } } } public System.Windows.Forms.Label Label2; public System.Windows.Forms.GroupBox Frame1; private System.Windows.Forms.Button withEventsField_cmdBuild; public System.Windows.Forms.Button cmdBuild { get { return withEventsField_cmdBuild; } set { if (withEventsField_cmdBuild != null) { withEventsField_cmdBuild.Click -= cmdBuild_Click; } withEventsField_cmdBuild = value; if (withEventsField_cmdBuild != null) { withEventsField_cmdBuild.Click += cmdBuild_Click; } } } public System.Windows.Forms.CheckBox _chkFields_2; public System.Windows.Forms.ComboBox cmbDraw; public System.Windows.Forms.TextBox _txtFields_12; public System.Windows.Forms.Label _lblLabels_0; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label _lblLabels_12; public System.Windows.Forms.GroupBox _frmSecurity_1; public System.Windows.Forms.TextBox _txtFields_11; public System.Windows.Forms.TextBox _txtFields_10; public System.Windows.Forms.Label _lblLabels_11; public System.Windows.Forms.Label _lblLabels_10; public System.Windows.Forms.GroupBox _frmSecurity_0; public System.Windows.Forms.TextBox _txtFields_1; public System.Windows.Forms.TextBox _txtFields_2; public System.Windows.Forms.TextBox _txtFields_4; public System.Windows.Forms.TextBox _txtFields_5; public System.Windows.Forms.TextBox _txtFields_7; public System.Windows.Forms.TextBox _txtFields_8; public System.Windows.Forms.TextBox _txtFields_13; private System.Windows.Forms.Button withEventsField_cmdFPR; public System.Windows.Forms.Button cmdFPR { get { return withEventsField_cmdFPR; } set { if (withEventsField_cmdFPR != null) { withEventsField_cmdFPR.Click -= cmdFPR_Click; } withEventsField_cmdFPR = value; if (withEventsField_cmdFPR != null) { withEventsField_cmdFPR.Click += cmdFPR_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPOSsecurity; public System.Windows.Forms.Button cmdPOSsecurity { get { return withEventsField_cmdPOSsecurity; } set { if (withEventsField_cmdPOSsecurity != null) { withEventsField_cmdPOSsecurity.Click -= cmdPOSsecurity_Click; } withEventsField_cmdPOSsecurity = value; if (withEventsField_cmdPOSsecurity != null) { withEventsField_cmdPOSsecurity.Click += cmdPOSsecurity_Click; } } } private System.Windows.Forms.Button withEventsField_cmdBOsecurity; public System.Windows.Forms.Button cmdBOsecurity { get { return withEventsField_cmdBOsecurity; } set { if (withEventsField_cmdBOsecurity != null) { withEventsField_cmdBOsecurity.Click -= cmdBOsecurity_Click; } withEventsField_cmdBOsecurity = value; if (withEventsField_cmdBOsecurity != null) { withEventsField_cmdBOsecurity.Click += cmdBOsecurity_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _lbl_1; public Microsoft.VisualBasic.PowerPacks.LineShape Line1; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; public System.Windows.Forms.Label _lbl_0; public System.Windows.Forms.Label _lblLabels_2; public System.Windows.Forms.Label _lblLabels_4; public System.Windows.Forms.Label _lblLabels_5; public System.Windows.Forms.Label _lblLabels_7; public System.Windows.Forms.Label _lblLabels_8; public System.Windows.Forms.Label _lblLabels_13; public System.Windows.Forms.Label _lbl_5; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; //Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray //Public WithEvents frmSecurity As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPerson)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.chkController = new System.Windows.Forms.CheckBox(); this.Frame1 = new System.Windows.Forms.GroupBox(); this.txtComm = new System.Windows.Forms.TextBox(); this.Label2 = new System.Windows.Forms.Label(); this.cmdBuild = new System.Windows.Forms.Button(); this._chkFields_2 = new System.Windows.Forms.CheckBox(); this._frmSecurity_1 = new System.Windows.Forms.GroupBox(); this.cmbDraw = new System.Windows.Forms.ComboBox(); this._txtFields_12 = new System.Windows.Forms.TextBox(); this._lblLabels_0 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this._lblLabels_12 = new System.Windows.Forms.Label(); this._frmSecurity_0 = new System.Windows.Forms.GroupBox(); this._txtFields_11 = new System.Windows.Forms.TextBox(); this._txtFields_10 = new System.Windows.Forms.TextBox(); this._lblLabels_11 = new System.Windows.Forms.Label(); this._lblLabels_10 = new System.Windows.Forms.Label(); this._txtFields_1 = new System.Windows.Forms.TextBox(); this._txtFields_2 = new System.Windows.Forms.TextBox(); this._txtFields_4 = new System.Windows.Forms.TextBox(); this._txtFields_5 = new System.Windows.Forms.TextBox(); this._txtFields_7 = new System.Windows.Forms.TextBox(); this._txtFields_8 = new System.Windows.Forms.TextBox(); this._txtFields_13 = new System.Windows.Forms.TextBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdFPR = new System.Windows.Forms.Button(); this.cmdPOSsecurity = new System.Windows.Forms.Button(); this.cmdBOsecurity = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this._lbl_1 = new System.Windows.Forms.Label(); this.Line1 = new Microsoft.VisualBasic.PowerPacks.LineShape(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._lbl_0 = new System.Windows.Forms.Label(); this._lblLabels_2 = new System.Windows.Forms.Label(); this._lblLabels_4 = new System.Windows.Forms.Label(); this._lblLabels_5 = new System.Windows.Forms.Label(); this._lblLabels_7 = new System.Windows.Forms.Label(); this._lblLabels_8 = new System.Windows.Forms.Label(); this._lblLabels_13 = new System.Windows.Forms.Label(); this._lbl_5 = new System.Windows.Forms.Label(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); //Me.chkFields = New Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray(components) //Me.frmSecurity = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) //Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) this.Shape1 = new RectangleShapeArray(components); this.Frame1.SuspendLayout(); this._frmSecurity_1.SuspendLayout(); this._frmSecurity_0.SuspendLayout(); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.chkFields, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.frmSecurity, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Edit Employee Details"; this.ClientSize = new System.Drawing.Size(486, 348); this.Location = new System.Drawing.Point(73, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmPerson"; this.chkController.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkController.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkController.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.chkController.Text = "Permit this person to terminate controller"; this.chkController.ForeColor = System.Drawing.SystemColors.WindowText; this.chkController.Size = new System.Drawing.Size(229, 21); this.chkController.Location = new System.Drawing.Point(226, 286); this.chkController.TabIndex = 34; this.chkController.CausesValidation = true; this.chkController.Enabled = true; this.chkController.Cursor = System.Windows.Forms.Cursors.Default; this.chkController.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkController.Appearance = System.Windows.Forms.Appearance.Normal; this.chkController.TabStop = true; this.chkController.CheckState = System.Windows.Forms.CheckState.Unchecked; this.chkController.Visible = true; this.chkController.Name = "chkController"; this.Frame1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this.Frame1.Text = "Commission %"; this.Frame1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.Frame1.Size = new System.Drawing.Size(189, 39); this.Frame1.Location = new System.Drawing.Point(22, 242); this.Frame1.TabIndex = 31; this.Frame1.Enabled = true; this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText; this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Frame1.Visible = true; this.Frame1.Padding = new System.Windows.Forms.Padding(0); this.Frame1.Name = "Frame1"; this.txtComm.AutoSize = false; this.txtComm.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtComm.Size = new System.Drawing.Size(61, 17); this.txtComm.Location = new System.Drawing.Point(116, 14); this.txtComm.TabIndex = 33; this.txtComm.AcceptsReturn = true; this.txtComm.BackColor = System.Drawing.SystemColors.Window; this.txtComm.CausesValidation = true; this.txtComm.Enabled = true; this.txtComm.ForeColor = System.Drawing.SystemColors.WindowText; this.txtComm.HideSelection = true; this.txtComm.ReadOnly = false; this.txtComm.MaxLength = 0; this.txtComm.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtComm.Multiline = false; this.txtComm.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtComm.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtComm.TabStop = true; this.txtComm.Visible = true; this.txtComm.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtComm.Name = "txtComm"; this.Label2.Text = "Value"; this.Label2.Size = new System.Drawing.Size(71, 17); this.Label2.Location = new System.Drawing.Point(10, 16); this.Label2.TabIndex = 32; this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label2.BackColor = System.Drawing.Color.Transparent; this.Label2.Enabled = true; this.Label2.ForeColor = System.Drawing.SystemColors.ControlText; this.Label2.Cursor = System.Windows.Forms.Cursors.Default; this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label2.UseMnemonic = true; this.Label2.Visible = true; this.Label2.AutoSize = false; this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label2.Name = "Label2"; this.cmdBuild.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBuild.Text = "Build..."; this.cmdBuild.Size = new System.Drawing.Size(46, 16); this.cmdBuild.Location = new System.Drawing.Point(402, 213); this.cmdBuild.TabIndex = 27; this.cmdBuild.BackColor = System.Drawing.SystemColors.Control; this.cmdBuild.CausesValidation = true; this.cmdBuild.Enabled = true; this.cmdBuild.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBuild.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBuild.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBuild.TabStop = true; this.cmdBuild.Name = "cmdBuild"; this._chkFields_2.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this._chkFields_2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._chkFields_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._chkFields_2.Text = "Disable this person from using the application suite:"; this._chkFields_2.ForeColor = System.Drawing.SystemColors.WindowText; this._chkFields_2.Size = new System.Drawing.Size(262, 19); this._chkFields_2.Location = new System.Drawing.Point(194, 308); this._chkFields_2.TabIndex = 29; this._chkFields_2.CausesValidation = true; this._chkFields_2.Enabled = true; this._chkFields_2.Cursor = System.Windows.Forms.Cursors.Default; this._chkFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._chkFields_2.Appearance = System.Windows.Forms.Appearance.Normal; this._chkFields_2.TabStop = true; this._chkFields_2.CheckState = System.Windows.Forms.CheckState.Unchecked; this._chkFields_2.Visible = true; this._chkFields_2.Name = "_chkFields_2"; this._frmSecurity_1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._frmSecurity_1.Text = "Point Of Sale Logon"; this._frmSecurity_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmSecurity_1.Size = new System.Drawing.Size(220, 108); this._frmSecurity_1.Location = new System.Drawing.Point(237, 171); this._frmSecurity_1.TabIndex = 24; this._frmSecurity_1.Enabled = true; this._frmSecurity_1.ForeColor = System.Drawing.SystemColors.ControlText; this._frmSecurity_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmSecurity_1.Visible = true; this._frmSecurity_1.Padding = new System.Windows.Forms.Padding(0); this._frmSecurity_1.Name = "_frmSecurity_1"; this.cmbDraw.BackColor = System.Drawing.Color.White; this.cmbDraw.Size = new System.Drawing.Size(105, 21); this.cmbDraw.Location = new System.Drawing.Point(104, 80); this.cmbDraw.Items.AddRange(new object[] { "Till / Drawer # 1", "Till / Drawer # 2" }); this.cmbDraw.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbDraw.TabIndex = 37; this.cmbDraw.CausesValidation = true; this.cmbDraw.Enabled = true; this.cmbDraw.ForeColor = System.Drawing.SystemColors.WindowText; this.cmbDraw.IntegralHeight = true; this.cmbDraw.Cursor = System.Windows.Forms.Cursors.Default; this.cmbDraw.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmbDraw.Sorted = false; this.cmbDraw.TabStop = true; this.cmbDraw.Visible = true; this.cmbDraw.Name = "cmbDraw"; this._txtFields_12.AutoSize = false; this._txtFields_12.Size = new System.Drawing.Size(114, 19); this._txtFields_12.ImeMode = System.Windows.Forms.ImeMode.Disable; this._txtFields_12.Location = new System.Drawing.Point(96, 18); this._txtFields_12.PasswordChar = Strings.ChrW(35); this._txtFields_12.TabIndex = 26; this._txtFields_12.AcceptsReturn = true; this._txtFields_12.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_12.BackColor = System.Drawing.SystemColors.Window; this._txtFields_12.CausesValidation = true; this._txtFields_12.Enabled = true; this._txtFields_12.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_12.HideSelection = true; this._txtFields_12.ReadOnly = false; this._txtFields_12.MaxLength = 0; this._txtFields_12.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_12.Multiline = false; this._txtFields_12.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_12.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_12.TabStop = true; this._txtFields_12.Visible = true; this._txtFields_12.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_12.Name = "_txtFields_12"; this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_0.BackColor = System.Drawing.Color.Transparent; this._lblLabels_0.Text = "Default Till/Drawer:"; this._lblLabels_0.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_0.Size = new System.Drawing.Size(92, 13); this._lblLabels_0.Location = new System.Drawing.Point(8, 88); this._lblLabels_0.TabIndex = 36; this._lblLabels_0.Enabled = true; this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_0.UseMnemonic = true; this._lblLabels_0.Visible = true; this._lblLabels_0.AutoSize = true; this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_0.Name = "_lblLabels_0"; this.Label1.Text = "This is a barcode used for log-in for the Point Of Sale device."; this.Label1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.Label1.Size = new System.Drawing.Size(148, 43); this.Label1.Location = new System.Drawing.Point(9, 39); this.Label1.TabIndex = 28; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.Color.Transparent; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this._lblLabels_12.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_12.BackColor = System.Drawing.Color.Transparent; this._lblLabels_12.Text = "Access Scan ID:"; this._lblLabels_12.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_12.Size = new System.Drawing.Size(80, 13); this._lblLabels_12.Location = new System.Drawing.Point(9, 18); this._lblLabels_12.TabIndex = 25; this._lblLabels_12.Enabled = true; this._lblLabels_12.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_12.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_12.UseMnemonic = true; this._lblLabels_12.Visible = true; this._lblLabels_12.AutoSize = true; this._lblLabels_12.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_12.Name = "_lblLabels_12"; this._frmSecurity_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._frmSecurity_0.Text = "Back Office Logon"; this._frmSecurity_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._frmSecurity_0.Size = new System.Drawing.Size(190, 66); this._frmSecurity_0.Location = new System.Drawing.Point(21, 171); this._frmSecurity_0.TabIndex = 19; this._frmSecurity_0.Enabled = true; this._frmSecurity_0.ForeColor = System.Drawing.SystemColors.ControlText; this._frmSecurity_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._frmSecurity_0.Visible = true; this._frmSecurity_0.Padding = new System.Windows.Forms.Padding(0); this._frmSecurity_0.Name = "_frmSecurity_0"; this._txtFields_11.AutoSize = false; this._txtFields_11.Size = new System.Drawing.Size(114, 19); this._txtFields_11.ImeMode = System.Windows.Forms.ImeMode.Disable; this._txtFields_11.Location = new System.Drawing.Point(65, 40); this._txtFields_11.PasswordChar = Strings.ChrW(35); this._txtFields_11.TabIndex = 23; this._txtFields_11.AcceptsReturn = true; this._txtFields_11.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_11.BackColor = System.Drawing.SystemColors.Window; this._txtFields_11.CausesValidation = true; this._txtFields_11.Enabled = true; this._txtFields_11.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_11.HideSelection = true; this._txtFields_11.ReadOnly = false; this._txtFields_11.MaxLength = 0; this._txtFields_11.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_11.Multiline = false; this._txtFields_11.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_11.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_11.TabStop = true; this._txtFields_11.Visible = true; this._txtFields_11.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_11.Name = "_txtFields_11"; this._txtFields_10.AutoSize = false; this._txtFields_10.Size = new System.Drawing.Size(114, 19); this._txtFields_10.Location = new System.Drawing.Point(65, 18); this._txtFields_10.TabIndex = 21; this._txtFields_10.AcceptsReturn = true; this._txtFields_10.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_10.BackColor = System.Drawing.SystemColors.Window; this._txtFields_10.CausesValidation = true; this._txtFields_10.Enabled = true; this._txtFields_10.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_10.HideSelection = true; this._txtFields_10.ReadOnly = false; this._txtFields_10.MaxLength = 0; this._txtFields_10.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_10.Multiline = false; this._txtFields_10.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_10.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_10.TabStop = true; this._txtFields_10.Visible = true; this._txtFields_10.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_10.Name = "_txtFields_10"; this._lblLabels_11.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_11.BackColor = System.Drawing.Color.Transparent; this._lblLabels_11.Text = "Password:"; this._lblLabels_11.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_11.Size = new System.Drawing.Size(49, 13); this._lblLabels_11.Location = new System.Drawing.Point(9, 40); this._lblLabels_11.TabIndex = 22; this._lblLabels_11.Enabled = true; this._lblLabels_11.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_11.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_11.UseMnemonic = true; this._lblLabels_11.Visible = true; this._lblLabels_11.AutoSize = true; this._lblLabels_11.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_11.Name = "_lblLabels_11"; this._lblLabels_10.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_10.BackColor = System.Drawing.Color.Transparent; this._lblLabels_10.Text = "User ID:"; this._lblLabels_10.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_10.Size = new System.Drawing.Size(39, 13); this._lblLabels_10.Location = new System.Drawing.Point(19, 18); this._lblLabels_10.TabIndex = 20; this._lblLabels_10.Enabled = true; this._lblLabels_10.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_10.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_10.UseMnemonic = true; this._lblLabels_10.Visible = true; this._lblLabels_10.AutoSize = true; this._lblLabels_10.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_10.Name = "_lblLabels_10"; this._txtFields_1.AutoSize = false; this._txtFields_1.Size = new System.Drawing.Size(31, 19); this._txtFields_1.Location = new System.Drawing.Point(87, 66); this._txtFields_1.TabIndex = 6; this._txtFields_1.Text = "Miss"; this._txtFields_1.AcceptsReturn = true; this._txtFields_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_1.BackColor = System.Drawing.SystemColors.Window; this._txtFields_1.CausesValidation = true; this._txtFields_1.Enabled = true; this._txtFields_1.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_1.HideSelection = true; this._txtFields_1.ReadOnly = false; this._txtFields_1.MaxLength = 0; this._txtFields_1.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_1.Multiline = false; this._txtFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_1.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_1.TabStop = true; this._txtFields_1.Visible = true; this._txtFields_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_1.Name = "_txtFields_1"; this._txtFields_2.AutoSize = false; this._txtFields_2.Size = new System.Drawing.Size(118, 19); this._txtFields_2.Location = new System.Drawing.Point(120, 66); this._txtFields_2.TabIndex = 7; this._txtFields_2.AcceptsReturn = true; this._txtFields_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_2.BackColor = System.Drawing.SystemColors.Window; this._txtFields_2.CausesValidation = true; this._txtFields_2.Enabled = true; this._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_2.HideSelection = true; this._txtFields_2.ReadOnly = false; this._txtFields_2.MaxLength = 0; this._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_2.Multiline = false; this._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_2.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_2.TabStop = true; this._txtFields_2.Visible = true; this._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_2.Name = "_txtFields_2"; this._txtFields_4.AutoSize = false; this._txtFields_4.Size = new System.Drawing.Size(151, 19); this._txtFields_4.Location = new System.Drawing.Point(87, 87); this._txtFields_4.TabIndex = 9; this._txtFields_4.AcceptsReturn = true; this._txtFields_4.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_4.BackColor = System.Drawing.SystemColors.Window; this._txtFields_4.CausesValidation = true; this._txtFields_4.Enabled = true; this._txtFields_4.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_4.HideSelection = true; this._txtFields_4.ReadOnly = false; this._txtFields_4.MaxLength = 0; this._txtFields_4.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_4.Multiline = false; this._txtFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_4.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_4.TabStop = true; this._txtFields_4.Visible = true; this._txtFields_4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_4.Name = "_txtFields_4"; this._txtFields_5.AutoSize = false; this._txtFields_5.Size = new System.Drawing.Size(151, 19); this._txtFields_5.Location = new System.Drawing.Point(318, 66); this._txtFields_5.TabIndex = 11; this._txtFields_5.AcceptsReturn = true; this._txtFields_5.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_5.BackColor = System.Drawing.SystemColors.Window; this._txtFields_5.CausesValidation = true; this._txtFields_5.Enabled = true; this._txtFields_5.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_5.HideSelection = true; this._txtFields_5.ReadOnly = false; this._txtFields_5.MaxLength = 0; this._txtFields_5.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_5.Multiline = false; this._txtFields_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_5.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_5.TabStop = true; this._txtFields_5.Visible = true; this._txtFields_5.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_5.Name = "_txtFields_5"; this._txtFields_7.AutoSize = false; this._txtFields_7.Size = new System.Drawing.Size(151, 19); this._txtFields_7.Location = new System.Drawing.Point(87, 120); this._txtFields_7.TabIndex = 15; this._txtFields_7.AcceptsReturn = true; this._txtFields_7.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_7.BackColor = System.Drawing.SystemColors.Window; this._txtFields_7.CausesValidation = true; this._txtFields_7.Enabled = true; this._txtFields_7.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_7.HideSelection = true; this._txtFields_7.ReadOnly = false; this._txtFields_7.MaxLength = 0; this._txtFields_7.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_7.Multiline = false; this._txtFields_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_7.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_7.TabStop = true; this._txtFields_7.Visible = true; this._txtFields_7.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_7.Name = "_txtFields_7"; this._txtFields_8.AutoSize = false; this._txtFields_8.Size = new System.Drawing.Size(151, 19); this._txtFields_8.Location = new System.Drawing.Point(318, 120); this._txtFields_8.TabIndex = 17; this._txtFields_8.AcceptsReturn = true; this._txtFields_8.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_8.BackColor = System.Drawing.SystemColors.Window; this._txtFields_8.CausesValidation = true; this._txtFields_8.Enabled = true; this._txtFields_8.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_8.HideSelection = true; this._txtFields_8.ReadOnly = false; this._txtFields_8.MaxLength = 0; this._txtFields_8.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_8.Multiline = false; this._txtFields_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_8.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_8.TabStop = true; this._txtFields_8.Visible = true; this._txtFields_8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_8.Name = "_txtFields_8"; this._txtFields_13.AutoSize = false; this._txtFields_13.Size = new System.Drawing.Size(151, 19); this._txtFields_13.Location = new System.Drawing.Point(318, 87); this._txtFields_13.TabIndex = 13; this._txtFields_13.AcceptsReturn = true; this._txtFields_13.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this._txtFields_13.BackColor = System.Drawing.SystemColors.Window; this._txtFields_13.CausesValidation = true; this._txtFields_13.Enabled = true; this._txtFields_13.ForeColor = System.Drawing.SystemColors.WindowText; this._txtFields_13.HideSelection = true; this._txtFields_13.ReadOnly = false; this._txtFields_13.MaxLength = 0; this._txtFields_13.Cursor = System.Windows.Forms.Cursors.IBeam; this._txtFields_13.Multiline = false; this._txtFields_13.RightToLeft = System.Windows.Forms.RightToLeft.No; this._txtFields_13.ScrollBars = System.Windows.Forms.ScrollBars.None; this._txtFields_13.TabStop = true; this._txtFields_13.Visible = true; this._txtFields_13.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._txtFields_13.Name = "_txtFields_13"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(486, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 0; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdFPR.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdFPR.Text = "&Finger Print Registration"; this.cmdFPR.Size = new System.Drawing.Size(73, 29); this.cmdFPR.Location = new System.Drawing.Point(304, 3); this.cmdFPR.TabIndex = 35; this.cmdFPR.TabStop = false; this.cmdFPR.BackColor = System.Drawing.SystemColors.Control; this.cmdFPR.CausesValidation = true; this.cmdFPR.Enabled = true; this.cmdFPR.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdFPR.Cursor = System.Windows.Forms.Cursors.Default; this.cmdFPR.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdFPR.Name = "cmdFPR"; this.cmdPOSsecurity.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPOSsecurity.Text = "&Point Of Sale Permissions"; this.cmdPOSsecurity.Size = new System.Drawing.Size(73, 29); this.cmdPOSsecurity.Location = new System.Drawing.Point(207, 3); this.cmdPOSsecurity.TabIndex = 2; this.cmdPOSsecurity.TabStop = false; this.cmdPOSsecurity.BackColor = System.Drawing.SystemColors.Control; this.cmdPOSsecurity.CausesValidation = true; this.cmdPOSsecurity.Enabled = true; this.cmdPOSsecurity.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPOSsecurity.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPOSsecurity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPOSsecurity.Name = "cmdPOSsecurity"; this.cmdBOsecurity.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdBOsecurity.Text = "&Back Office Permissions"; this.cmdBOsecurity.Size = new System.Drawing.Size(73, 29); this.cmdBOsecurity.Location = new System.Drawing.Point(104, 3); this.cmdBOsecurity.TabIndex = 30; this.cmdBOsecurity.TabStop = false; this.cmdBOsecurity.BackColor = System.Drawing.SystemColors.Control; this.cmdBOsecurity.CausesValidation = true; this.cmdBOsecurity.Enabled = true; this.cmdBOsecurity.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdBOsecurity.Cursor = System.Windows.Forms.Cursors.Default; this.cmdBOsecurity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdBOsecurity.Name = "cmdBOsecurity"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.TabIndex = 3; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(405, 3); this.cmdClose.TabIndex = 1; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lbl_1.BackColor = System.Drawing.Color.Transparent; this._lbl_1.Text = "Employee No. "; this._lbl_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_1.Size = new System.Drawing.Size(77, 14); this._lbl_1.Location = new System.Drawing.Point(400, 44); this._lbl_1.TabIndex = 38; this._lbl_1.Enabled = true; this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_1.UseMnemonic = true; this._lbl_1.Visible = true; this._lbl_1.AutoSize = true; this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_1.Name = "_lbl_1"; this.Line1.X1 = 16; this.Line1.X2 = 468; this.Line1.Y1 = 110; this.Line1.Y2 = 110; this.Line1.BorderColor = System.Drawing.SystemColors.WindowText; this.Line1.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this.Line1.BorderWidth = 1; this.Line1.Visible = true; this.Line1.Name = "Line1"; this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.Size = new System.Drawing.Size(472, 171); this._Shape1_0.Location = new System.Drawing.Point(6, 166); this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_0.BorderWidth = 1; this._Shape1_0.FillColor = System.Drawing.Color.Black; this._Shape1_0.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_0.Visible = true; this._Shape1_0.Name = "_Shape1_0"; this._lbl_0.BackColor = System.Drawing.Color.Transparent; this._lbl_0.Text = "&2. Security"; this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_0.Size = new System.Drawing.Size(64, 13); this._lbl_0.Location = new System.Drawing.Point(8, 150); this._lbl_0.TabIndex = 18; this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_0.Enabled = true; this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.UseMnemonic = true; this._lbl_0.Visible = true; this._lbl_0.AutoSize = true; this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_0.Name = "_lbl_0"; this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_2.BackColor = System.Drawing.Color.Transparent; this._lblLabels_2.Text = "First Name:"; this._lblLabels_2.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_2.Size = new System.Drawing.Size(55, 13); this._lblLabels_2.Location = new System.Drawing.Point(27, 66); this._lblLabels_2.TabIndex = 5; this._lblLabels_2.Enabled = true; this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_2.UseMnemonic = true; this._lblLabels_2.Visible = true; this._lblLabels_2.AutoSize = true; this._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_2.Name = "_lblLabels_2"; this._lblLabels_4.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_4.BackColor = System.Drawing.Color.Transparent; this._lblLabels_4.Text = "Surname:"; this._lblLabels_4.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_4.Size = new System.Drawing.Size(46, 13); this._lblLabels_4.Location = new System.Drawing.Point(33, 87); this._lblLabels_4.TabIndex = 8; this._lblLabels_4.Enabled = true; this._lblLabels_4.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_4.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_4.UseMnemonic = true; this._lblLabels_4.Visible = true; this._lblLabels_4.AutoSize = true; this._lblLabels_4.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_4.Name = "_lblLabels_4"; this._lblLabels_5.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_5.BackColor = System.Drawing.Color.Transparent; this._lblLabels_5.Text = "Position:"; this._lblLabels_5.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_5.Size = new System.Drawing.Size(40, 13); this._lblLabels_5.Location = new System.Drawing.Point(258, 66); this._lblLabels_5.TabIndex = 10; this._lblLabels_5.Enabled = true; this._lblLabels_5.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_5.UseMnemonic = true; this._lblLabels_5.Visible = true; this._lblLabels_5.AutoSize = true; this._lblLabels_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_5.Name = "_lblLabels_5"; this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_7.BackColor = System.Drawing.Color.Transparent; this._lblLabels_7.Text = "Cell:"; this._lblLabels_7.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_7.Size = new System.Drawing.Size(22, 13); this._lblLabels_7.Location = new System.Drawing.Point(60, 120); this._lblLabels_7.TabIndex = 14; this._lblLabels_7.Enabled = true; this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_7.UseMnemonic = true; this._lblLabels_7.Visible = true; this._lblLabels_7.AutoSize = true; this._lblLabels_7.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_7.Name = "_lblLabels_7"; this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_8.BackColor = System.Drawing.Color.Transparent; this._lblLabels_8.Text = "Telephone:"; this._lblLabels_8.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_8.Size = new System.Drawing.Size(55, 13); this._lblLabels_8.Location = new System.Drawing.Point(243, 120); this._lblLabels_8.TabIndex = 16; this._lblLabels_8.Enabled = true; this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_8.UseMnemonic = true; this._lblLabels_8.Visible = true; this._lblLabels_8.AutoSize = true; this._lblLabels_8.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_8.Name = "_lblLabels_8"; this._lblLabels_13.TextAlign = System.Drawing.ContentAlignment.TopRight; this._lblLabels_13.BackColor = System.Drawing.Color.Transparent; this._lblLabels_13.Text = "ID Number:"; this._lblLabels_13.ForeColor = System.Drawing.SystemColors.WindowText; this._lblLabels_13.Size = new System.Drawing.Size(55, 13); this._lblLabels_13.Location = new System.Drawing.Point(243, 87); this._lblLabels_13.TabIndex = 12; this._lblLabels_13.Enabled = true; this._lblLabels_13.Cursor = System.Windows.Forms.Cursors.Default; this._lblLabels_13.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lblLabels_13.UseMnemonic = true; this._lblLabels_13.Visible = true; this._lblLabels_13.AutoSize = true; this._lblLabels_13.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lblLabels_13.Name = "_lblLabels_13"; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Text = "&1. General"; this._lbl_5.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this._lbl_5.Size = new System.Drawing.Size(61, 13); this._lbl_5.Location = new System.Drawing.Point(8, 44); this._lbl_5.TabIndex = 4; this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_5.Enabled = true; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.UseMnemonic = true; this._lbl_5.Visible = true; this._lbl_5.AutoSize = true; this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_5.Name = "_lbl_5"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(472, 85); this._Shape1_2.Location = new System.Drawing.Point(6, 60); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this.Controls.Add(chkController); this.Controls.Add(Frame1); this.Controls.Add(cmdBuild); this.Controls.Add(_chkFields_2); this.Controls.Add(_frmSecurity_1); this.Controls.Add(_frmSecurity_0); this.Controls.Add(_txtFields_1); this.Controls.Add(_txtFields_2); this.Controls.Add(_txtFields_4); this.Controls.Add(_txtFields_5); this.Controls.Add(_txtFields_7); this.Controls.Add(_txtFields_8); this.Controls.Add(_txtFields_13); this.Controls.Add(picButtons); this.Controls.Add(_lbl_1); this.ShapeContainer1.Shapes.Add(Line1); this.ShapeContainer1.Shapes.Add(_Shape1_0); this.Controls.Add(_lbl_0); this.Controls.Add(_lblLabels_2); this.Controls.Add(_lblLabels_4); this.Controls.Add(_lblLabels_5); this.Controls.Add(_lblLabels_7); this.Controls.Add(_lblLabels_8); this.Controls.Add(_lblLabels_13); this.Controls.Add(_lbl_5); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.Controls.Add(ShapeContainer1); this.Frame1.Controls.Add(txtComm); this.Frame1.Controls.Add(Label2); this._frmSecurity_1.Controls.Add(cmbDraw); this._frmSecurity_1.Controls.Add(_txtFields_12); this._frmSecurity_1.Controls.Add(_lblLabels_0); this._frmSecurity_1.Controls.Add(Label1); this._frmSecurity_1.Controls.Add(_lblLabels_12); this._frmSecurity_0.Controls.Add(_txtFields_11); this._frmSecurity_0.Controls.Add(_txtFields_10); this._frmSecurity_0.Controls.Add(_lblLabels_11); this._frmSecurity_0.Controls.Add(_lblLabels_10); this.picButtons.Controls.Add(cmdFPR); this.picButtons.Controls.Add(cmdPOSsecurity); this.picButtons.Controls.Add(cmdBOsecurity); this.picButtons.Controls.Add(cmdCancel); this.picButtons.Controls.Add(cmdClose); //Me.chkFields.SetIndex(_chkFields_2, CType(2, Short)) //Me.frmSecurity.SetIndex(_frmSecurity_1, CType(1, Short)) //Me.frmSecurity.SetIndex(_frmSecurity_0, CType(0, Short)) //Me.lbl.SetIndex(_lbl_1, CType(1, Short)) //Me.lbl.SetIndex(_lbl_0, CType(0, Short)) //Me.lbl.SetIndex(_lbl_5, CType(5, Short)) //Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short)) //Me.lblLabels.SetIndex(_lblLabels_12, CType(12, Short)) //Me.lblLabels.SetIndex(_lblLabels_11, CType(11, Short)) //Me.lblLabels.SetIndex(_lblLabels_10, CType(10, Short)) //Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short)) //Me.lblLabels.SetIndex(_lblLabels_4, CType(4, Short)) //M() ''e.lblLabels.SetIndex(_lblLabels_5, CType(5, Short)) //M() 'e.lblLabels.SetIndex(_lblLabels_7, CType(7, Short)) //M() 'e.lblLabels.SetIndex(_lblLabels_8, CType(8, Short)) //Me.lblLabels.SetIndex(_lblLabels_13, CType(13, Short)) //Me.txtFields.SetIndex(_txtFields_12, CType(12, Short)) //Me.txtFields.SetIndex(_txtFields_11, CType(11, Short)) //Me.txtFields.SetIndex(_txtFields_10, CType(10, Short)) //Me.txtFields.SetIndex(_txtFields_1, CType(1, Short)) //Me.txtFields.SetIndex(_txtFields_2, CType(2, Short)) //Me.txtFields.SetIndex(_txtFields_4, CType(4, Short)) //Me.txtFields.SetIndex(_txtFields_5, CType(5, Short)) //Me.txtFields.SetIndex(_txtFields_7, CType(7, Short)) //Me.txtFields.SetIndex(_txtFields_8, CType(8, Short)) //Me.txtFields.SetIndex(_txtFields_13, CType(13, Short)) this.Shape1.SetIndex(_Shape1_0, Convert.ToInt16(0)); this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.frmSecurity, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.chkFields, System.ComponentModel.ISupportInitialize).EndInit() this.Frame1.ResumeLayout(false); this._frmSecurity_1.ResumeLayout(false); this._frmSecurity_0.ResumeLayout(false); this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileUserStatisticBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileUserStatisticProfileUserStatisticStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileUserStatisticUserStatisticName))] public partial class LocalLBProfileUserStatistic : iControlInterface { public LocalLBProfileUserStatistic() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileUserStatisticProfileUserStatisticStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileUserStatisticProfileUserStatisticStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileUserStatisticProfileUserStatisticStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileUserStatisticProfileUserStatisticStatistics)(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_statistic_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileUserStatisticUserStatisticName [] [] get_statistic_name( string [] profile_names, LocalLBProfileUserStatisticUserStatisticKey [] [] statistic_keys ) { object [] results = this.Invoke("get_statistic_name", new object [] { profile_names, statistic_keys}); return ((LocalLBProfileUserStatisticUserStatisticName [] [])(results[0])); } public System.IAsyncResult Beginget_statistic_name(string [] profile_names,LocalLBProfileUserStatisticUserStatisticKey [] [] statistic_keys, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistic_name", new object[] { profile_names, statistic_keys}, callback, asyncState); } public LocalLBProfileUserStatisticUserStatisticName [] [] Endget_statistic_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileUserStatisticUserStatisticName [] [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileUserStatisticProfileUserStatisticStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileUserStatisticProfileUserStatisticStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileUserStatisticProfileUserStatisticStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileUserStatisticProfileUserStatisticStatistics)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_statistic_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileUserStatistic", RequestNamespace="urn:iControl:LocalLB/ProfileUserStatistic", ResponseNamespace="urn:iControl:LocalLB/ProfileUserStatistic")] public void set_statistic_name( string [] profile_names, LocalLBProfileUserStatisticUserStatisticName [] [] statistic_names ) { this.Invoke("set_statistic_name", new object [] { profile_names, statistic_names}); } public System.IAsyncResult Beginset_statistic_name(string [] profile_names,LocalLBProfileUserStatisticUserStatisticName [] [] statistic_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_statistic_name", new object[] { profile_names, statistic_names}, callback, asyncState); } public void Endset_statistic_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileUserStatistic.UserStatisticKey", Namespace = "urn:iControl")] public enum LocalLBProfileUserStatisticUserStatisticKey { USER_STATISTIC_UNDEFINED, USER_STATISTIC_1, USER_STATISTIC_2, USER_STATISTIC_3, USER_STATISTIC_4, USER_STATISTIC_5, USER_STATISTIC_6, USER_STATISTIC_7, USER_STATISTIC_8, USER_STATISTIC_9, USER_STATISTIC_10, USER_STATISTIC_11, USER_STATISTIC_12, USER_STATISTIC_13, USER_STATISTIC_14, USER_STATISTIC_15, USER_STATISTIC_16, USER_STATISTIC_17, USER_STATISTIC_18, USER_STATISTIC_19, USER_STATISTIC_20, USER_STATISTIC_21, USER_STATISTIC_22, USER_STATISTIC_23, USER_STATISTIC_24, USER_STATISTIC_25, USER_STATISTIC_26, USER_STATISTIC_27, USER_STATISTIC_28, USER_STATISTIC_29, USER_STATISTIC_30, USER_STATISTIC_31, USER_STATISTIC_32, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileUserStatistic.ProfileUserStatisticStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileUserStatisticProfileUserStatisticStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private LocalLBProfileUserStatisticUserStatistic [] statisticsField; public LocalLBProfileUserStatisticUserStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileUserStatistic.ProfileUserStatisticStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileUserStatisticProfileUserStatisticStatistics { private LocalLBProfileUserStatisticProfileUserStatisticStatisticEntry [] statisticsField; public LocalLBProfileUserStatisticProfileUserStatisticStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileUserStatistic.UserStatistic", Namespace = "urn:iControl")] public partial class LocalLBProfileUserStatisticUserStatistic { private LocalLBProfileUserStatisticUserStatisticKey statistic_keyField; public LocalLBProfileUserStatisticUserStatisticKey statistic_key { get { return this.statistic_keyField; } set { this.statistic_keyField = value; } } private CommonULong64 valueField; public CommonULong64 value { get { return this.valueField; } set { this.valueField = value; } } private long time_stampField; public long time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileUserStatistic.UserStatisticName", Namespace = "urn:iControl")] public partial class LocalLBProfileUserStatisticUserStatisticName { private LocalLBProfileUserStatisticUserStatisticKey statistic_keyField; public LocalLBProfileUserStatisticUserStatisticKey statistic_key { get { return this.statistic_keyField; } set { this.statistic_keyField = value; } } private LocalLBProfileString statistic_nameField; public LocalLBProfileString statistic_name { get { return this.statistic_nameField; } set { this.statistic_nameField = value; } } }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ShiftLeftLogical128BitLaneInt321() { var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321(); 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(); // 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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321 testClass) { var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[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.ShiftLeftLogical128BitLane( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneInt321(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(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<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 2048) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical128BitLane)}<Int32>(Vector128<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//! \file ImageEPA.cs //! \date Fri May 01 03:34:26 2015 //! \brief Pajamas Adventure System image format. // // Copyright (C) 2015 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Text; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.Pajamas { internal class EpaMetaData : ImageMetaData { public int Mode; public int ColorType; } [Export(typeof(ImageFormat))] public class EpaFormat : ImageFormat { public override string Tag { get { return "EPA"; } } public override string Description { get { return "Pajamas Adventure System image"; } } public override uint Signature { get { return 0x01015045u; } } // 'EP' public EpaFormat () { Signatures = new uint[] { 0x01015045u, 0x02015045u }; } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("EpaFormat.Write not implemented"); } public override ImageMetaData ReadMetaData (Stream stream) { using (var header = new ArcView.Reader (stream)) { var info = new EpaMetaData(); info.Mode = header.ReadInt32() >> 24; info.ColorType = header.ReadInt32() & 0xff; switch (info.ColorType) { case 0: info.BPP = 8; break; case 1: info.BPP = 24; break; case 2: info.BPP = 32; break; case 3: info.BPP = 15; break; case 4: info.BPP = 8; break; default: return null; } info.Width = header.ReadUInt32(); info.Height = header.ReadUInt32(); if (2 == info.Mode) { info.OffsetX = header.ReadInt32(); info.OffsetY = header.ReadInt32(); } return info; } } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = info as EpaMetaData; if (null == meta) throw new ArgumentException ("EpaFormat.Read should be supplied with EpaMetaData", "info"); stream.Position = 2 == meta.Mode ? 0x18 : 0x10; var reader = new Reader (stream, meta); reader.Unpack(); return ImageData.Create (meta, reader.Format, reader.Palette, reader.Data); } internal class Reader { private Stream m_input; private int m_width; private int m_height; private int m_pixel_size; private byte[] m_output; public PixelFormat Format { get; private set; } public BitmapPalette Palette { get; private set; } public byte[] Data { get { return m_output; } } public Reader (Stream stream, EpaMetaData info) { m_input = stream; switch (info.ColorType) { case 0: m_pixel_size = 1; Format = PixelFormats.Indexed8; break; case 1: m_pixel_size = 3; Format = PixelFormats.Bgr24; break; case 2: m_pixel_size = 4; Format = PixelFormats.Bgra32; break; case 3: m_pixel_size = 2; Format = PixelFormats.Bgr555; break; case 4: m_pixel_size = 1; Format = PixelFormats.Indexed8; break; default: throw new NotSupportedException ("Not supported EPA color depth"); } m_width = (int)info.Width; m_height = (int)info.Height; m_output = new byte[info.Width*info.Height*m_pixel_size]; if (8 == info.BPP) ReadPalette(); } private void ReadPalette () { var palette_data = new byte[0x300]; if (palette_data.Length != m_input.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException(); var palette = new Color[0x100]; for (int i = 0; i < palette.Length; ++i) { palette[i] = Color.FromRgb (palette_data[i*3+2], palette_data[i*3+1], palette_data[i*3]); } Palette = new BitmapPalette (palette); } public void Unpack () { int dst = 0; var offset_table = new int[16]; offset_table[0] = 0; offset_table[1] = 1; offset_table[2] = m_width; offset_table[3] = m_width + 1; offset_table[4] = 2; offset_table[5] = m_width - 1; offset_table[6] = m_width * 2; offset_table[7] = 3; offset_table[8] = (m_width + 1) * 2; offset_table[9] = m_width + 2; offset_table[10] = m_width * 2 + 1; offset_table[11] = m_width * 2 - 1; offset_table[12] = (m_width - 1) * 2; offset_table[13] = m_width - 2; offset_table[14] = m_width * 3; offset_table[15] = 4; while (dst < m_output.Length) { int flag = m_input.ReadByte(); if (-1 == flag) throw new InvalidFormatException ("Unexpected end of file"); if (0 == (flag & 0xf0)) { int count = flag; if (dst + count > m_output.Length) count = m_output.Length - dst; if (count != m_input.Read (m_output, dst, count)) throw new InvalidFormatException ("Unexpected end of file"); dst += count; } else { int count; if (0 != (flag & 8)) { count = m_input.ReadByte(); if (-1 == count) throw new InvalidFormatException ("Unexpected end of file"); count += (flag & 7) << 8; } else count = flag & 7; if (dst + count > m_output.Length) break; Binary.CopyOverlapped (m_output, dst-offset_table[flag >> 4], dst, count); dst += count; } } if (m_pixel_size > 1) { var bitmap = new byte[m_output.Length]; int stride = m_width * m_pixel_size; int i = 0; for (int p = 0; p < m_pixel_size; ++p) { for (int y = 0; y < m_height; ++y) { int pixel = y * stride + p; for (int x = 0; x < m_width; ++x) { bitmap[pixel] = m_output[i++]; pixel += m_pixel_size; } } } m_output = bitmap; } } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // FirstQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// First tries to discover the first element in the source, optionally matching a /// predicate. All partitions search in parallel, publish the lowest index for a /// candidate match, and reach a barrier. Only the partition that "wins" the race, /// i.e. who found the candidate with the smallest index, will yield an element. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class FirstQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { private readonly Func<TSource, bool> _predicate; // The optional predicate used during the search. private readonly bool _prematureMergeNeeded; // Whether to prematurely merge the input of this operator. //--------------------------------------------------------------------------------------- // Initializes a new first operator. // // Arguments: // child - the child whose data we will reverse // internal FirstQueryOperator(IEnumerable<TSource> child, Func<TSource, bool> predicate) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); _predicate = predicate; _prematureMergeNeeded = Child.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the child operator. QueryResults<TSource> childQueryResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { // If the index is not at least increasing, we need to reindex. if (_prematureMergeNeeded) { ListQueryResults<TSource> listResults = ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings); WrapHelper<int>(listResults.GetPartitionedStream(), recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Generate the shared data. FirstQueryOperatorState<TKey> operatorState = new FirstQueryOperatorState<TKey>(); CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>( partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new FirstQueryOperatorEnumerator<TKey>( inputStream[i], _predicate, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer, i); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // [ExcludeFromCodeCoverage] internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { Debug.Fail("This method should never be called as fallback to sequential is handled in ParallelEnumerable.First()."); throw new NotSupportedException(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the first operation. // class FirstQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, int> { private QueryOperatorEnumerator<TSource, TKey> _source; // The data source to enumerate. private Func<TSource, bool> _predicate; // The optional predicate used during the search. private bool _alreadySearched; // Set once the enumerator has performed the search. private int _partitionId; // ID of this partition // Data shared among partitions. private FirstQueryOperatorState<TKey> _operatorState; // The current first candidate and its partition index. private CountdownEvent _sharedBarrier; // Shared barrier, signaled when partitions find their 1st element. private CancellationToken _cancellationToken; // Token used to cancel this operator. private IComparer<TKey> _keyComparer; // Comparer for the order keys //--------------------------------------------------------------------------------------- // Instantiates a new enumerator. // internal FirstQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TKey> source, Func<TSource, bool> predicate, FirstQueryOperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancellationToken, IComparer<TKey> keyComparer, int partitionId) { Debug.Assert(source != null); Debug.Assert(operatorState != null); Debug.Assert(sharedBarrier != null); Debug.Assert(keyComparer != null); _source = source; _predicate = predicate; _operatorState = operatorState; _sharedBarrier = sharedBarrier; _cancellationToken = cancellationToken; _keyComparer = keyComparer; _partitionId = partitionId; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TSource currentElement, ref int currentKey) { Debug.Assert(_source != null); if (_alreadySearched) { return false; } // Look for the lowest element. TSource candidate = default(TSource); TKey candidateKey = default(TKey); try { TSource value = default(TSource); TKey key = default(TKey); int i = 0; while (_source.MoveNext(ref value, ref key)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If the predicate is null or the current element satisfies it, we have found the // current partition's "candidate" for the first element. Note it. if (_predicate == null || _predicate(value)) { candidate = value; candidateKey = key; lock (_operatorState) { if (_operatorState._partitionId == -1 || _keyComparer.Compare(candidateKey, _operatorState._key) < 0) { _operatorState._key = candidateKey; _operatorState._partitionId = _partitionId; } } break; } } } finally { // No matter whether we exit due to an exception or normal completion, we must ensure // that we signal other partitions that we have completed. Otherwise, we can cause deadlocks. _sharedBarrier.Signal(); } _alreadySearched = true; // Wait only if we may have the result if (_partitionId == _operatorState._partitionId) { _sharedBarrier.Wait(_cancellationToken); // Now re-read the shared index. If it's the same as ours, we won and return true. if (_partitionId == _operatorState._partitionId) { currentElement = candidate; currentKey = 0; // 1st (and only) element, so we hardcode the output index to 0. return true; } } // If we got here, we didn't win. Return false. return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } class FirstQueryOperatorState<TKey> { internal TKey _key; internal int _partitionId = -1; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; namespace Platform.Support.Windows { #pragma warning disable CS0649 /// <summary> /// Imports from Shell32.dll /// </summary> #if !INTEROP internal class Shell32 #else public class Shell32 #endif { [DllImport(ExternDll.Shell32, CharSet = CharSet.Unicode)] public static extern bool PathYetAnotherMakeUniqueName( StringBuilder pszUniqueName, string pszPath, string pszShort, string pszFileSpec); [DllImport(ExternDll.Shell32)] public static extern bool PathIsSlow(string pszFile, int attr); [DllImport(ExternDll.Shell32)] public static extern IntPtr FindExecutable(string lpFile, string lpDirectory, [Out] StringBuilder lpResult); [DllImport(ExternDll.Shell32)] public static extern int SHGetInstanceExplorer( out IntPtr ppunk); [DllImport(ExternDll.Shell32)] public static extern int SHGetSpecialFolderLocation( IntPtr hwndOwner, int nFolder, out IntPtr ppidl); [DllImport(ExternDll.Shell32)] public static extern Int32 SHGetFolderLocation( IntPtr hwndOwner, Int32 nFolder, IntPtr hToken, UInt32 dwReserved, out IntPtr ppidl); [DllImport(ExternDll.Shell32)] public static extern Int32 SHGetKnownFolderIDList( ref Guid rfid, UInt32 dwFlags, IntPtr hToken, out IntPtr ppidl); [DllImport(ExternDll.Shell32)] public static extern void ILFree(IntPtr pidl); [DllImport(ExternDll.Shell32, CharSet = CharSet.Unicode)] public static extern void SHAddToRecentDocs(uint uFlags, [MarshalAs(UnmanagedType.LPTStr)]string pv); [DllImport(ExternDll.Shell32, CharSet = CharSet.Unicode)] public static extern bool SHGetPathFromIDList(IntPtr pidl, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath); [DllImport(ExternDll.Shell32)] public static extern int SHGetMalloc(out IntPtr ppMalloc); [DllImport(ExternDll.Shell32)] public static extern int SHCreateDirectory( IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszPath); [DllImport(ExternDll.Shell32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int SHCreateItemFromParsingName( [MarshalAs(UnmanagedType.LPWStr)] string path, // The following parameter is not used - binding context. IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem2 shellItem); /// <summary> /// Gets the HIcon for the icon associated with a file /// </summary> [DllImport(ExternDll.Shell32)] public static extern IntPtr ExtractAssociatedIcon( IntPtr hInst, string lpIconPath, ref short lpiIcon ); /// <summary> /// Retrieves an icon from an icon, exe, or dll file by index /// </summary> [DllImport(ExternDll.Shell32)] public static extern IntPtr ExtractIcon( IntPtr hInst, string lpszExeFileName, Int32 nIconIndex ); [DllImport(ExternDll.Shell32, SetLastError = true)] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); [DllImport(ExternDll.Shell32)] public static extern void SetCurrentProcessExplicitAppUserModelID( [MarshalAs(UnmanagedType.LPWStr)] string AppID); [DllImport(ExternDll.Shell32)] public static extern void GetCurrentProcessExplicitAppUserModelID( [Out(), MarshalAs(UnmanagedType.LPWStr)] out string AppID); [DllImport(ExternDll.Shell32)] public static extern int SHGetPropertyStoreForWindow( IntPtr hwnd, ref Guid iid /*IID_IPropertyStore*/, [Out(), MarshalAs(UnmanagedType.Interface)] out IPropertyStore propertyStore); /// <summary> /// Indicate flags that modify the property store object retrieved by methods /// that create a property store, such as IShellItem2::GetPropertyStore or /// IPropertyStoreFactory::GetPropertyStore. /// </summary> [Flags] public enum GETPROPERTYSTOREFLAGS : uint { /// <summary> /// Meaning to a calling process: Return a read-only property store that contains all /// properties. Slow items (offline files) are not opened. /// Combination with other flags: Can be overridden by other flags. /// </summary> GPS_DEFAULT = 0, /// <summary> /// Meaning to a calling process: Include only properties directly from the property /// handler, which opens the file on the disk, network, or device. Meaning to a file /// folder: Only include properties directly from the handler. /// /// Meaning to other folders: When delegating to a file folder, pass this flag on /// to the file folder; do not do any multiplexing (MUX). When not delegating to a /// file folder, ignore this flag instead of returning a failure code. /// /// Combination with other flags: Cannot be combined with GPS_TEMPORARY, /// GPS_FASTPROPERTIESONLY, or GPS_BESTEFFORT. /// </summary> GPS_HANDLERPROPERTIESONLY = 0x1, /// <summary> /// Meaning to a calling process: Can write properties to the item. /// Note: The store may contain fewer properties than a read-only store. /// /// Meaning to a file folder: ReadWrite. /// /// Meaning to other folders: ReadWrite. Note: When using default MUX, /// return a single unmultiplexed store because the default MUX does not support ReadWrite. /// /// Combination with other flags: Cannot be combined with GPS_TEMPORARY, GPS_FASTPROPERTIESONLY, /// GPS_BESTEFFORT, or GPS_DELAYCREATION. Implies GPS_HANDLERPROPERTIESONLY. /// </summary> GPS_READWRITE = 0x2, /// <summary> /// Meaning to a calling process: Provides a writable store, with no initial properties, /// that exists for the lifetime of the Shell item instance; basically, a property bag /// attached to the item instance. /// /// Meaning to a file folder: Not applicable. Handled by the Shell item. /// /// Meaning to other folders: Not applicable. Handled by the Shell item. /// /// Combination with other flags: Cannot be combined with any other flag. Implies GPS_READWRITE /// </summary> GPS_TEMPORARY = 0x4, /// <summary> /// Meaning to a calling process: Provides a store that does not involve reading from the /// disk or network. Note: Some values may be different, or missing, compared to a store /// without this flag. /// /// Meaning to a file folder: Include the "innate" and "fallback" stores only. Do not load the handler. /// /// Meaning to other folders: Include only properties that are available in memory or can /// be computed very quickly (no properties from disk, network, or peripheral IO devices). /// This is normally only data sources from the IDLIST. When delegating to other folders, pass this flag on to them. /// /// Combination with other flags: Cannot be combined with GPS_TEMPORARY, GPS_READWRITE, /// GPS_HANDLERPROPERTIESONLY, or GPS_DELAYCREATION. /// </summary> GPS_FASTPROPERTIESONLY = 0x8, /// <summary> /// Meaning to a calling process: Open a slow item (offline file) if necessary. /// Meaning to a file folder: Retrieve a file from offline storage, if necessary. /// Note: Without this flag, the handler is not created for offline files. /// /// Meaning to other folders: Do not return any properties that are very slow. /// /// Combination with other flags: Cannot be combined with GPS_TEMPORARY or GPS_FASTPROPERTIESONLY. /// </summary> GPS_OPENSLOWITEM = 0x10, /// <summary> /// Meaning to a calling process: Delay memory-intensive operations, such as file access, until /// a property is requested that requires such access. /// /// Meaning to a file folder: Do not create the handler until needed; for example, either /// GetCount/GetAt or GetValue, where the innate store does not satisfy the request. /// Note: GetValue might fail due to file access problems. /// /// Meaning to other folders: If the folder has memory-intensive properties, such as /// delegating to a file folder or network access, it can optimize performance by /// supporting IDelayedPropertyStoreFactory and splitting up its properties into a /// fast and a slow store. It can then use delayed MUX to recombine them. /// /// Combination with other flags: Cannot be combined with GPS_TEMPORARY or /// GPS_READWRITE /// </summary> GPS_DELAYCREATION = 0x20, /// <summary> /// Meaning to a calling process: Succeed at getting the store, even if some /// properties are not returned. Note: Some values may be different, or missing, /// compared to a store without this flag. /// /// Meaning to a file folder: Succeed and return a store, even if the handler or /// innate store has an error during creation. Only fail if substores fail. /// /// Meaning to other folders: Succeed on getting the store, even if some properties /// are not returned. /// /// Combination with other flags: Cannot be combined with GPS_TEMPORARY, /// GPS_READWRITE, or GPS_HANDLERPROPERTIESONLY. /// </summary> GPS_BESTEFFORT = 0x40, /// <summary> /// Mask for valid GETPROPERTYSTOREFLAGS values. /// </summary> GPS_MASK_VALID = 0xff, } [Flags] public enum SFGAO : uint { /// <summary> /// The specified items can be copied. /// </summary> SFGAO_CANCOPY = 0x00000001, /// <summary> /// The specified items can be moved. /// </summary> SFGAO_CANMOVE = 0x00000002, /// <summary> /// Shortcuts can be created for the specified items. This flag has the same value as DROPEFFECT. /// The normal use of this flag is to add a Create Shortcut item to the shortcut menu that is displayed /// during drag-and-drop operations. However, SFGAO_CANLINK also adds a Create Shortcut item to the Microsoft /// Windows Explorer's File menu and to normal shortcut menus. /// If this item is selected, your application's IContextMenu::InvokeCommand is invoked with the lpVerb /// member of the CMINVOKECOMMANDINFO structure set to "link." Your application is responsible for creating the link. /// </summary> SFGAO_CANLINK = 0x00000004, /// <summary> /// The specified items can be bound to an IStorage interface through IShellFolder::BindToObject. /// </summary> SFGAO_STORAGE = 0x00000008, /// <summary> /// The specified items can be renamed. /// </summary> SFGAO_CANRENAME = 0x00000010, /// <summary> /// The specified items can be deleted. /// </summary> SFGAO_CANDELETE = 0x00000020, /// <summary> /// The specified items have property sheets. /// </summary> SFGAO_HASPROPSHEET = 0x00000040, /// <summary> /// The specified items are drop targets. /// </summary> SFGAO_DROPTARGET = 0x00000100, /// <summary> /// This flag is a mask for the capability flags. /// </summary> SFGAO_CAPABILITYMASK = 0x00000177, /// <summary> /// Windows 7 and later. The specified items are system items. /// </summary> SFGAO_SYSTEM = 0x00001000, /// <summary> /// The specified items are encrypted. /// </summary> SFGAO_ENCRYPTED = 0x00002000, /// <summary> /// Indicates that accessing the object = through IStream or other storage interfaces, /// is a slow operation. /// Applications should avoid accessing items flagged with SFGAO_ISSLOW. /// </summary> SFGAO_ISSLOW = 0x00004000, /// <summary> /// The specified items are ghosted icons. /// </summary> SFGAO_GHOSTED = 0x00008000, /// <summary> /// The specified items are shortcuts. /// </summary> SFGAO_LINK = 0x00010000, /// <summary> /// The specified folder objects are shared. /// </summary> SFGAO_SHARE = 0x00020000, /// <summary> /// The specified items are read-only. In the case of folders, this means /// that new items cannot be created in those folders. /// </summary> SFGAO_READONLY = 0x00040000, /// <summary> /// The item is hidden and should not be displayed unless the /// Show hidden files and folders option is enabled in Folder Settings. /// </summary> SFGAO_HIDDEN = 0x00080000, /// <summary> /// This flag is a mask for the display attributes. /// </summary> SFGAO_DISPLAYATTRMASK = 0x000FC000, /// <summary> /// The specified folders contain one or more file system folders. /// </summary> SFGAO_FILESYSANCESTOR = 0x10000000, /// <summary> /// The specified items are folders. /// </summary> SFGAO_FOLDER = 0x20000000, /// <summary> /// The specified folders or file objects are part of the file system /// that is, they are files, directories, or root directories). /// </summary> SFGAO_FILESYSTEM = 0x40000000, /// <summary> /// The specified folders have subfolders = and are, therefore, /// expandable in the left pane of Windows Explorer). /// </summary> SFGAO_HASSUBFOLDER = 0x80000000, /// <summary> /// This flag is a mask for the contents attributes. /// </summary> SFGAO_CONTENTSMASK = 0x80000000, /// <summary> /// When specified as input, SFGAO_VALIDATE instructs the folder to validate that the items /// pointed to by the contents of apidl exist. If one or more of those items do not exist, /// IShellFolder::GetAttributesOf returns a failure code. /// When used with the file system folder, SFGAO_VALIDATE instructs the folder to discard cached /// properties retrieved by clients of IShellFolder2::GetDetailsEx that may /// have accumulated for the specified items. /// </summary> SFGAO_VALIDATE = 0x01000000, /// <summary> /// The specified items are on removable media or are themselves removable devices. /// </summary> SFGAO_REMOVABLE = 0x02000000, /// <summary> /// The specified items are compressed. /// </summary> SFGAO_COMPRESSED = 0x04000000, /// <summary> /// The specified items can be browsed in place. /// </summary> SFGAO_BROWSABLE = 0x08000000, /// <summary> /// The items are nonenumerated items. /// </summary> SFGAO_NONENUMERATED = 0x00100000, /// <summary> /// The objects contain new content. /// </summary> SFGAO_NEWCONTENT = 0x00200000, /// <summary> /// It is possible to create monikers for the specified file objects or folders. /// </summary> SFGAO_CANMONIKER = 0x00400000, /// <summary> /// Not supported. /// </summary> SFGAO_HASSTORAGE = 0x00400000, /// <summary> /// Indicates that the item has a stream associated with it that can be accessed /// by a call to IShellFolder::BindToObject with IID_IStream in the riid parameter. /// </summary> SFGAO_STREAM = 0x00400000, /// <summary> /// Children of this item are accessible through IStream or IStorage. /// Those children are flagged with SFGAO_STORAGE or SFGAO_STREAM. /// </summary> SFGAO_STORAGEANCESTOR = 0x00800000, /// <summary> /// This flag is a mask for the storage capability attributes. /// </summary> SFGAO_STORAGECAPMASK = 0x70C50008, /// <summary> /// Mask used by PKEY_SFGAOFlags to remove certain values that are considered /// to cause slow calculations or lack context. /// Equal to SFGAO_VALIDATE | SFGAO_ISSLOW | SFGAO_HASSUBFOLDER. /// </summary> SFGAO_PKEYSFGAOMASK = 0x81044000, } public enum KNOWNDESTCATEGORY { KDC_FREQUENT = 1, KDC_RECENT } public enum SIGDN : uint { SIGDN_NORMALDISPLAY = 0x00000000, // SHGDN_NORMAL SIGDN_PARENTRELATIVEPARSING = 0x80018001, // SHGDN_INFOLDER | SHGDN_FORPARSING SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000, // SHGDN_FORPARSING SIGDN_PARENTRELATIVEEDITING = 0x80031001, // SHGDN_INFOLDER | SHGDN_FOREDITING SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000, // SHGDN_FORPARSING | SHGDN_FORADDRESSBAR SIGDN_FILESYSPATH = 0x80058000, // SHGDN_FORPARSING SIGDN_URL = 0x80068000, // SHGDN_FORPARSING SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001, // SHGDN_INFOLDER | SHGDN_FORPARSING | SHGDN_FORADDRESSBAR SIGDN_PARENTRELATIVE = 0x80080001 // SHGDN_INFOLDER } public enum SICHINTF : uint { SICHINT_DISPLAY = 0x00000000, SICHINT_CANONICAL = 0x10000000, SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000, SICHINT_ALLFIELDS = 0x80000000 } // IID GUID strings for relevant Shell COM interfaces. public const string IShellItem = "43826D1E-E718-42EE-BC55-A1E261C37BFE"; public const string IShellItem2 = "7E9FB0D3-919F-4307-AB2E-9B1860310C93"; internal const string IShellFolder = "000214E6-0000-0000-C000-000000000046"; internal const string IShellFolder2 = "93F2F68C-1D1B-11D3-A30E-00C04F79ABD1"; internal const string IShellLinkW = "000214F9-0000-0000-C000-000000000046"; internal const string CShellLink = "00021401-0000-0000-C000-000000000046"; public const string IPropertyStore = "886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"; public static Guid IObjectArray = new Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9"); [DllImport(ExternDll.Shell32, EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public extern static int ExtractIconExW(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons); } #if !INTEROP internal struct SHARD #else public struct SHARD #endif { public const uint PIDL = 0x00000001; public const uint PATHA = 0x00000002; public const uint PATHW = 0x00000003; } #if !INTEROP internal struct CSIDL #else public struct CSIDL #endif { public const int SENDTO = 0x0009; } #if !INTEROP internal struct FILEDESCRIPTOR_HEADER #else public struct FILEDESCRIPTOR_HEADER #endif { public int dwFlags; public Guid clsid; public SIZEL sizel; public POINTL pointl; public int dwFileAttributes; public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; public int nFileSizeHigh; public int nFileSizeLow; } #if !INTEROP internal struct SHGFI #else public struct SHGFI #endif { public const uint ICON = 0x100; public const uint LARGEICON = 0x0; // 'Large icon public const uint SMALLICON = 0x1; // 'Small icon public const uint USEFILEATTRIBUTES = 0x000000010; public const uint ADDOVERLAYS = 0x000000020; public const uint LINKOVERLAY = 0x000008000; // Show shortcut overlay } #if !INTEROP [StructLayout(LayoutKind.Sequential)] internal struct SHFILEINFO #else [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO #endif { public IntPtr hIcon; public IntPtr iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; #if !INTEROP internal struct DROPFILES #else public struct DROPFILES #endif { public uint pFiles; public POINT pt; [MarshalAs(UnmanagedType.Bool)] public bool fNC; [MarshalAs(UnmanagedType.Bool)] public bool fWide; }; // ShellExecute and FindExecutable error codes #if !INTEROP internal struct SE_ERR #else public struct SE_ERR #endif { public const int FNF = 2; // file not found public const int NOASSOC = 31; // no association available public const int OOM = 8; // out of memory } /// <summary> /// Flags controlling the appearance of a window /// </summary> #if !INTEROP internal enum WindowShowCommand : uint #else public enum WindowShowCommand : uint #endif { /// <summary> /// Hides the window and activates another window. /// </summary> Hide = 0, /// <summary> /// Activates and displays the window (including restoring /// it to its original size and position). /// </summary> Normal = 1, /// <summary> /// Minimizes the window. /// </summary> Minimized = 2, /// <summary> /// Maximizes the window. /// </summary> Maximized = 3, /// <summary> /// Similar to <see cref="Normal"/>, except that the window /// is not activated. /// </summary> ShowNoActivate = 4, /// <summary> /// Activates the window and displays it in its current size /// and position. /// </summary> Show = 5, /// <summary> /// Minimizes the window and activates the next top-level window. /// </summary> Minimize = 6, /// <summary> /// Minimizes the window and does not activate it. /// </summary> ShowMinimizedNoActivate = 7, /// <summary> /// Similar to <see cref="Normal"/>, except that the window is not /// activated. /// </summary> ShowNA = 8, /// <summary> /// Activates and displays the window, restoring it to its original /// size and position. /// </summary> Restore = 9, /// <summary> /// Sets the show state based on the initial value specified when /// the process was created. /// </summary> Default = 10, /// <summary> /// Minimizes a window, even if the thread owning the window is not /// responding. Use this only to minimize windows from a different /// thread. /// </summary> ForceMinimize = 11 } #if !INTEROP [ComImport, Guid(Shell32.IShellItem2), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellItem2 : IShellItem #else [ComImport, Guid(Shell32.IShellItem2), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IShellItem2 : IShellItem #endif { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void Compare( [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] int GetPropertyStore( [In] Shell32.GETPROPERTYSTOREFLAGS Flags, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IPropertyStore ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyStoreWithCreateObject([In] Shell32.GETPROPERTYSTOREFLAGS Flags, [In, MarshalAs(UnmanagedType.IUnknown)] object punkCreateObject, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyStoreForKeys([In] ref PropertyKey rgKeys, [In] uint cKeys, [In] Shell32.GETPROPERTYSTOREFLAGS Flags, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.IUnknown)] out IPropertyStore ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetPropertyDescriptionList([In] ref PropertyKey keyType, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void Update([In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetProperty([In] ref PropertyKey key, out PropVariant ppropvar); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCLSID([In] ref PropertyKey key, out Guid pclsid); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetFileTime([In] ref PropertyKey key, out System.Runtime.InteropServices.ComTypes.FILETIME pft); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetInt32([In] ref PropertyKey key, out int pi); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetString([In] ref PropertyKey key, [MarshalAs(UnmanagedType.LPWStr)] out string ppsz); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUInt32([In] ref PropertyKey key, out uint pui); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUInt64([In] ref PropertyKey key, out ulong pull); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetBool([In] ref PropertyKey key, out int pf); } #if !INTEROP [ComImport, Guid(Shell32.IShellItem), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IShellItem #else [ComImport, Guid(Shell32.IShellItem), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IShellItem #endif { // Not supported: IBindCtx. [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int BindToHandler( [In] IntPtr pbc, [In] ref Guid bhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetDisplayName( [In] Shell32.SIGDN sigdnName, out IntPtr ppszName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributes([In] Shell32.SFGAO sfgaoMask, out Shell32.SFGAO psfgaoAttribs); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int Compare( [In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] Shell32.SICHINTF hint, out int piOrder); } #if !INTEROP [ComImport, Guid(Shell32.IPropertyStore), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IPropertyStore #else [ComImport, Guid(Shell32.IPropertyStore), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPropertyStore #endif { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetCount([Out] out uint cProps); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAt([In] uint iProp, out PropertyKey pkey); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetValue([In] ref PropertyKey key, out PropVariant pv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), PreserveSig] [return: MarshalAs(UnmanagedType.I4)] int SetValue([In] ref PropertyKey key, [In] ref PropVariant pv); [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int Commit(); } /// <summary> /// Defines a unique key for a Shell Property /// </summary> #if !INTEROP [StructLayout(LayoutKind.Sequential, Pack = 4)] internal struct PropertyKey : IEquatable<PropertyKey> #else [StructLayout(LayoutKind.Sequential, Pack = 4)] public struct PropertyKey : IEquatable<PropertyKey> #endif { #region Private Fields private Guid formatId; private Int32 propertyId; #endregion Private Fields #region Public Properties /// <summary> /// A unique GUID for the property /// </summary> public Guid FormatId { get { return formatId; } } /// <summary> /// Property identifier (PID) /// </summary> public Int32 PropertyId { get { return propertyId; } } #endregion Public Properties #region Public Construction /// <summary> /// PropertyKey Constructor /// </summary> /// <param name="formatId">A unique GUID for the property</param> /// <param name="propertyId">Property identifier (PID)</param> public PropertyKey(Guid formatId, Int32 propertyId) { this.formatId = formatId; this.propertyId = propertyId; } /// <summary> /// PropertyKey Constructor /// </summary> /// <param name="formatId">A string represenstion of a GUID for the property</param> /// <param name="propertyId">Property identifier (PID)</param> public PropertyKey(string formatId, Int32 propertyId) { this.formatId = new Guid(formatId); this.propertyId = propertyId; } // Convenience ctor to initialize Windows Ribbon framework property key. public PropertyKey(Int32 index, VarEnum id) { this.formatId = new Guid(index, 0x7363, 0x696e, new byte[] { 0x84, 0x41, 0x79, 0x8a, 0xcf, 0x5a, 0xeb, 0xb7 }); this.propertyId = Convert.ToInt32(id); } #endregion Public Construction #region IEquatable<PropertyKey> Members /// <summary> /// Returns whether this object is equal to another. This is vital for performance of value types. /// </summary> /// <param name="other">The object to compare against.</param> /// <returns>Equality result.</returns> public bool Equals(PropertyKey other) { return other.Equals((object)this); } #endregion IEquatable<PropertyKey> Members #region equality and hashing /// <summary> /// Returns the hash code of the object. This is vital for performance of value types. /// </summary> /// <returns></returns> public override int GetHashCode() { return formatId.GetHashCode() ^ propertyId; } /// <summary> /// Returns whether this object is equal to another. This is vital for performance of value types. /// </summary> /// <param name="obj">The object to compare against.</param> /// <returns>Equality result.</returns> public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is PropertyKey)) return false; PropertyKey other = (PropertyKey)obj; return other.formatId.Equals(formatId) && (other.propertyId == propertyId); } /// <summary> /// Implements the == (equality) operator. /// </summary> /// <param name="a">Object a.</param> /// <param name="b">Object b.</param> /// <returns>true if object a equals object b. false otherwise.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")] public static bool operator ==(PropertyKey a, PropertyKey b) { return a.Equals(b); } /// <summary> /// Implements the != (inequality) operator. /// </summary> /// <param name="a">Object a.</param> /// <param name="b">Object b.</param> /// <returns>true if object a does not equal object b. false otherwise.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")] public static bool operator !=(PropertyKey a, PropertyKey b) { return !a.Equals(b); } /// <summary> /// Override ToString() to provide a user friendly string representation /// </summary> /// <returns>String representing the property key</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")] public override string ToString() { return String.Format("{0}, {1}", formatId.ToString("B"), propertyId); } #endregion equality and hashing private static System.Collections.Generic.Dictionary<PropertyKey, GCHandle> s_pinnedCache = new System.Collections.Generic.Dictionary<PropertyKey, GCHandle>(16); public IntPtr ToPointer() { if (!s_pinnedCache.ContainsKey(this)) { s_pinnedCache.Add(this, GCHandle.Alloc(this, GCHandleType.Pinned)); } return s_pinnedCache[this].AddrOfPinnedObject(); } } #if !INTEROP [StructLayout(LayoutKind.Sequential)] internal class PropertyKeyRef #else [StructLayout(LayoutKind.Sequential)] public class PropertyKeyRef #endif { public PropertyKey PropertyKey; public static PropertyKeyRef From(PropertyKey value) { PropertyKeyRef obj = new PropertyKeyRef(); obj.PropertyKey = value; return obj; } } #if !INTEROP [ComImport, Guid(Shell32.IShellFolder), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComConversionLoss] internal interface IShellFolder #else [ComImport, Guid(Shell32.IShellFolder), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComConversionLoss] public interface IShellFolder #endif { [PreserveSig] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int BindToObject([In] IntPtr pidl, /*[In, MarshalAs(UnmanagedType.Interface)] IBindCtx*/ IntPtr pbc, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IShellFolder ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindToStorage([In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.Interface)] IBindCtx pbc, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CompareIDs([In] IntPtr lParam, [In] ref IntPtr pidl1, [In] ref IntPtr pidl2); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void CreateViewObject([In] IntPtr hwndOwner, [In] ref Guid riid, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetAttributesOf([In] uint cidl, [In] IntPtr apidl, [In, Out] ref uint rgfInOut); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetUIObjectOf([In] IntPtr hwndOwner, [In] uint cidl, [In] IntPtr apidl, [In] ref Guid riid, [In, Out] ref uint rgfReserved, out IntPtr ppv); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void GetDisplayNameOf([In] ref IntPtr pidl, [In] uint uFlags, out IntPtr pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void SetNameOf([In] IntPtr hwnd, [In] ref IntPtr pidl, [In, MarshalAs(UnmanagedType.LPWStr)] string pszName, [In] uint uFlags, [Out] IntPtr ppidlOut); } #pragma warning restore }
using System; using System.Configuration; using System.Data.Entity; using System.Data.Entity.Migrations; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Cors; using System.Web.Http.ExceptionHandling; using Autofac; using Autofac.Integration.SignalR; using Autofac.Integration.WebApi; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using Microsoft.Owin.Cors; using Microsoft.Owin.FileSystems; using Microsoft.Owin.Security.DataHandler; using Microsoft.Owin.Security.Jwt; using Microsoft.Owin.Security.OAuth; using Microsoft.Owin.StaticFiles; using Newtonsoft.Json.Serialization; using Owin; using Owin.Security.AesDataProtectorProvider; using Serilog; using Thinktecture.Relay.Server.Config; using Thinktecture.Relay.Server.Controller; using Thinktecture.Relay.Server.Controller.ManagementWeb; using Thinktecture.Relay.Server.Filters; using Thinktecture.Relay.Server.Logging; using Thinktecture.Relay.Server.Owin; using Thinktecture.Relay.Server.Repository; using Thinktecture.Relay.Server.Security; using Thinktecture.Relay.Server.SignalR; using ExceptionLogger = Thinktecture.Relay.Server.Logging.ExceptionLogger; namespace Thinktecture.Relay.Server { internal class Startup : IStartup { private readonly ILogger _logger; private readonly IConfiguration _configuration; private readonly ILifetimeScope _rootScope; private readonly IOAuthAuthorizationServerProvider _authorizationServerProvider; public Startup(ILogger logger, IConfiguration configuration, ILifetimeScope rootScope, IOAuthAuthorizationServerProvider authorizationServerProvider) { _logger = logger; _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); _rootScope = rootScope ?? throw new ArgumentNullException(nameof(rootScope)); _authorizationServerProvider = authorizationServerProvider ?? throw new ArgumentNullException(nameof(authorizationServerProvider)); } public void Configuration(IAppBuilder app) { InitializeAndMigrateDatabase(); var httpConfig = CreateHttpConfiguration(); var innerScope = RegisterAdditionalServices(_rootScope, httpConfig, _configuration); app.UseAutofacMiddleware(innerScope); app.UseHsts(_configuration.HstsHeaderMaxAge, _configuration.HstsIncludeSubdomains); app.UseCors(CorsOptions.AllowAll); UseOAuthSecurity(app); MapSignalR(app, innerScope); UseWebApi(app, httpConfig, innerScope); UseFileServer(app); } private static void InitializeAndMigrateDatabase() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<RelayContext, Migrations.Configuration>()); var migrator = new DbMigrator(new Migrations.Configuration { AutomaticMigrationsEnabled = true, AutomaticMigrationDataLossAllowed = false }); if (migrator.GetPendingMigrations().Any()) { migrator.Update(); } } private ILifetimeScope RegisterAdditionalServices(ILifetimeScope container, HttpConfiguration httpConfig, IConfiguration config) { return container.BeginLifetimeScope(builder => { // This enables property injection into ASP.NET MVC filter attributes builder.RegisterWebApiFilterProvider(httpConfig); RegisterApiControllers(builder); }); } private void RegisterApiControllers(ContainerBuilder builder) { if (_configuration.EnableManagementWeb != ModuleBinding.False) builder.RegisterModule<ManagementWebModule>(); if (_configuration.EnableRelaying != ModuleBinding.False) builder.RegisterModule<RelayingModule>(); if (_configuration.EnableOnPremiseConnections != ModuleBinding.False) builder.RegisterModule<OnPremiseConnectionsModule>(); } private void UseOAuthSecurity(IAppBuilder app) { // Todo: Add this only when relaying is enabled (no need to auth OnPremises if not), and add // a second endpoint with different token lifetime for management web user (i.e. `/managementToken`), // when management web is enabled. Also, use different AuthProviders for each endpoint var serverOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = _configuration.UseInsecureHttp, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = _configuration.AccessTokenLifetime, Provider = _authorizationServerProvider, }; var certBase64 = _configuration.OAuthCertificate; if (!String.IsNullOrWhiteSpace(certBase64)) { var cert = new X509Certificate2(Convert.FromBase64String(certBase64)); serverOptions.AccessTokenFormat = new TicketDataFormat(new RsaDataProtector(cert)); var authOptions = new OAuthBearerAuthenticationOptions { AccessTokenFormat = new TicketDataFormat(new RsaDataProtector(cert)), Provider = new OAuthBearerAuthenticationProvider() { OnApplyChallenge = context => { // Workaround: Keep an already set WWW-Authenticate header (otherwise OWIN would add its challenge). if (!context.Response.Headers.ContainsKey("WWW-Authenticate")) { context.OwinContext.Response.Headers.AppendValues("WWW-Authenticate", context.Challenge); } return Task.CompletedTask; } } }; app.UseOAuthBearerAuthentication(authOptions); } else { var sharedSecret = _configuration.SharedSecret; if (!String.IsNullOrWhiteSpace(sharedSecret)) { const string issuer = "http://thinktecture.com/relayserver/sts"; const string audience = "http://thinktecture.com/relayserver/consumers"; var key = Convert.FromBase64String(sharedSecret); serverOptions.AccessTokenFormat = new CustomJwtFormat(serverOptions.AccessTokenExpireTimeSpan, key, issuer, audience); app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions() { AllowedAudiences = new[] { audience }, IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, key) }, }); } } app.UseOAuthAuthorizationServer(serverOptions); } private void MapSignalR(IAppBuilder app, ILifetimeScope scope) { if (_configuration.EnableOnPremiseConnections == ModuleBinding.False) return; const string path = "/signalr"; GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(_configuration.ConnectionTimeout); GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(_configuration.DisconnectTimeout); GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(_configuration.KeepAliveInterval); var sharedSecret = _configuration.SharedSecret; if (!String.IsNullOrWhiteSpace(sharedSecret)) { app.UseAesDataProtectorProvider(sharedSecret); } if (_configuration.EnableOnPremiseConnections == ModuleBinding.Local) { app.Use(typeof(BlockNonLocalRequestsMiddleware), path); } app.MapSignalR<OnPremisesConnection>(path, new ConnectionConfiguration { Resolver = new AutofacDependencyResolver(scope), }); } private static void UseWebApi(IAppBuilder app, HttpConfiguration httpConfig, ILifetimeScope scope) { httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(scope); app.UseWebApi(httpConfig); } private HttpConfiguration CreateHttpConfiguration() { var httpConfig = new HttpConfiguration { IncludeErrorDetailPolicy = _configuration.IncludeErrorDetailPolicy, }; httpConfig.EnableCors(new EnableCorsAttribute("*", "*", "*")); httpConfig.SuppressDefaultHostAuthentication(); if (StringComparer.OrdinalIgnoreCase.Equals(ConfigurationManager.AppSettings["EnableTraceWriter"], "true")) httpConfig.Services.Replace(typeof(System.Web.Http.Tracing.ITraceWriter), new TraceWriter(_logger?.ForContext<TraceWriter>(), new TraceLevelConverter())); httpConfig.Services.Add(typeof(IExceptionLogger), new ExceptionLogger(_logger?.ForContext<ExceptionLogger>())); if (StringComparer.OrdinalIgnoreCase.Equals(ConfigurationManager.AppSettings["EnableActionFilter"], "true")) httpConfig.Filters.Add(new LogActionFilter(_logger?.ForContext<LogActionFilter>())); httpConfig.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // custom code api controllers should use the RouteAttribute only httpConfig.MapHttpAttributeRoutes(); if (_configuration.EnableRelaying != ModuleBinding.False) { _logger?.Information("Relaying enabled"); httpConfig.Routes.MapHttpRoute("ClientRequest", "relay/{*fullPathToOnPremiseEndpoint}", new { controller = "Client", action = "Relay" }); } if (_configuration.EnableOnPremiseConnections != ModuleBinding.False) { _logger?.Information("On-premise connections enabled"); httpConfig.Routes.MapHttpRoute("OnPremiseTargetResponse", "forward", new { controller = "Response", action = "Forward" }); httpConfig.Routes.MapHttpRoute("OnPremiseTargetRequestAcknowledgement", "request/acknowledge", new { controller = "Request", action = "Acknowledge" }); httpConfig.Routes.MapHttpRoute("OnPremiseTargetRequest", "request/{requestId}", new { controller = "Request", action = "Get" }); } if (_configuration.EnableManagementWeb != ModuleBinding.False) { _logger?.Information("Management web enabled"); httpConfig.Routes.MapHttpRoute("ManagementWeb", "api/managementweb/{controller}/{action}"); } httpConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); return httpConfig; } private void UseFileServer(IAppBuilder app) { if (_configuration.EnableManagementWeb == ModuleBinding.False) return; try { const string path = "/managementweb"; var options = new FileServerOptions() { FileSystem = new PhysicalFileSystem(_configuration.ManagementWebLocation), RequestPath = new PathString(path), }; options.DefaultFilesOptions.DefaultFileNames.Add("index.html"); if (_configuration.EnableManagementWeb == ModuleBinding.Local) { app.Use(typeof(BlockNonLocalRequestsMiddleware), path); } options.StaticFileOptions.OnPrepareResponse = ctx => { ctx.OwinContext.Response.Headers.Append("X-Frame-Options", "DENY"); ctx.OwinContext.Response.Headers.Append("X-XSS-Protection", "1; mode=block"); }; app.UseFileServer(options); } catch (DirectoryNotFoundException) { // no admin web deployed - catch silently, but display info for the user _logger?.Information("The configured directory for the ManagementWeb was not found. ManagementWeb will be disabled."); } } } }
using System; using System.Collections.Generic; using Boo.Lang.Compiler.TypeSystem; namespace BooCompiler.Tests.TypeSystem.Reflection { internal class BeanPropertyFinder { readonly Dictionary<string, BeanProperty> _properties = new Dictionary<string, BeanProperty>(); public BeanPropertyFinder(IEntity[] members) { foreach (IEntity entity in members) if (entity.EntityType == EntityType.Method) if (IsGetter(entity)) ProcessBeanAccessor((IMethod)entity); else if (IsSetter(entity)) ProcessBeanMutator((IMethod) entity); } private bool IsSetter(IEntity entity) { return HasCamelCasePrefix(entity, "set"); } private bool IsGetter(IEntity entity) { return HasCamelCasePrefix(entity, "get"); } private static bool HasCamelCasePrefix(IEntity entity, string prefix) { string name = entity.Name; if (name.Length <= prefix.Length + 1) return false; return name.StartsWith(prefix) && char.IsUpper(name[prefix.Length]); } private void ProcessBeanAccessor(IMethod method) { BeanPropertyFor(method).Getter = method; } private void ProcessBeanMutator(IMethod method) { BeanPropertyFor(method).Setter = method; } private BeanProperty BeanPropertyFor(IMethod method) { string propertyName = method.Name.Substring(3); BeanProperty beanProperty; if (!_properties.TryGetValue(propertyName, out beanProperty)) { beanProperty = new BeanProperty(propertyName); _properties.Add(propertyName, beanProperty); } return beanProperty; } public IEntity[] FindAll() { BeanProperty[] result = new BeanProperty[_properties.Count]; _properties.Values.CopyTo(result, 0); return result; } } internal class BeanProperty : IProperty { private IMethod _getter; private IMethod _setter; private string _name; public BeanProperty(string name) { _name = char.ToLower(name[0]) + name.Substring(1); } public IMethod Getter { set { if (_getter != null) throw new InvalidOperationException(); _getter = value; } } public IMethod Setter { set { if (_setter != null) throw new InvalidOperationException(); _setter = value; } } #region Implementation of IEntity public string Name { get { return _name; } } public string FullName { get { throw new System.NotImplementedException(); } } public EntityType EntityType { get { throw new System.NotImplementedException(); } } #endregion #region Implementation of ITypedEntity public IType Type { get { throw new System.NotImplementedException(); } } #endregion #region Implementation of IEntityWithAttributes public bool IsDefined(IType attributeType) { throw new System.NotImplementedException(); } #endregion #region Implementation of IMember public bool IsDuckTyped { get { throw new System.NotImplementedException(); } } public IType DeclaringType { get { throw new System.NotImplementedException(); } } public bool IsStatic { get { throw new System.NotImplementedException(); } } public bool IsPublic { get { throw new System.NotImplementedException(); } } #endregion #region Implementation of IAccessibleMember public bool IsProtected { get { throw new System.NotImplementedException(); } } public bool IsInternal { get { throw new System.NotImplementedException(); } } public bool IsPrivate { get { throw new System.NotImplementedException(); } } #endregion #region Implementation of IEntityWithParameters public IParameter[] GetParameters() { throw new System.NotImplementedException(); } public bool AcceptVarArgs { get { throw new System.NotImplementedException(); } } #endregion #region Implementation of IExtensionEnabled public bool IsExtension { get { throw new System.NotImplementedException(); } } #endregion #region Implementation of IProperty public IMethod GetGetMethod() { return _getter; } public IMethod GetSetMethod() { return _setter; } #endregion } }
// // - LazyDescriptionCollection.cs - // // Copyright 2012 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Carbonfrost.Commons.Shared.Runtime { class LazyDescriptionCollection<TValue> : ICollection<TValue>, IAssemblyInfoFilter, IEnumerable<TValue>, IObservable<TValue> { private readonly List<ObserverDisposer> observers = new List<ObserverDisposer>(); private readonly ICollection<TValue> inner; private readonly Func<Assembly, IEnumerable<TValue>> selector; private readonly object root = new object(); protected ICollection<TValue> Inner { get { return inner; } } public LazyDescriptionCollection(Func<Assembly, IEnumerable<TValue>> func) : this(func, new List<TValue>()) {} public LazyDescriptionCollection( Func<Assembly, IEnumerable<TValue>> selector, ICollection<TValue> inner) { if (selector == null) throw new ArgumentNullException("selector"); this.selector = selector; this.inner = inner; AssemblyInfo.AddStaticFilter(this); } public bool IsReadOnly { get { return false; } } public int Count { get { Complete(); return Inner.Count; } } public void Add(TValue item) { AddValue(item); } public virtual bool Contains(TValue item) { return Continue(item); } public void CopyTo(TValue[] array, int arrayIndex) { Inner.CopyTo(array, arrayIndex); } public bool Remove(TValue item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } protected void Complete() { AssemblyInfo.CompleteAppDomain(); } protected bool Continue(TValue value) { do { if (this.Inner.Contains(value)) return true; } while (AssemblyInfo.ContinueAppDomain()); return false; } // `IObservable<TValue>' implementation public IDisposable Subscribe(IObserver<TValue> observer) { if (observer == null) throw new ArgumentNullException("observer"); var result = new DefaultObserverDisposer(this, observer); this.observers.Add(result); return result; } // IAssemblyInfoFilter implementation public void ApplyToAssembly(AssemblyInfo info) { var items = this.selector(info.Assembly); if (items == null) return; foreach (var item in items) { AddValue(item); } } protected virtual void AddValue(TValue value) { lock (root) { this.Inner.Add(value); } int count = 0; foreach (var o in this.observers) { if (!o.Disposed) { o.OnNext(value); count++; } } if (count != this.observers.Count) { this.observers.RemoveAll(t => t.Disposed); } } public IEnumerator<TValue> GetEnumerator() { if (AssemblyInfo.AppDomainInSync()) return Inner.GetEnumerator(); var result = new Enumerator(this); this.observers.Add(result); return result; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } abstract class ObserverDisposer : IDisposable, IObserver<TValue> { protected LazyDescriptionCollection<TValue> owner; public bool Disposed { get; private set; } protected ObserverDisposer(LazyDescriptionCollection<TValue> owner) { this.owner = owner; } public void Dispose() { this.Disposed = true; } public abstract void OnNext(TValue item); public void OnError(Exception error) {} public void OnCompleted() {} } class DefaultObserverDisposer : ObserverDisposer { private readonly IObserver<TValue> observer; public DefaultObserverDisposer(LazyDescriptionCollection<TValue> owner, IObserver<TValue> observer) : base(owner) { this.observer = observer; } public override void OnNext(TValue item) { observer.OnNext(item); } } class Enumerator : ObserverDisposer, IEnumerator<TValue> { private readonly ConcurrentQueue<TValue> existingValues; public Enumerator(LazyDescriptionCollection<TValue> owner) : base(owner) { this.existingValues = new ConcurrentQueue<TValue>(); this.Reset(); } public TValue Current { get { if (this.existingValues.Count == 0) throw Failure.OutsideEnumeration(); TValue result; existingValues.TryPeek(out result); return result; } } object System.Collections.IEnumerator.Current { get { return this.Current; } } public bool MoveNext() { while (existingValues.Count == 0 && AssemblyInfo.ContinueAppDomain()) { } if (existingValues.Count > 0) { TValue result; existingValues.TryDequeue(out result); } return (existingValues.Count > 0); } public void Reset() { foreach (var value in owner.Inner) this.existingValues.Enqueue(value); } public override void OnNext(TValue value) { this.existingValues.Enqueue(value); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Input; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Edit.Blueprints.HitCircles.Components; using osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders.Components; using osuTK; using osuTK.Input; namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Sliders { public class SliderPlacementBlueprint : PlacementBlueprint { public new Objects.Slider HitObject => (Objects.Slider)base.HitObject; private SliderBodyPiece bodyPiece; private HitCirclePiece headCirclePiece; private HitCirclePiece tailCirclePiece; private PathControlPointVisualiser controlPointVisualiser; private InputManager inputManager; private PlacementState state; private PathControlPoint segmentStart; private PathControlPoint cursor; private int currentSegmentLength; [Resolved(CanBeNull = true)] private HitObjectComposer composer { get; set; } public SliderPlacementBlueprint() : base(new Objects.Slider()) { RelativeSizeAxes = Axes.Both; HitObject.Path.ControlPoints.Add(segmentStart = new PathControlPoint(Vector2.Zero, PathType.Linear)); currentSegmentLength = 1; } [BackgroundDependencyLoader] private void load(OsuColour colours) { InternalChildren = new Drawable[] { bodyPiece = new SliderBodyPiece(), headCirclePiece = new HitCirclePiece(), tailCirclePiece = new HitCirclePiece(), controlPointVisualiser = new PathControlPointVisualiser(HitObject, false) }; setState(PlacementState.Initial); } protected override void LoadComplete() { base.LoadComplete(); inputManager = GetContainingInputManager(); } public override void UpdatePosition(Vector2 screenSpacePosition) { switch (state) { case PlacementState.Initial: BeginPlacement(); HitObject.Position = ToLocalSpace(screenSpacePosition); break; case PlacementState.Body: updateCursor(); break; } } protected override bool OnClick(ClickEvent e) { switch (state) { case PlacementState.Initial: beginCurve(); break; case PlacementState.Body: if (e.Button != MouseButton.Left) break; if (canPlaceNewControlPoint(out var lastPoint)) { // Place a new point by detatching the current cursor. updateCursor(); cursor = null; } else { // Transform the last point into a new segment. Debug.Assert(lastPoint != null); segmentStart = lastPoint; segmentStart.Type.Value = PathType.Linear; currentSegmentLength = 1; } return true; } return true; } protected override void OnMouseUp(MouseUpEvent e) { if (state == PlacementState.Body && e.Button == MouseButton.Right) endCurve(); base.OnMouseUp(e); } private void beginCurve() { BeginPlacement(commitStart: true); setState(PlacementState.Body); } private void endCurve() { updateSlider(); EndPlacement(true); } protected override void Update() { base.Update(); updateSlider(); } private void updatePathType() { switch (currentSegmentLength) { case 1: case 2: segmentStart.Type.Value = PathType.Linear; break; case 3: segmentStart.Type.Value = PathType.PerfectCurve; break; default: segmentStart.Type.Value = PathType.Bezier; break; } } private void updateCursor() { if (canPlaceNewControlPoint(out _)) { // The cursor does not overlap a previous control point, so it can be added if not already existing. if (cursor == null) { HitObject.Path.ControlPoints.Add(cursor = new PathControlPoint { Position = { Value = Vector2.Zero } }); // The path type should be adjusted in the progression of updatePathType() (Linear -> PC -> Bezier). currentSegmentLength++; updatePathType(); } // Update the cursor position. cursor.Position.Value = ToLocalSpace(inputManager.CurrentState.Mouse.Position) - HitObject.Position; } else if (cursor != null) { // The cursor overlaps a previous control point, so it's removed. HitObject.Path.ControlPoints.Remove(cursor); cursor = null; // The path type should be adjusted in the reverse progression of updatePathType() (Bezier -> PC -> Linear). currentSegmentLength--; updatePathType(); } } /// <summary> /// Whether a new control point can be placed at the current mouse position. /// </summary> /// <param name="lastPoint">The last-placed control point. May be null, but is not null if <c>false</c> is returned.</param> /// <returns>Whether a new control point can be placed at the current position.</returns> private bool canPlaceNewControlPoint([CanBeNull] out PathControlPoint lastPoint) { // We cannot rely on the ordering of drawable pieces, so find the respective drawable piece by searching for the last non-cursor control point. var last = HitObject.Path.ControlPoints.LastOrDefault(p => p != cursor); var lastPiece = controlPointVisualiser.Pieces.Single(p => p.ControlPoint == last); lastPoint = last; return lastPiece?.IsHovered != true; } private void updateSlider() { HitObject.Path.ExpectedDistance.Value = composer?.GetSnappedDistanceFromDistance(HitObject.StartTime, (float)HitObject.Path.CalculatedDistance) ?? (float)HitObject.Path.CalculatedDistance; bodyPiece.UpdateFrom(HitObject); headCirclePiece.UpdateFrom(HitObject.HeadCircle); tailCirclePiece.UpdateFrom(HitObject.TailCircle); } private void setState(PlacementState newState) { state = newState; } private enum PlacementState { Initial, Body, } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using CSharpGuidelinesAnalyzer.Extensions; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace CSharpGuidelinesAnalyzer.Rules.Maintainability { [DiagnosticAnalyzer(LanguageNames.CSharp)] public sealed class NamespaceShouldMatchAssemblyNameAnalyzer : DiagnosticAnalyzer { // Copied from Microsoft.CodeAnalysis.WellKnownMemberNames, which provides these in later versions. private const string TopLevelStatementsEntryPointTypeName = "Program"; private const string TopLevelStatementsEntryPointMethodName = "<Main>$"; private const string Title = "Namespace should match with assembly name"; private const string NamespaceMessageFormat = "Namespace '{0}' does not match with assembly name '{1}'"; private const string TypeInNamespaceMessageFormat = "Type '{0}' is declared in namespace '{1}', which does not match with assembly name '{2}'"; private const string GlobalTypeMessageFormat = "Type '{0}' is declared in global namespace, which does not match with assembly name '{1}'"; private const string Description = "Name assemblies after their contained namespace."; public const string DiagnosticId = "AV1505"; [NotNull] private static readonly AnalyzerCategory Category = AnalyzerCategory.Maintainability; [NotNull] private static readonly DiagnosticDescriptor NamespaceRule = new DiagnosticDescriptor(DiagnosticId, Title, NamespaceMessageFormat, Category.DisplayName, DiagnosticSeverity.Info, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [NotNull] private static readonly DiagnosticDescriptor TypeInNamespaceRule = new DiagnosticDescriptor(DiagnosticId, Title, TypeInNamespaceMessageFormat, Category.DisplayName, DiagnosticSeverity.Info, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [NotNull] private static readonly DiagnosticDescriptor GlobalTypeRule = new DiagnosticDescriptor(DiagnosticId, Title, GlobalTypeMessageFormat, Category.DisplayName, DiagnosticSeverity.Info, true, Description, Category.GetHelpLinkUri(DiagnosticId)); [NotNull] private static readonly Action<SymbolAnalysisContext> AnalyzeNamespaceAction = context => context.SkipEmptyName(AnalyzeNamespace); [NotNull] private static readonly Action<SymbolAnalysisContext> AnalyzeNamedTypeAction = context => context.SkipEmptyName(AnalyzeNamedType); [ItemNotNull] public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(NamespaceRule, TypeInNamespaceRule, GlobalTypeRule); public override void Initialize([NotNull] AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterSymbolAction(AnalyzeNamespaceAction, SymbolKind.Namespace); context.RegisterSymbolAction(AnalyzeNamedTypeAction, SymbolKind.NamedType); } private static void AnalyzeNamespace(SymbolAnalysisContext context) { var namespaceSymbol = (INamespaceSymbol)context.Symbol; if (IsTopLevelNamespace(namespaceSymbol)) { AnalyzeTopLevelNamespace(namespaceSymbol, context); } } private static bool IsTopLevelNamespace([NotNull] INamespaceSymbol namespaceSymbol) { return namespaceSymbol.ContainingNamespace.IsGlobalNamespace; } private static void AnalyzeTopLevelNamespace([NotNull] INamespaceSymbol namespaceSymbol, SymbolAnalysisContext context) { string reportAssemblyName = namespaceSymbol.ContainingAssembly.Name; string assemblyName = GetAssemblyNameWithoutCore(reportAssemblyName); context.CancellationToken.ThrowIfCancellationRequested(); var visitor = new TypesInNamespaceVisitor(assemblyName, reportAssemblyName, context); visitor.Visit(namespaceSymbol); } [NotNull] private static string GetAssemblyNameWithoutCore([NotNull] string assemblyName) { if (assemblyName == "Core") { return string.Empty; } return assemblyName.EndsWith(".Core", StringComparison.Ordinal) ? assemblyName.Substring(0, assemblyName.Length - ".Core".Length) : assemblyName; } private static void AnalyzeNamedType(SymbolAnalysisContext context) { var type = (INamedTypeSymbol)context.Symbol; if (type.ContainingNamespace.IsGlobalNamespace && !type.IsSynthesized() && !IsTopLevelStatementsContainer(type)) { context.ReportDiagnostic(Diagnostic.Create(GlobalTypeRule, type.Locations[0], type.Name, type.ContainingAssembly.Name)); } } private static bool IsTopLevelStatementsContainer([NotNull] INamedTypeSymbol type) { return type.Name == TopLevelStatementsEntryPointTypeName && type.GetMembers(TopLevelStatementsEntryPointMethodName).Any(); } private sealed class TypesInNamespaceVisitor : SymbolVisitor { [ItemNotNull] private static readonly ImmutableArray<string> JetBrainsAnnotationsNamespace = ImmutableArray.Create("JetBrains", "Annotations"); [NotNull] private static readonly char[] DotSeparator = { '.' }; [ItemNotNull] private readonly ImmutableArray<string> assemblyNameParts; [NotNull] private readonly string reportAssemblyName; [NotNull] [ItemNotNull] private readonly Stack<string> namespaceNames = new Stack<string>(); private SymbolAnalysisContext context; [NotNull] private string CurrentNamespaceName => string.Join(".", namespaceNames.Reverse()); public TypesInNamespaceVisitor([NotNull] string assemblyName, [NotNull] string reportAssemblyName, SymbolAnalysisContext context) { Guard.NotNull(assemblyName, nameof(assemblyName)); Guard.NotNullNorWhiteSpace(reportAssemblyName, nameof(reportAssemblyName)); assemblyNameParts = assemblyName.Split(DotSeparator, StringSplitOptions.RemoveEmptyEntries).ToImmutableArray(); this.reportAssemblyName = reportAssemblyName; this.context = context; } public override void VisitNamespace([NotNull] INamespaceSymbol symbol) { context.CancellationToken.ThrowIfCancellationRequested(); namespaceNames.Push(symbol.Name); if (!IsCurrentNamespaceAllowed(NamespaceMatchMode.RequirePartialMatchWithAssemblyName) && !symbol.IsSynthesized()) { context.ReportDiagnostic(Diagnostic.Create(NamespaceRule, symbol.Locations[0], CurrentNamespaceName, reportAssemblyName)); } VisitChildren(symbol); namespaceNames.Pop(); } private void VisitChildren([NotNull] INamespaceSymbol namespaceSymbol) { foreach (INamedTypeSymbol typeMember in namespaceSymbol.GetTypeMembers()) { VisitNamedType(typeMember); } foreach (INamespaceSymbol namespaceMember in namespaceSymbol.GetNamespaceMembers()) { VisitNamespace(namespaceMember); } } public override void VisitNamedType([NotNull] INamedTypeSymbol symbol) { if (!IsCurrentNamespaceAllowed(NamespaceMatchMode.RequireCompleteMatchWithAssemblyName) && !symbol.IsSynthesized()) { context.ReportDiagnostic(Diagnostic.Create(TypeInNamespaceRule, symbol.Locations[0], symbol.Name, CurrentNamespaceName, reportAssemblyName)); } } private bool IsCurrentNamespaceAllowed(NamespaceMatchMode matchMode) { string[] currentNamespaceParts = namespaceNames.Reverse().ToArray(); if (IsCurrentNamespacePartOfJetBrainsAnnotations(currentNamespaceParts)) { return true; } bool? isMatchOnParts = IsMatchOnNamespaceParts(currentNamespaceParts, matchMode); return isMatchOnParts == null || isMatchOnParts.Value; } private bool IsCurrentNamespacePartOfJetBrainsAnnotations([NotNull] [ItemNotNull] string[] currentNamespaceParts) { switch (currentNamespaceParts.Length) { case 1: { return currentNamespaceParts[0] == JetBrainsAnnotationsNamespace[0]; } case 2: { return currentNamespaceParts.SequenceEqual(JetBrainsAnnotationsNamespace); } } return false; } [CanBeNull] private bool? IsMatchOnNamespaceParts([NotNull] [ItemNotNull] string[] currentNamespaceParts, NamespaceMatchMode matchMode) { if (matchMode == NamespaceMatchMode.RequireCompleteMatchWithAssemblyName && assemblyNameParts.Length > currentNamespaceParts.Length) { return false; } int commonLength = Math.Min(currentNamespaceParts.Length, assemblyNameParts.Length); for (int index = 0; index < commonLength; index++) { if (currentNamespaceParts[index] != assemblyNameParts[index]) { return false; } } return null; } private enum NamespaceMatchMode { RequirePartialMatchWithAssemblyName, RequireCompleteMatchWithAssemblyName } } } }
// 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. #if ARM #define _TARGET_ARM_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define FEATURE_HFA #elif ARM64 #define _TARGET_ARM64_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #define FEATURE_HFA #elif X86 #define _TARGET_X86_ #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLINGCONVENTION_CALLEE_POPS #elif AMD64 #if UNIXAMD64 #define UNIX_AMD64_ABI #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #else #endif #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define _TARGET_AMD64_ #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #else #error Unknown architecture! #endif using System; using System.Collections.Generic; using System.Diagnostics; using Internal.Runtime.Augments; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime.CompilerServices; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.Runtime.CallConverter; using CallingConvention = Internal.Runtime.CallConverter.CallingConvention; namespace Internal.Runtime.TypeLoader { internal unsafe struct CallConversionParameters { internal class GCHandleContainer { internal GCHandle _thisPtrHandle; internal GCHandle _dynamicInvokeArgHandle; internal GCHandle _returnObjectHandle; internal GCHandleContainer() { // Allocations of pinned gc handles done only once during the lifetime of a thread. // An empty string is used as the initial pinned object reference. _thisPtrHandle = GCHandle.Alloc("", GCHandleType.Pinned); _dynamicInvokeArgHandle = GCHandle.Alloc("", GCHandleType.Pinned); _returnObjectHandle = GCHandle.Alloc("", GCHandleType.Pinned); } ~GCHandleContainer() { // Free all the pinned objects when the thread dies to avoid gchandle leaks _thisPtrHandle.Free(); _dynamicInvokeArgHandle.Free(); _returnObjectHandle.Free(); } } private struct DelegateData { internal Delegate _delegateObject; internal object _firstParameter; internal object _helperObject; internal IntPtr _extraFunctionPointerOrData; internal IntPtr _functionPointer; // Computed fields internal object _boxedFirstParameter; internal object _multicastThisPointer; internal int _multicastTargetCount; } internal CallConversionInfo _conversionInfo; internal ArgIterator _callerArgs; internal ArgIterator _calleeArgs; internal byte* _callerTransitionBlock; internal IntPtr _invokeReturnValue; internal bool _copyReturnValue; internal object[] _dynamicInvokeParams; internal CallConverterThunk.DynamicInvokeByRefArgObjectWrapper[] _dynamicInvokeByRefObjectArgs; private IntPtr _instantiatingStubArgument; private IntPtr _functionPointerToCall; private DelegateData _delegateData; [ThreadStatic] internal static GCHandleContainer s_pinnedGCHandles; // Signature of the DynamicInvokeImpl method on delegates is always the same. private static ArgIteratorData s_delegateDynamicInvokeImplArgIteratorData = new ArgIteratorData(true, false, new TypeHandle[]{ new TypeHandle(false, typeof(object).TypeHandle), new TypeHandle(false, typeof(IntPtr).TypeHandle), new TypeHandle(true, typeof(InvokeUtils.ArgSetupState).TypeHandle) }, new TypeHandle(false, typeof(object).TypeHandle)); // Signature of all the InvokeRetXYZ reflection invoker stubs is always the same. private static ArgIteratorData s_reflectionDynamicInvokeImplArgIteratorData = new ArgIteratorData(false, false, new TypeHandle[]{ new TypeHandle(false, typeof(object).TypeHandle), new TypeHandle(false, typeof(IntPtr).TypeHandle), new TypeHandle(true, typeof(InvokeUtils.ArgSetupState).TypeHandle), new TypeHandle(false, typeof(bool).TypeHandle) }, new TypeHandle(false, typeof(object).TypeHandle)); internal CallConversionParameters(CallConversionInfo conversionInfo, IntPtr callerTransitionBlockParam) { // Make sure the thred static variable has been initialized for this thread s_pinnedGCHandles = s_pinnedGCHandles ?? new GCHandleContainer(); _conversionInfo = conversionInfo; _callerTransitionBlock = (byte*)callerTransitionBlockParam.ToPointer(); _functionPointerToCall = conversionInfo.TargetFunctionPointer; _instantiatingStubArgument = conversionInfo.InstantiatingStubArgument; _delegateData = default(DelegateData); _calleeArgs = default(ArgIterator); _invokeReturnValue = IntPtr.Zero; _copyReturnValue = true; _dynamicInvokeParams = null; _dynamicInvokeByRefObjectArgs = null; // // Setup input argument iterator for the caller // ArgIteratorData callerIteratorData; if (conversionInfo.IsDelegateDynamicInvokeThunk) callerIteratorData = s_delegateDynamicInvokeImplArgIteratorData; else if (conversionInfo.IsReflectionDynamicInvokerThunk) callerIteratorData = s_reflectionDynamicInvokeImplArgIteratorData; else callerIteratorData = conversionInfo.ArgIteratorData; _callerArgs = new ArgIterator(callerIteratorData, callerIteratorData.HasThis() ? CallingConvention.ManagedInstance : CallingConvention.ManagedStatic, conversionInfo.CallerHasParamType, conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget, conversionInfo.CallerForcedByRefData, false, false); // Setup input bool forceCalleeHasParamType = false; // If the callee MAY have a param type, we need to know before we create the callee arg iterator // To do this we need to actually load the target address and see if it has the generic method pointer // bit set. if (conversionInfo.CalleeMayHaveParamType) { ArgIterator callerArgsLookupTargetFunctionPointer = new ArgIterator(conversionInfo.ArgIteratorData, conversionInfo.ArgIteratorData.HasThis() ? CallingConvention.ManagedInstance : CallingConvention.ManagedStatic, conversionInfo.CallerHasParamType, conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget, conversionInfo.CallerForcedByRefData, false, false); // Find the last valid caller offset. That's the offset of the target function pointer. int ofsCallerValid = TransitionBlock.InvalidOffset; while (true) { // Setup argument offsets. int ofsCallerTemp = callerArgsLookupTargetFunctionPointer.GetNextOffset(); // Check to see if we've handled all the arguments that we are to pass to the callee. if (TransitionBlock.InvalidOffset == ofsCallerTemp) break; ofsCallerValid = ofsCallerTemp; } if (ofsCallerValid == TransitionBlock.InvalidOffset) throw new InvalidProgramException(); int stackSizeCaller = callerArgsLookupTargetFunctionPointer.GetArgSize(); Debug.Assert(stackSizeCaller == IntPtr.Size); void* pSrc = _callerTransitionBlock + ofsCallerValid; IntPtr tempFunctionPointer = *((IntPtr*)pSrc); forceCalleeHasParamType = UpdateCalleeFunctionPointer(tempFunctionPointer); } // Retrieve target function pointer and instantiation argument for delegate thunks if (conversionInfo.IsDelegateThunk) { Debug.Assert(_callerArgs.HasThis() && !_conversionInfo.IsUnboxingThunk); IntPtr locationOfThisPointer = (IntPtr)(_callerTransitionBlock + ArgIterator.GetThisOffset()); _delegateData._delegateObject = (Delegate)Unsafe.As<IntPtr, Object>(ref *(IntPtr*)locationOfThisPointer); Debug.Assert(_delegateData._delegateObject != null); RuntimeAugments.GetDelegateData( _delegateData._delegateObject, out _delegateData._firstParameter, out _delegateData._helperObject, out _delegateData._extraFunctionPointerOrData, out _delegateData._functionPointer); if (conversionInfo.TargetDelegateFunctionIsExtraFunctionPointerOrDataField) { if (conversionInfo.IsOpenInstanceDelegateThunk) { _delegateData._boxedFirstParameter = BoxedCallerFirstArgument; Debug.Assert(_delegateData._boxedFirstParameter != null); _callerArgs.Reset(); IntPtr resolvedTargetFunctionPointer = OpenMethodResolver.ResolveMethod(_delegateData._extraFunctionPointerOrData, _delegateData._boxedFirstParameter); forceCalleeHasParamType = UpdateCalleeFunctionPointer(resolvedTargetFunctionPointer); } else { forceCalleeHasParamType = UpdateCalleeFunctionPointer(_delegateData._extraFunctionPointerOrData); } } else if (conversionInfo.IsMulticastDelegate) { _delegateData._multicastTargetCount = (int)_delegateData._extraFunctionPointerOrData; } } // // Setup output argument iterator for the callee // _calleeArgs = new ArgIterator(conversionInfo.ArgIteratorData, (conversionInfo.ArgIteratorData.HasThis() && !conversionInfo.IsStaticDelegateThunk) ? CallingConvention.ManagedInstance : CallingConvention.ManagedStatic, forceCalleeHasParamType || conversionInfo.CalleeHasParamType, false, conversionInfo.CalleeForcedByRefData, conversionInfo.IsOpenInstanceDelegateThunk, conversionInfo.IsClosedStaticDelegate); // The function pointer, 'hasParamType', and 'hasThis' flags for the callee arg iterator need to be computed/read from the caller's // input arguments in the case of a reflection invoker thunk (the target method pointer and 'hasThis' flags are // passed in as parameters from the caller, not loaded from a static method signature in native layout) if (conversionInfo.IsReflectionDynamicInvokerThunk) ComputeCalleeFlagsAndFunctionPointerForReflectionInvokeThunk(); #if CALLINGCONVENTION_CALLEE_POPS // Ensure that the count of bytes in the stack is available _callerArgs.CbStackPop(); #endif } private void ComputeCalleeFlagsAndFunctionPointerForReflectionInvokeThunk() { Debug.Assert(_conversionInfo.IsReflectionDynamicInvokerThunk); Debug.Assert(!_callerArgs.Equals(default(ArgIterator)) && !_calleeArgs.Equals(default(ArgIterator))); _callerArgs.GetNextOffset(); // Skip thisPtr { int ofsCaller = _callerArgs.GetNextOffset(); // methodToCall Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller); void** pSrc = (void**)(_callerTransitionBlock + ofsCaller); IntPtr functionPointer = new IntPtr(*pSrc); bool forceCalleeHasParamType = UpdateCalleeFunctionPointer(functionPointer); _calleeArgs.SetHasParamTypeAndReset(forceCalleeHasParamType); } _callerArgs.GetNextOffset(); // Skip argSetupState // targetIsThisCall { int ofsCaller = _callerArgs.GetNextOffset(); // targetIsThisCall Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller); bool* pSrc = (bool*)(_callerTransitionBlock + ofsCaller); bool targetIsThisCall = *pSrc; _calleeArgs.SetHasThisAndReset(targetIsThisCall); } _callerArgs.Reset(); } internal void ResetPinnedObjects() { // Reset all pinned gchandles to an empty string. // Freeing of gchandles is done in the destructor of GCHandleContainer when the thread dies s_pinnedGCHandles._thisPtrHandle.Target = ""; s_pinnedGCHandles._returnObjectHandle.Target = ""; s_pinnedGCHandles._dynamicInvokeArgHandle.Target = ""; } private bool UpdateCalleeFunctionPointer(IntPtr newFunctionPointer) { if (FunctionPointerOps.IsGenericMethodPointer(newFunctionPointer)) { GenericMethodDescriptor* genericTarget = FunctionPointerOps.ConvertToGenericDescriptor(newFunctionPointer); _instantiatingStubArgument = genericTarget->InstantiationArgument; _functionPointerToCall = genericTarget->MethodFunctionPointer; return true; } else { _functionPointerToCall = newFunctionPointer; return false; } } internal void PrepareNextMulticastDelegateCall(int currentIndex) { if (!_conversionInfo.IsMulticastDelegate) { Environment.FailFast("Thunk is not a multicast delegate thunk!"); } Debug.Assert(currentIndex < _delegateData._multicastTargetCount); Debug.Assert(!_delegateData.Equals(default(DelegateData))); Debug.Assert(_delegateData._helperObject is Delegate[]); Debug.Assert(_delegateData._multicastTargetCount <= ((Delegate[])_delegateData._helperObject).Length); Delegate[] delegateArray = (Delegate[])_delegateData._helperObject; Delegate currentDelegate = delegateArray[currentIndex]; object helperObject; IntPtr extraFunctionPointerOrData; IntPtr functionPointer; RuntimeAugments.GetDelegateData(currentDelegate, out _delegateData._multicastThisPointer, out helperObject, out extraFunctionPointerOrData, out functionPointer); bool forceCalleeHasParamType = UpdateCalleeFunctionPointer(functionPointer); _calleeArgs.SetHasParamTypeAndReset(forceCalleeHasParamType); _callerArgs.Reset(); } internal int MulticastDelegateCallCount { get { Debug.Assert(_conversionInfo.IsMulticastDelegate); return _delegateData._multicastTargetCount; } } private object BoxedCallerFirstArgument { // Get the first argument that will be passed to the callee (if available), and box it if it's a value type. // The first argument is an actual explicit argument passed to the callee... i.e. not a thispointer or instantiationStubArg // NOTE: This method advances the caller ArgIterator and does NOT reset it. It's up to whoever calls this method // to reset the caller ArgIterator if it needs to be reset get { int ofsCaller = _callerArgs.GetNextOffset(); if (TransitionBlock.InvalidOffset == ofsCaller) return null; byte* pSrc = _callerTransitionBlock + ofsCaller; TypeHandle thValueType; _callerArgs.GetArgType(out thValueType); if (thValueType.IsNull()) { Debug.Assert(_callerArgs.GetArgSize() == IntPtr.Size); Debug.Assert(!_callerArgs.IsArgPassedByRef()); return Unsafe.As<IntPtr, Object>(ref *(IntPtr*)pSrc); } else { RuntimeTypeHandle argEEType = thValueType.GetRuntimeTypeHandle(); if (_callerArgs.IsArgPassedByRef()) { return RuntimeAugments.Box(argEEType, new IntPtr(*((void**)pSrc))); } else { return RuntimeAugments.Box(argEEType, new IntPtr(pSrc)); } } } } internal IntPtr ClosedStaticDelegateThisPointer { get { Debug.Assert(_conversionInfo.IsClosedStaticDelegate && !_delegateData.Equals(default(DelegateData))); Debug.Assert(_delegateData._helperObject != null); s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._helperObject; return RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)s_pinnedGCHandles._thisPtrHandle); } } internal void* ThisPointer { get { if (_conversionInfo.IsStaticDelegateThunk) return null; if (_callerArgs.HasThis() != _calleeArgs.HasThis()) { // Note: the _callerArgs for a reflection dynamic invoker thunk will never have a thisPtr // because it's a static method. The _calleeArgs may have a thisPtr if the target method // being called is an instance method. if (!_conversionInfo.IsReflectionDynamicInvokerThunk) { // Whether or not a given signature has a this parameter is not allowed to change across this thunk. Environment.FailFast("HasThis on signatures must match"); } } if (_calleeArgs.HasThis()) { void* thisPointer = null; if (_conversionInfo.IsThisPointerInDelegateData || _conversionInfo.IsAnyDynamicInvokerThunk) { // Assert that we have extracted the delegate data Debug.Assert(_conversionInfo.IsReflectionDynamicInvokerThunk || !_delegateData.Equals(default(DelegateData))); if (_conversionInfo.IsAnyDynamicInvokerThunk) { // Resilience to multiple or out of order calls _callerArgs.Reset(); int ofsCaller = _callerArgs.GetNextOffset(); Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller); void** pSrc = (void**)(_callerTransitionBlock + ofsCaller); // No need to pin since the thisPtr is one of the arguments on the caller TB return *pSrc; } if (_conversionInfo.IsOpenInstanceDelegateThunk) { // We should have already extracted and boxed the first parameter Debug.Assert(_delegateData._boxedFirstParameter != null); s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._boxedFirstParameter; // Note: We should advance the caller's ArgIterator since the first parameter is used as a thisPointer, // not as an actual parameter passed to the callee. // We do not need to advance the callee's ArgIterator because we already initialized it with a // 'skipFirstArg' flag _callerArgs.GetNextOffset(); } else if (_conversionInfo.IsMulticastDelegate) { Debug.Assert(_delegateData._multicastThisPointer != null); s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._multicastThisPointer; } else { Debug.Assert(_delegateData._helperObject != null); s_pinnedGCHandles._thisPtrHandle.Target = _delegateData._helperObject; } thisPointer = (void*)RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)s_pinnedGCHandles._thisPtrHandle); } else { thisPointer = *((void**)(_callerTransitionBlock + ArgIterator.GetThisOffset())); if (_conversionInfo.IsUnboxingThunk) { thisPointer = (void*)(((IntPtr*)thisPointer) + 1); } } return thisPointer; } return null; } } internal void* CallerReturnBuffer { get { // If the return buffer is treated the same way for both calling conventions if (_callerArgs.HasRetBuffArg() == _calleeArgs.HasRetBuffArg()) { // Do nothing, or copy the ret buf arg around if (_callerArgs.HasRetBuffArg()) { return *((void**)(_callerTransitionBlock + _callerArgs.GetRetBuffArgOffset())); } } else { // We'll need to create a return buffer, or assign into the return buffer when the actual call completes. if (_calleeArgs.HasRetBuffArg()) { TypeHandle thValueType; bool forceByRefUnused; void* callerRetBuffer = null; if (_conversionInfo.IsAnyDynamicInvokerThunk) { // In the case of dynamic invoke thunks that use return buffers, we need to allocate a buffer for the return // value, of the same type as the return value type handle in the callee's arguments. Debug.Assert(!_callerArgs.HasRetBuffArg()); CorElementType returnType = _calleeArgs.GetReturnType(out thValueType, out forceByRefUnused); RuntimeTypeHandle returnValueType = thValueType.IsNull() ? typeof(object).TypeHandle : thValueType.GetRuntimeTypeHandle(); s_pinnedGCHandles._returnObjectHandle.Target = RuntimeAugments.RawNewObject(returnValueType); // The transition block has a space reserved for storing return buffer data. This is protected conservatively. // Copy the address of the allocated object to the protected memory to be able to safely unpin it. callerRetBuffer = _callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock(); *((void**)callerRetBuffer) = (void*)RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)s_pinnedGCHandles._returnObjectHandle); // Unpin the allocated object (it's now protected in the caller's conservatively reported memory space) s_pinnedGCHandles._returnObjectHandle.Target = ""; // Point the callerRetBuffer to the begining of the actual object's data (skipping the EETypePtr slot) callerRetBuffer = (void*)(new IntPtr(*((void**)callerRetBuffer)) + IntPtr.Size); } else { // The transition block has a space reserved for storing return buffer data. This is protected conservatively callerRetBuffer = _callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock(); // Make sure buffer is nulled out, and setup the return buffer location. CorElementType returnType = _callerArgs.GetReturnType(out thValueType, out forceByRefUnused); int returnSize = TypeHandle.GetElemSize(returnType, thValueType); CallConverterThunk.memzeroPointerAligned((byte*)callerRetBuffer, returnSize); } Debug.Assert(callerRetBuffer != null); return callerRetBuffer; } } return null; } } internal void* VarArgSigCookie { get { if (_calleeArgs.IsVarArg() != _callerArgs.IsVarArg()) { // Whether or not a given signature has a this parameter is not allowed to change across this thunk. Environment.FailFast("IsVarArg on signatures must match"); } if (_calleeArgs.IsVarArg()) { return *((void**)(_callerTransitionBlock + _callerArgs.GetVASigCookieOffset())); } return null; } } internal IntPtr InstantiatingStubArgument { get { if (_calleeArgs.HasParamType() == _callerArgs.HasParamType()) { if (_calleeArgs.HasParamType()) { return new IntPtr(*((void**)(_callerTransitionBlock + _callerArgs.GetParamTypeArgOffset()))); } } else if (_calleeArgs.HasParamType()) { Debug.Assert(_instantiatingStubArgument != IntPtr.Zero); return _instantiatingStubArgument; } else { // Whether or not a given signature has a this parameter is not allowed to change across this thunk. Environment.FailFast("Uninstantiating thunks are not allowed"); } return IntPtr.Zero; } } internal IntPtr FunctionPointerToCall { get { if (_conversionInfo.IsDelegateDynamicInvokeThunk) { // Resilience to multiple or out of order calls { _callerArgs.Reset(); _callerArgs.GetNextOffset(); // thisPtr } int ofsCaller = _callerArgs.GetNextOffset(); // methodToCall Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller); void** pSrc = (void**)(_callerTransitionBlock + ofsCaller); return new IntPtr(*pSrc); } return _functionPointerToCall; } } internal IntPtr InvokeObjectArrayDelegate(object[] arguments) { if (!_conversionInfo.IsObjectArrayDelegateThunk) Environment.FailFast("Thunk is not an object array delegate thunk!"); Debug.Assert(!_delegateData.Equals(default(DelegateData))); Func<object[], object> targetDelegate = _delegateData._helperObject as Func<object[], object>; Debug.Assert(targetDelegate != null); s_pinnedGCHandles._returnObjectHandle.Target = targetDelegate(arguments ?? Array.Empty<object>()); return RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)s_pinnedGCHandles._returnObjectHandle); } internal IntPtr GetArgSetupStateDataPointer() { if (!_conversionInfo.IsAnyDynamicInvokerThunk) Environment.FailFast("Thunk is not a valid dynamic invoker thunk!"); // Resilience to multiple or out of order calls { _callerArgs.Reset(); _callerArgs.GetNextOffset(); // thisPtr _callerArgs.GetNextOffset(); // methodToCall } int ofsCaller = _callerArgs.GetNextOffset(); //argSetupState Debug.Assert(TransitionBlock.InvalidOffset != ofsCaller); void** pSrc = (void**)(_callerTransitionBlock + ofsCaller); // No need to pin since the argSetupState is one of the arguments on the caller TB return new IntPtr(*pSrc); } } }
/* * 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 Newtonsoft.Json; using QuantConnect.Interfaces; using QuantConnect.Securities.Future; using QuantConnect.Securities.FutureOption; using IB = QuantConnect.Brokerages.InteractiveBrokers.Client; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using IBApi; using QuantConnect.Data.Auxiliary; using QuantConnect.Logging; using QuantConnect.Securities; namespace QuantConnect.Brokerages.InteractiveBrokers { /// <summary> /// Provides the mapping between Lean symbols and InteractiveBrokers symbols. /// </summary> public class InteractiveBrokersSymbolMapper : ISymbolMapper { private readonly IMapFileProvider _mapFileProvider; // we have a special treatment of futures, because IB renamed several exchange tickers (like GBP instead of 6B). We fix this: // We map those tickers back to their original names using the map below private readonly Dictionary<string, string> _ibNameMap = new Dictionary<string, string>(); /// <summary> /// Constructs InteractiveBrokersSymbolMapper. Default parameters are used. /// </summary> public InteractiveBrokersSymbolMapper(IMapFileProvider mapFileProvider) : this(Path.Combine("InteractiveBrokers", "IB-symbol-map.json")) { _mapFileProvider = mapFileProvider; } /// <summary> /// Constructs InteractiveBrokersSymbolMapper /// </summary> /// <param name="ibNameMap">New names map (IB -> LEAN)</param> public InteractiveBrokersSymbolMapper(Dictionary<string, string> ibNameMap) { _ibNameMap = ibNameMap; } /// <summary> /// Constructs InteractiveBrokersSymbolMapper /// </summary> /// <param name="ibNameMapFullName">Full file name of the map file</param> public InteractiveBrokersSymbolMapper(string ibNameMapFullName) { if (File.Exists(ibNameMapFullName)) { _ibNameMap = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(ibNameMapFullName)); } } /// <summary> /// Converts a Lean symbol instance to an InteractiveBrokers symbol /// </summary> /// <param name="symbol">A Lean symbol instance</param> /// <returns>The InteractiveBrokers symbol</returns> public string GetBrokerageSymbol(Symbol symbol) { if (string.IsNullOrWhiteSpace(symbol?.Value)) throw new ArgumentException("Invalid symbol: " + (symbol == null ? "null" : symbol.ToString())); var ticker = GetMappedTicker(symbol); if (string.IsNullOrWhiteSpace(ticker)) throw new ArgumentException("Invalid symbol: " + symbol.ToString()); if (symbol.ID.SecurityType != SecurityType.Forex && symbol.ID.SecurityType != SecurityType.Equity && symbol.ID.SecurityType != SecurityType.Index && symbol.ID.SecurityType != SecurityType.Option && symbol.ID.SecurityType != SecurityType.IndexOption && symbol.ID.SecurityType != SecurityType.FutureOption && symbol.ID.SecurityType != SecurityType.Future) throw new ArgumentException("Invalid security type: " + symbol.ID.SecurityType); if (symbol.ID.SecurityType == SecurityType.Forex && ticker.Length != 6) throw new ArgumentException("Forex symbol length must be equal to 6: " + symbol.Value); switch (symbol.ID.SecurityType) { case SecurityType.Option: case SecurityType.IndexOption: // Final case is for equities. We use the mapped value to select // the equity we want to trade. We skip mapping for index options. return GetMappedTicker(symbol.Underlying); case SecurityType.FutureOption: // We use the underlying Future Symbol since IB doesn't use // the Futures Options' ticker, but rather uses the underlying's // Symbol, mapped to the brokerage. return GetBrokerageSymbol(symbol.Underlying); case SecurityType.Future: return GetBrokerageRootSymbol(symbol.ID.Symbol); case SecurityType.Equity: return ticker.Replace(".", " "); case SecurityType.Index: return ticker; } return ticker; } /// <summary> /// Converts an InteractiveBrokers symbol to a Lean symbol instance /// </summary> /// <param name="brokerageSymbol">The InteractiveBrokers symbol</param> /// <param name="securityType">The security type</param> /// <param name="market">The market</param> /// <param name="expirationDate">Expiration date of the security(if applicable)</param> /// <param name="strike">The strike of the security (if applicable)</param> /// <param name="optionRight">The option right of the security (if applicable)</param> /// <returns>A new Lean Symbol instance</returns> public Symbol GetLeanSymbol(string brokerageSymbol, SecurityType securityType, string market, DateTime expirationDate = default(DateTime), decimal strike = 0, OptionRight optionRight = 0) { if (string.IsNullOrWhiteSpace(brokerageSymbol)) throw new ArgumentException("Invalid symbol: " + brokerageSymbol); if (securityType != SecurityType.Forex && securityType != SecurityType.Equity && securityType != SecurityType.Index && securityType != SecurityType.Option && securityType != SecurityType.IndexOption && securityType != SecurityType.Future && securityType != SecurityType.FutureOption) throw new ArgumentException("Invalid security type: " + securityType); try { switch (securityType) { case SecurityType.Future: return Symbol.CreateFuture(GetLeanRootSymbol(brokerageSymbol), market, expirationDate); case SecurityType.Option: return Symbol.CreateOption(brokerageSymbol, market, OptionStyle.American, optionRight, strike, expirationDate); case SecurityType.IndexOption: // Index Options have their expiry offset from their last trading date by one day. We add one day // to get the expected expiration date. return Symbol.CreateOption( Symbol.Create(brokerageSymbol, SecurityType.Index, market), market, securityType.DefaultOptionStyle(), optionRight, strike, expirationDate.AddDays(1)); case SecurityType.FutureOption: var future = FuturesOptionsUnderlyingMapper.GetUnderlyingFutureFromFutureOption( GetLeanRootSymbol(brokerageSymbol), market, expirationDate, DateTime.Now); if (future == null) { // This is the worst case scenario, because we didn't find a matching futures contract for the FOP. // Note that this only applies to CBOT symbols for now. throw new ArgumentException($"The Future Option with expected underlying of {future} with expiry: {expirationDate:yyyy-MM-dd} has no matching underlying future contract."); } return Symbol.CreateOption( future, market, OptionStyle.American, optionRight, strike, expirationDate); case SecurityType.Equity: brokerageSymbol = brokerageSymbol.Replace(" ", "."); break; } return Symbol.Create(brokerageSymbol, securityType, market); } catch (Exception exception) { Log.Error(exception, "Error in GetLeanSymbol"); throw new ArgumentException($"Invalid symbol: {brokerageSymbol}, security type: {securityType}, market: {market}."); } } /// <summary> /// IB specific versions of the symbol mapping (GetBrokerageRootSymbol) for future root symbols /// </summary> /// <param name="rootSymbol">LEAN root symbol</param> /// <returns></returns> public string GetBrokerageRootSymbol(string rootSymbol) { var brokerageSymbol = _ibNameMap.FirstOrDefault(kv => kv.Value == rootSymbol); return brokerageSymbol.Key ?? rootSymbol; } /// <summary> /// IB specific versions of the symbol mapping (GetLeanRootSymbol) for future root symbols /// </summary> /// <param name="brokerageRootSymbol">IB Brokerage root symbol</param> /// <returns></returns> public string GetLeanRootSymbol(string brokerageRootSymbol) { return _ibNameMap.ContainsKey(brokerageRootSymbol) ? _ibNameMap[brokerageRootSymbol] : brokerageRootSymbol; } /// <summary> /// Parses a contract for future with malformed data. /// Malformed data usually manifests itself by having "0" assigned to some values /// we expect, like the contract's expiry date. The contract is returned by IB /// like this, usually due to a high amount of data subscriptions that are active /// in an account, surpassing IB's imposed limit. Read more about this here: https://interactivebrokers.github.io/tws-api/rtd_fqa_errors.html#rtd_common_errors_maxmktdata /// /// We are provided a string in the Symbol in malformed contracts that can be /// parsed to construct the clean contract, which is done by this method. /// </summary> /// <param name="malformedContract">Malformed contract (for futures), i.e. a contract with invalid values ("0") in some of its fields</param> /// <param name="symbolPropertiesDatabase">The symbol properties database to use</param> /// <returns>Clean Contract for the future</returns> /// <remarks> /// The malformed contract returns data similar to the following when calling <see cref="InteractiveBrokersBrokerage.GetContractDetails"/>: ES MAR2021 /// </remarks> public Contract ParseMalformedContractFutureSymbol(Contract malformedContract, SymbolPropertiesDatabase symbolPropertiesDatabase) { Log.Trace($"InteractiveBrokersSymbolMapper.ParseMalformedContractFutureSymbol(): Parsing malformed contract: {InteractiveBrokersBrokerage.GetContractDescription(malformedContract)} with trading class: \"{malformedContract.TradingClass}\""); // capture any character except spaces, match spaces, capture any char except digits, capture digits var matches = Regex.Matches(malformedContract.Symbol, @"^(\S*)\s*(\D*)(\d*)"); var match = matches[0].Groups; var contractSymbol = match[1].Value; var contractMonthExpiration = DateTime.ParseExact(match[2].Value, "MMM", CultureInfo.CurrentCulture).Month; var contractYearExpiration = match[3].Value; var leanSymbol = GetLeanRootSymbol(contractSymbol); string market; if (!symbolPropertiesDatabase.TryGetMarket(leanSymbol, SecurityType.Future, out market)) { market = InteractiveBrokersBrokerageModel.DefaultMarketMap[SecurityType.Future]; } var canonicalSymbol = Symbol.Create(leanSymbol, SecurityType.Future, market); var contractMonthYear = new DateTime(int.Parse(contractYearExpiration, CultureInfo.InvariantCulture), contractMonthExpiration, 1); // we get the expiration date using the FuturesExpiryFunctions var contractExpirationDate = FuturesExpiryFunctions.FuturesExpiryFunction(canonicalSymbol)(contractMonthYear); return new Contract { Symbol = contractSymbol, Multiplier = malformedContract.Multiplier, LastTradeDateOrContractMonth = $"{contractExpirationDate:yyyyMMdd}", Exchange = malformedContract.Exchange, SecType = malformedContract.SecType, IncludeExpired = false, Currency = malformedContract.Currency }; } private string GetMappedTicker(Symbol symbol) { var ticker = symbol.ID.Symbol; if (symbol.ID.SecurityType == SecurityType.Equity) { var mapFile = _mapFileProvider.Get(AuxiliaryDataKey.Create(symbol)).ResolveMapFile(symbol); ticker = mapFile.GetMappedSymbol(DateTime.UtcNow, symbol.Value); } return ticker; } /// <summary> /// Parses a contract for options with malformed data. /// Malformed data usually manifests itself by having "0" assigned to some values /// we expect, like the contract's expiry date. The contract is returned by IB /// like this, usually due to a high amount of data subscriptions that are active /// in an account, surpassing IB's imposed limit. Read more about this here: https://interactivebrokers.github.io/tws-api/rtd_fqa_errors.html#rtd_common_errors_maxmktdata /// /// We are provided a string in the Symbol in malformed contracts that can be /// parsed to construct the clean contract, which is done by this method. /// </summary> /// <param name="malformedContract">Malformed contract (for options), i.e. a contract with invalid values ("0") in some of its fields</param> /// <param name="exchange">Exchange that the contract's asset lives on/where orders will be routed through</param> /// <returns>Clean Contract for the option</returns> /// <remarks> /// The malformed contract returns data similar to the following when calling <see cref="InteractiveBrokersBrokerage.GetContractDetails"/>: /// OPT SPY JUN2021 350 P [SPY 210618P00350000 100] USD 0 0 0 /// /// ... which the contents inside [] follow the pattern: /// /// [SYMBOL YY_MM_DD_OPTIONRIGHT_STRIKE(divide by 1000) MULTIPLIER] /// </remarks> public static Contract ParseMalformedContractOptionSymbol(Contract malformedContract, string exchange = "Smart") { Log.Trace($"InteractiveBrokersSymbolMapper.ParseMalformedContractOptionSymbol(): Parsing malformed contract: {InteractiveBrokersBrokerage.GetContractDescription(malformedContract)} with trading class: \"{malformedContract.TradingClass}\""); // we search for the '[ ]' pattern, inside of it we: (capture any character except spaces, match spaces) -> 3 times var matches = Regex.Matches(malformedContract.Symbol, @"^.*[\[](\S*)\s*(\S*)\s*(\S*)[\]]"); var match = matches[0].Groups; var contractSymbol = match[1].Value; var contractSpecification = match[2].Value; var multiplier = match[3].Value; var expiryDate = "20" + contractSpecification.Substring(0, 6); var contractRight = contractSpecification[6] == 'C' ? IB.RightType.Call : IB.RightType.Put; var contractStrike = long.Parse(contractSpecification.Substring(7), CultureInfo.InvariantCulture) / 1000.0; return new Contract { Symbol = contractSymbol, Multiplier = multiplier, LastTradeDateOrContractMonth = expiryDate, Right = contractRight, Strike = contractStrike, Exchange = exchange, SecType = malformedContract.SecType, IncludeExpired = false, Currency = malformedContract.Currency }; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Globalization; using Xunit; using System.Collections; using System.Collections.Generic; namespace System.Json.Tests { public class JsonValueTests { [Fact] public void JsonValue_Load_LoadWithTrailingCommaInDictionary() { Parse("{ \"a\": \"b\",}", value => { Assert.Equal(1, value.Count); Assert.Equal(JsonType.String, value["a"].JsonType); Assert.Equal("b", value["a"]); JsonValue.Parse("[{ \"a\": \"b\",}]"); }); } [Theory] [InlineData("[]")] [InlineData(" \t \r \n [ \t \r \n ] \t \r \n ")] public void Parse_EmptyArray(string jsonString) { Parse(jsonString, value => { Assert.Equal(0, value.Count); Assert.Equal(JsonType.Array, value.JsonType); }); } [Theory] [InlineData("{}")] [InlineData(" \t \r \n { \t \r \n } \t \r \n ")] public void Parse_EmptyDictionary(string jsonString) { Parse(jsonString, value => { Assert.Equal(0, value.Count); Assert.Equal(JsonType.Object, value.JsonType); }); } public static IEnumerable<object[]> ParseIntegralBoundaries_TestData() { yield return new object[] { "2147483649", "2147483649" }; yield return new object[] { "4294967297", "4294967297" }; yield return new object[] { "9223372036854775807", "9223372036854775807" }; yield return new object[] { "18446744073709551615", "18446744073709551615" }; yield return new object[] { "79228162514264337593543950336", "7.9228162514264338E+28" }; } [Theory] [MemberData(nameof(ParseIntegralBoundaries_TestData))] public void Parse_IntegralBoundaries_LessThanMaxDouble_Works(string jsonString, string expectedToString) { Parse(jsonString, value => { Assert.Equal(JsonType.Number, value.JsonType); Assert.Equal(expectedToString, value.ToString()); }); } [Fact] public void Parse_TrueFalse() { Parse("[true, false]", value => { Assert.Equal(2, value.Count); Assert.Equal("true", value[0].ToString()); Assert.Equal("false", value[1].ToString()); }); } [Fact] public void JsonValue_Load_ToString_JsonArrayWithNulls() { Parse("[1,2,3,null]", value => { Assert.Equal(4, value.Count); Assert.Equal(JsonType.Array, value.JsonType); Assert.Equal("[1, 2, 3, null]", value.ToString()); }); } [Fact] public void JsonValue_ToString_JsonObjectWithNulls() { Parse("{\"a\":null,\"b\":2}", value => { Assert.Equal(2, value.Count); Assert.Equal(JsonType.Object, value.JsonType); Assert.Equal("{\"a\": null, \"b\": 2}", value.ToString()); }); } [Fact] public void JsonObject_ToString_OrderingMaintained() { var obj = new JsonObject(); obj["a"] = 1; obj["c"] = 3; obj["b"] = 2; Assert.Equal("{\"a\": 1, \"b\": 2, \"c\": 3}", obj.ToString()); } [Fact] public void JsonPrimitive_QuoteEscape() { Assert.Equal((new JsonPrimitive("\"\"")).ToString(), "\"\\\"\\\"\""); } [Fact] public void Load_NullStream_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("stream", () => JsonValue.Load((Stream)null)); } [Fact] public void Load_NullTextReader_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("textReader", () => JsonValue.Load((TextReader)null)); } [Fact] public void Parse_NullJsonString_ThrowArgumentNullException() { Assert.Throws<ArgumentNullException>("jsonString", () => JsonValue.Parse(null)); } [Theory] [InlineData("")] [InlineData("-")] [InlineData("- ")] [InlineData("1.")] [InlineData("1. ")] [InlineData("1e+")] [InlineData("1 2")] [InlineData("077")] [InlineData("[1,]")] [InlineData("NaN")] [InlineData("Infinity")] [InlineData("-Infinity")] [InlineData("[")] [InlineData("[1")] [InlineData("{")] [InlineData("{ ")] [InlineData("{1")] [InlineData("{\"")] [InlineData("{\"u")] [InlineData("{\"\\")] [InlineData("{\"\\u")] [InlineData("{\"\\uABC")] [InlineData("{\"\\/")] [InlineData("{\"\\\\")] [InlineData("{\"\\\"")] [InlineData("{\"\\!")] [InlineData("[tru]")] [InlineData("[fals]")] [InlineData("{\"name\"}")] [InlineData("{\"name\":}")] [InlineData("{\"name\":1")] [InlineData("1e")] [InlineData("1e-")] [InlineData("\0")] [InlineData("\u000B1")] [InlineData("\u000C1")] [InlineData("{\"\\a\"}")] [InlineData("{\"\\z\"}")] public void Parse_InvalidInput_ThrowsArgumentException(string value) { Assert.Throws<ArgumentException>(null, () => JsonValue.Parse(value)); using (StringReader textReader = new StringReader(value)) { Assert.Throws<ArgumentException>(null, () => JsonValue.Load(textReader)); } using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(value))) { Assert.Throws<ArgumentException>(null, () => JsonValue.Load(stream)); } } [Fact] public void Parse_DoubleTooLarge_ThrowsOverflowException() { Assert.Throws<OverflowException>(() => JsonValue.Parse("1.7976931348623157E+309")); } [Fact] public void Parse_InvalidNumericString_ThrowsFormatException() { Assert.Throws<FormatException>(() => JsonValue.Parse("1E!")); } [Theory] [InlineData("0", 0)] [InlineData("-0", 0)] [InlineData("0.00", 0)] [InlineData("-0.00", 0)] [InlineData("1", 1)] [InlineData("1.1", 1.1)] [InlineData("-1", -1)] [InlineData("-1.1", -1.1)] [InlineData("1e-10", 1e-10)] [InlineData("1e+10", 1e+10)] [InlineData("1e-30", 1e-30)] [InlineData("1e+30", 1e+30)] [InlineData("\"1\"", 1)] [InlineData("\"1.1\"", 1.1)] [InlineData("\"-1\"", -1)] [InlineData("\"-1.1\"", -1.1)] [InlineData("\"NaN\"", double.NaN)] [InlineData("\"Infinity\"", double.PositiveInfinity)] [InlineData("\"-Infinity\"", double.NegativeInfinity)] [InlineData("0.000000000000000000000000000011", 1.1E-29)] public void JsonValue_Parse_Double(string json, double expected) { foreach (string culture in new[] { "en", "fr", "de" }) { CultureInfo old = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo(culture); Assert.Equal(expected, (double)JsonValue.Parse(json)); } finally { CultureInfo.CurrentCulture = old; } } } // Convert a number to json and parse the string, then compare the result to the original value [Theory] [InlineData(1)] [InlineData(1.1)] [InlineData(1.25)] [InlineData(-1)] [InlineData(-1.1)] [InlineData(-1.25)] [InlineData(1e-20)] [InlineData(1e+20)] [InlineData(1e-30)] [InlineData(1e+30)] [InlineData(3.1415926535897932384626433)] [InlineData(3.1415926535897932384626433e-20)] [InlineData(3.1415926535897932384626433e+20)] [InlineData(double.NaN)] [InlineData(double.PositiveInfinity)] [InlineData(double.NegativeInfinity)] [InlineData(double.MinValue)] [InlineData(double.MaxValue)] [InlineData(18014398509481982.0)] // A number which needs 17 digits (see http://stackoverflow.com/questions/6118231/why-do-i-need-17-significant-digits-and-not-16-to-represent-a-double) [InlineData(1.123456789e-29)] [InlineData(1.123456789e-28)] // Values around the smallest positive decimal value public void JsonValue_Parse_Double_ViaJsonPrimitive(double number) { foreach (string culture in new[] { "en", "fr", "de" }) { CultureInfo old = CultureInfo.CurrentCulture; try { CultureInfo.CurrentCulture = new CultureInfo(culture); Assert.Equal(number, (double)JsonValue.Parse(new JsonPrimitive(number).ToString())); } finally { CultureInfo.CurrentCulture = old; } } } [Fact] public void JsonValue_Parse_MinMax_Integers_ViaJsonPrimitive() { Assert.Equal(sbyte.MinValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MinValue).ToString())); Assert.Equal(sbyte.MaxValue, (sbyte)JsonValue.Parse(new JsonPrimitive(sbyte.MaxValue).ToString())); Assert.Equal(byte.MinValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MinValue).ToString())); Assert.Equal(byte.MaxValue, (byte)JsonValue.Parse(new JsonPrimitive(byte.MaxValue).ToString())); Assert.Equal(short.MinValue, (short)JsonValue.Parse(new JsonPrimitive(short.MinValue).ToString())); Assert.Equal(short.MaxValue, (short)JsonValue.Parse(new JsonPrimitive(short.MaxValue).ToString())); Assert.Equal(ushort.MinValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MinValue).ToString())); Assert.Equal(ushort.MaxValue, (ushort)JsonValue.Parse(new JsonPrimitive(ushort.MaxValue).ToString())); Assert.Equal(int.MinValue, (int)JsonValue.Parse(new JsonPrimitive(int.MinValue).ToString())); Assert.Equal(int.MaxValue, (int)JsonValue.Parse(new JsonPrimitive(int.MaxValue).ToString())); Assert.Equal(uint.MinValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MinValue).ToString())); Assert.Equal(uint.MaxValue, (uint)JsonValue.Parse(new JsonPrimitive(uint.MaxValue).ToString())); Assert.Equal(long.MinValue, (long)JsonValue.Parse(new JsonPrimitive(long.MinValue).ToString())); Assert.Equal(long.MaxValue, (long)JsonValue.Parse(new JsonPrimitive(long.MaxValue).ToString())); Assert.Equal(ulong.MinValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MinValue).ToString())); Assert.Equal(ulong.MaxValue, (ulong)JsonValue.Parse(new JsonPrimitive(ulong.MaxValue).ToString())); Assert.Equal("1E-30", JsonValue.Parse("1e-30").ToString()); Assert.Equal("1E+30", JsonValue.Parse("1e+30").ToString()); } [Theory] [InlineData("Fact\b\f\n\r\t\"\\/</\0x")] [InlineData("\ud800")] [InlineData("x\ud800")] [InlineData("\udfff\ud800")] [InlineData("\ude03\ud912")] [InlineData("\uc000\ubfff")] [InlineData("\udfffx")] public void JsonPrimitive_Roundtrip_ValidUnicode(string str) { string json = new JsonPrimitive(str).ToString(); new UTF8Encoding(false, true).GetBytes(json); Assert.Equal(str, JsonValue.Parse(json)); } [Fact] public void JsonPrimitive_Roundtrip_ValidUnicode_AllChars() { for (int i = 0; i <= char.MaxValue; i++) { JsonPrimitive_Roundtrip_ValidUnicode("x" + (char)i); } } // String handling: http://tools.ietf.org/html/rfc7159#section-7 [Fact] public void JsonPrimitive_StringHandling() { Assert.Equal("\"Fact\"", new JsonPrimitive("Fact").ToString()); // Handling of characters Assert.Equal("\"f\"", new JsonPrimitive('f').ToString()); Assert.Equal('f', (char)JsonValue.Parse("\"f\"")); // Control characters with special escape sequence Assert.Equal("\"\\b\\f\\n\\r\\t\"", new JsonPrimitive("\b\f\n\r\t").ToString()); // Other characters which must be escaped Assert.Equal(@"""\""\\""", new JsonPrimitive("\"\\").ToString()); // Control characters without special escape sequence for (int i = 0; i < 32; i++) { if (i != '\b' && i != '\f' && i != '\n' && i != '\r' && i != '\t') { Assert.Equal("\"\\u" + i.ToString("x04") + "\"", new JsonPrimitive("" + (char)i).ToString()); } } // JSON does not require U+2028 and U+2029 to be escaped, but // JavaScript does require this: // http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character/9168133#9168133 Assert.Equal("\"\\u2028\\u2029\"", new JsonPrimitive("\u2028\u2029").ToString()); // '/' also does not have to be escaped, but escaping it when // preceeded by a '<' avoids problems with JSON in HTML <script> tags Assert.Equal("\"<\\/\"", new JsonPrimitive("</").ToString()); // Don't escape '/' in other cases as this makes the JSON hard to read Assert.Equal("\"/bar\"", new JsonPrimitive("/bar").ToString()); Assert.Equal("\"foo/bar\"", new JsonPrimitive("foo/bar").ToString()); // Valid strings should not be escaped: Assert.Equal("\"\ud7ff\"", new JsonPrimitive("\ud7ff").ToString()); Assert.Equal("\"\ue000\"", new JsonPrimitive("\ue000").ToString()); Assert.Equal("\"\ud800\udc00\"", new JsonPrimitive("\ud800\udc00").ToString()); Assert.Equal("\"\ud912\ude03\"", new JsonPrimitive("\ud912\ude03").ToString()); Assert.Equal("\"\udbff\udfff\"", new JsonPrimitive("\udbff\udfff").ToString()); Assert.Equal("\"{\\\"\\\\uD800\\\\uDC00\\\": 1}\"", new JsonPrimitive("{\"\\uD800\\uDC00\": 1}").ToString()); } [Fact] public void GetEnumerator_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => ((IEnumerable)value).GetEnumerator()); } [Fact] public void Count_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value.Count); } [Fact] public void Item_Int_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value[0]); Assert.Throws<InvalidOperationException>(() => value[0] = 0); } [Fact] public void Item_String_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value["abc"]); Assert.Throws<InvalidOperationException>(() => value["abc"] = 0); } [Fact] public void ContainsKey_ThrowsInvalidOperationException() { JsonValue value = JsonValue.Parse("1"); Assert.Throws<InvalidOperationException>(() => value.ContainsKey("key")); } [Fact] public void Save_Stream() { JsonSubValue value = new JsonSubValue(); using (MemoryStream stream = new MemoryStream()) { value.Save(stream); Assert.Empty(stream.ToArray()); } } [Fact] public void Save_Null_ThrowsArgumentNullException() { JsonValue value = new JsonSubValue(); Assert.Throws<ArgumentNullException>("stream", () => value.Save((Stream)null)); } [Fact] public void ImplicitConversion_NullJsonValue_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("value", () => { bool i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { byte i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { char i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { decimal i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { double i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { float i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { int i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { long i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { sbyte i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { short i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { uint i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { ulong i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { ushort i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { DateTime i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { DateTimeOffset i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { TimeSpan i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { Guid i = (JsonValue)null; }); Assert.Throws<ArgumentNullException>("value", () => { Uri i = (JsonValue)null; }); } [Fact] public void ImplicitConversion_NotJsonPrimitive_ThrowsInvalidCastException() { Assert.Throws<InvalidCastException>(() => { bool i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { byte i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { char i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { decimal i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { double i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { float i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { int i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { long i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { sbyte i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { short i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { string i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { uint i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { ulong i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { ushort i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { DateTime i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { DateTimeOffset i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { TimeSpan i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { Guid i = new JsonArray(); }); Assert.Throws<InvalidCastException>(() => { Uri i = new JsonArray(); }); } [Fact] public void ImplicitCast_Bool() { JsonPrimitive primitive = new JsonPrimitive(true); bool toPrimitive = primitive; Assert.True(toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Byte() { JsonPrimitive primitive = new JsonPrimitive(1); byte toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Char() { JsonPrimitive primitive = new JsonPrimitive(1); char toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Decimal() { JsonPrimitive primitive = new JsonPrimitive(1m); decimal toPrimitive = primitive; Assert.Equal(1m, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Double() { JsonPrimitive primitive = new JsonPrimitive(1); double toPrimitive = primitive; Assert.Equal(1.0, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Float() { JsonPrimitive primitive = new JsonPrimitive(1); float toPrimitive = primitive; Assert.Equal(1.0f, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Int() { JsonPrimitive primitive = new JsonPrimitive(1); int toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Long() { JsonPrimitive primitive = new JsonPrimitive(1); long toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_SByte() { JsonPrimitive primitive = new JsonPrimitive(1); sbyte toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Short() { JsonPrimitive primitive = new JsonPrimitive(1); short toPrimitive = primitive; Assert.Equal(1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Theory] [InlineData("abc")] [InlineData(null)] public void ImplicitCast_String(string value) { JsonPrimitive primitive = new JsonPrimitive(value); string toPrimitive = primitive; Assert.Equal(value, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_String_NullString() { string toPrimitive = (JsonPrimitive)null; Assert.Equal(null, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(new JsonPrimitive((string)null), toPrimitive); } [Fact] public void ImplicitCast_UInt() { JsonPrimitive primitive = new JsonPrimitive(1); uint toPrimitive = primitive; Assert.Equal((uint)1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_ULong() { JsonPrimitive primitive = new JsonPrimitive(1); ulong toPrimitive = primitive; Assert.Equal((ulong)1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_UShort() { JsonPrimitive primitive = new JsonPrimitive(1); ushort toPrimitive = primitive; Assert.Equal((ushort)1, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_DateTime() { JsonPrimitive primitive = new JsonPrimitive(DateTime.MinValue); DateTime toPrimitive = primitive; Assert.Equal(DateTime.MinValue, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_DateTimeOffset() { JsonPrimitive primitive = new JsonPrimitive(DateTimeOffset.MinValue); DateTimeOffset toPrimitive = primitive; Assert.Equal(DateTimeOffset.MinValue, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_TimeSpan() { JsonPrimitive primitive = new JsonPrimitive(TimeSpan.Zero); TimeSpan toPrimitive = primitive; Assert.Equal(TimeSpan.Zero, toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Guid() { JsonPrimitive primitive = new JsonPrimitive(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); Guid toPrimitive = primitive; Assert.Equal(new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ImplicitCast_Uri() { JsonPrimitive primitive = new JsonPrimitive(new Uri("scheme://host/")); Uri toPrimitive = primitive; Assert.Equal(new Uri("scheme://host/"), toPrimitive); JsonValue fromPrimitive = toPrimitive; Assert.Equal(primitive, toPrimitive); } [Fact] public void ToString_InvalidJsonType_ThrowsInvalidCastException() { InvalidJsonValue value = new InvalidJsonValue(); Assert.Throws<InvalidCastException>(() => value.ToString()); } private static void Parse(string jsonString, Action<JsonValue> action) { action(JsonValue.Parse(jsonString)); using (StringReader textReader = new StringReader(jsonString)) { action(JsonValue.Load(textReader)); } using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString))) { action(JsonValue.Load(stream)); } } public class JsonSubValue : JsonValue { public override JsonType JsonType => JsonType.String; public override void Save(TextWriter textWriter) => textWriter.Write("Hello"); } public class InvalidJsonValue : JsonValue { public override JsonType JsonType => (JsonType)(-1); } } }
using Magnesium; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; namespace Magnesium.Vulkan { public class VkQueue : IMgQueue { internal IntPtr Handle = IntPtr.Zero; internal VkQueue(IntPtr handle) { Handle = handle; } public Result QueueSubmit(MgSubmitInfo[] pSubmits, IMgFence fence) { var bFence = (VkFence)fence; var bFencePtr = bFence != null ? bFence.Handle : 0UL; var attachedItems = new List<IntPtr>(); try { unsafe { uint submitCount = 0; if (pSubmits != null) { submitCount = (uint)pSubmits.Length; } var submissions = stackalloc VkSubmitInfo[(int)submitCount]; for (var i = 0; i < submitCount; ++i) { var currentInfo = pSubmits[i]; var waitSemaphoreCount = 0U; var pWaitSemaphores = IntPtr.Zero; var pWaitDstStageMask = IntPtr.Zero; if (currentInfo.WaitSemaphores != null) { waitSemaphoreCount = (uint)currentInfo.WaitSemaphores.Length; if (waitSemaphoreCount > 0) { pWaitSemaphores = VkInteropsUtility.ExtractUInt64HandleArray( currentInfo.WaitSemaphores, (arg) => { var bSemaphore = (VkSemaphore)arg.WaitSemaphore; Debug.Assert(bSemaphore != null); return bSemaphore.Handle; }); attachedItems.Add(pWaitSemaphores); pWaitDstStageMask = VkInteropsUtility.AllocateHGlobalArray<MgSubmitInfoWaitSemaphoreInfo, uint>( currentInfo.WaitSemaphores, (arg) => { return (uint) arg.WaitDstStageMask; }); attachedItems.Add(pWaitDstStageMask); } } var commandBufferCount = 0U; var pCommandBuffers = IntPtr.Zero; if (currentInfo.CommandBuffers != null) { commandBufferCount = (uint)currentInfo.CommandBuffers.Length; if (commandBufferCount > 0) { pCommandBuffers = VkInteropsUtility.ExtractIntPtrHandleArray ( currentInfo.CommandBuffers, (arg) => { var bCommandBuffer = (VkCommandBuffer)arg; Debug.Assert(bCommandBuffer != null); return bCommandBuffer.Handle; } ); attachedItems.Add(pCommandBuffers); } } var signalSemaphoreCount = 0U; var pSignalSemaphores = IntPtr.Zero; if (currentInfo.SignalSemaphores != null) { signalSemaphoreCount = (uint)currentInfo.SignalSemaphores.Length; if (signalSemaphoreCount > 0) { pSignalSemaphores = VkInteropsUtility.ExtractUInt64HandleArray( currentInfo.SignalSemaphores, (arg) => { var bSemaphore = (VkSemaphore)arg; Debug.Assert(bSemaphore != null); return bSemaphore.Handle; }); attachedItems.Add(pSignalSemaphores); } } submissions[i] = new VkSubmitInfo { sType = VkStructureType.StructureTypeSubmitInfo, pNext = IntPtr.Zero, waitSemaphoreCount = waitSemaphoreCount, pWaitSemaphores = pWaitSemaphores, pWaitDstStageMask = pWaitDstStageMask, commandBufferCount = commandBufferCount, pCommandBuffers = pCommandBuffers, signalSemaphoreCount = signalSemaphoreCount, pSignalSemaphores = pSignalSemaphores, }; } return Interops.vkQueueSubmit(Handle, submitCount, submitCount > 0 ? submissions : null, bFencePtr); } } finally { foreach (var item in attachedItems) { Marshal.FreeHGlobal(item); } } } public Result QueueWaitIdle() { return Interops.vkQueueWaitIdle(Handle); } public Result QueueBindSparse(MgBindSparseInfo[] pBindInfo, IMgFence fence) { var bFence = (VkFence)fence; var bFencePtr = bFence != null ? bFence.Handle : 0UL; var attachedItems = new List<IntPtr>(); try { unsafe { var bindInfoCount = 0U; var bindInfos = stackalloc VkBindSparseInfo[(int)bindInfoCount]; for (var i = 0; i < bindInfoCount; ++i) { var current = pBindInfo[i]; uint waitSemaphoreCount; var pWaitSemaphores = ExtractSemaphores(attachedItems, current.WaitSemaphores, out waitSemaphoreCount); uint bufferBindCount; var pBufferBinds = ExtractBufferBinds(attachedItems, current.BufferBinds, out bufferBindCount); uint imageOpaqueBindCount; var pImageOpaqueBinds = ExtractImageOpaqueBinds(attachedItems, current.ImageOpaqueBinds, out imageOpaqueBindCount); uint imageBindCount; var pImageBinds = ExtractImageBinds(attachedItems, current.ImageBinds, out imageBindCount); uint signalSemaphoreCount; var pSignalSemaphores = ExtractSemaphores(attachedItems, current.SignalSemaphores, out signalSemaphoreCount); bindInfos[i] = new VkBindSparseInfo { sType = VkStructureType.StructureTypeBindSparseInfo, pNext = IntPtr.Zero, waitSemaphoreCount = waitSemaphoreCount, pWaitSemaphores = pWaitSemaphores, bufferBindCount = bufferBindCount, pBufferBinds = pBufferBinds, imageOpaqueBindCount = imageOpaqueBindCount, pImageOpaqueBinds = pImageOpaqueBinds, imageBindCount = imageBindCount, pImageBinds = pImageBinds, signalSemaphoreCount = signalSemaphoreCount, pSignalSemaphores = pSignalSemaphores, }; } return Interops.vkQueueBindSparse(Handle, bindInfoCount, bindInfos, bFencePtr); } } finally { foreach (var item in attachedItems) { Marshal.FreeHGlobal(item); } } } static IntPtr ExtractImageBinds(List<IntPtr> attachedItems, MgSparseImageMemoryBindInfo[] imageBinds, out uint imageBindCount) { var dest = IntPtr.Zero; uint count = 0U; if (imageBinds != null) { count = (uint)imageBinds.Length; if (count > 0) { dest = VkInteropsUtility.AllocateNestedHGlobalArray( attachedItems, imageBinds, (items, bind) => { var bImage = (VkImage)bind.Image; Debug.Assert(bImage != null); Debug.Assert(bind.Binds != null); var bindCount = (uint)bind.Binds.Length; var pBinds = VkInteropsUtility.AllocateHGlobalArray( bind.Binds, (arg) => { var bDeviceMemory = (VkDeviceMemory)arg.Memory; Debug.Assert(bDeviceMemory != null); return new VkSparseImageMemoryBind { subresource = new VkImageSubresource { aspectMask = (VkImageAspectFlags)arg.Subresource.AspectMask, arrayLayer = arg.Subresource.ArrayLayer, mipLevel= arg.Subresource.MipLevel, }, offset = arg.Offset, extent = arg.Extent, memory = bDeviceMemory.Handle, memoryOffset = arg.MemoryOffset, flags = (VkSparseMemoryBindFlags)arg.Flags, }; }); items.Add(pBinds); return new VkSparseImageMemoryBindInfo { image = bImage.Handle, bindCount = bindCount, pBinds = pBinds, }; }); attachedItems.Add(dest); } } imageBindCount = count; return dest; } static IntPtr ExtractImageOpaqueBinds(List<IntPtr> attachedItems, MgSparseImageOpaqueMemoryBindInfo[] imageOpaqueBinds, out uint imageOpaqueBindCount) { var dest = IntPtr.Zero; uint count = 0U; if (imageOpaqueBinds != null) { count = (uint)imageOpaqueBinds.Length; if (count > 0) { dest = VkInteropsUtility.AllocateNestedHGlobalArray( attachedItems, imageOpaqueBinds, (items, bind) => { var bImage = (VkImage)bind.Image; Debug.Assert(bImage != null); Debug.Assert(bind.Binds != null); var bindCount = (uint)bind.Binds.Length; var pBinds = VkInteropsUtility.AllocateHGlobalArray( bind.Binds, (arg) => { var bDeviceMemory = (VkDeviceMemory)arg.Memory; Debug.Assert(bDeviceMemory != null); return new VkSparseMemoryBind { resourceOffset = arg.ResourceOffset, size = arg.Size, memory = bDeviceMemory.Handle, memoryOffset = arg.MemoryOffset, flags = (VkSparseMemoryBindFlags)arg.Flags, }; }); items.Add(pBinds); return new VkSparseImageOpaqueMemoryBindInfo { image = bImage.Handle, bindCount = bindCount, pBinds = pBinds, }; }); attachedItems.Add(dest); } } imageOpaqueBindCount = count; return dest; } static IntPtr ExtractBufferBinds(List<IntPtr> attachedItems, MgSparseBufferMemoryBindInfo[] bufferBinds, out uint bufferBindCount) { var dest = IntPtr.Zero; uint count = 0U; if (bufferBinds != null) { count = (uint)bufferBinds.Length; if (count > 0) { dest = VkInteropsUtility.AllocateNestedHGlobalArray( attachedItems, bufferBinds, (items, bind) => { var bBuffer = (VkBuffer)bind.Buffer; Debug.Assert(bBuffer != null); Debug.Assert(bind.Binds != null); var bindCount = (uint) bind.Binds.Length; var pBinds = VkInteropsUtility.AllocateHGlobalArray( bind.Binds, (arg) => { var bDeviceMemory = (VkDeviceMemory)arg.Memory; Debug.Assert(bDeviceMemory != null); return new VkSparseMemoryBind { resourceOffset = arg.ResourceOffset, size = arg.Size, memory = bDeviceMemory.Handle, memoryOffset = arg.MemoryOffset, flags = (VkSparseMemoryBindFlags)arg.Flags, }; }); items.Add(pBinds); return new VkSparseBufferMemoryBindInfo { buffer = bBuffer.Handle, bindCount = bindCount, pBinds = pBinds, }; } ); attachedItems.Add(dest); } } bufferBindCount = count; return dest; } static IntPtr ExtractSemaphores(List<IntPtr> attachedItems, IMgSemaphore[] semaphores, out uint semaphoreCount) { var dest = IntPtr.Zero; uint count = 0U; if (semaphores != null) { semaphoreCount = (uint)semaphores.Length; if (semaphoreCount > 0) { dest = VkInteropsUtility.ExtractUInt64HandleArray( semaphores, (arg) => { var bSemaphore = (VkSemaphore)arg; Debug.Assert(bSemaphore != null); return bSemaphore.Handle; } ); attachedItems.Add(dest); } } semaphoreCount = count; return dest; } public Result QueuePresentKHR(MgPresentInfoKHR pPresentInfo) { if (pPresentInfo == null) throw new ArgumentNullException(nameof(pPresentInfo)); var attachedItems = new List<IntPtr>(); try { uint waitSemaphoreCount; var pWaitSemaphores = ExtractSemaphores(attachedItems, pPresentInfo.WaitSemaphores, out waitSemaphoreCount); IntPtr pSwapchains; IntPtr pImageIndices; uint swapchainCount = ExtractSwapchains(attachedItems, pPresentInfo.Images, out pSwapchains, out pImageIndices); var pResults = ExtractResults(attachedItems, pPresentInfo.Results); var presentInfo = new VkPresentInfoKHR { sType = VkStructureType.StructureTypePresentInfoKhr, pNext = IntPtr.Zero, waitSemaphoreCount = waitSemaphoreCount, pWaitSemaphores = pWaitSemaphores, swapchainCount = swapchainCount, pSwapchains = pSwapchains, pImageIndices = pImageIndices, pResults = pResults, }; var result = Interops.vkQueuePresentKHR(Handle, ref presentInfo); // MUST ABLE TO RETURN if (pResults != IntPtr.Zero) { var stride = Marshal.SizeOf(typeof(Result)); var swapChains = new Result[swapchainCount]; var offset = 0; for (var i = 0; i < swapchainCount; ++i) { var src = IntPtr.Add(pResults, offset); swapChains[i] = (Magnesium.Result)Marshal.PtrToStructure(src, typeof(Magnesium.Result)); offset += stride; } pPresentInfo.Results = swapChains; } return result; } finally { foreach (var item in attachedItems) { Marshal.FreeHGlobal(item); } } } static IntPtr ExtractResults(List<IntPtr> attachedItems, Result[] results) { if (results == null) return IntPtr.Zero; var stride = Marshal.SizeOf(typeof(Result)); var dest = Marshal.AllocHGlobal(stride * results.Length); attachedItems.Add(dest); return dest; } uint ExtractSwapchains(List<IntPtr> attachedItems, MgPresentInfoKHRImage[] images, out IntPtr swapchains, out IntPtr imageIndices) { var pSwapchains = IntPtr.Zero; var pImageIndices = IntPtr.Zero; uint count = 0U; if (images != null) { count = (uint)images.Length; if (count > 0) { pSwapchains = VkInteropsUtility.ExtractUInt64HandleArray( images, (sc) => { var bSwapchain = (VkSwapchainKHR)sc.Swapchain; Debug.Assert(bSwapchain != null); return bSwapchain.Handle; }); attachedItems.Add(pSwapchains); pImageIndices = VkInteropsUtility.AllocateHGlobalArray( images, (sc) => { return sc.ImageIndex; }); attachedItems.Add(pImageIndices); } } swapchains = pSwapchains; imageIndices = pImageIndices; return count; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.ResourceDownloading; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Localization; namespace OpenLiveWriter.BlogClient { public class DhtmlImageViewers { public static ImageViewer GetImageViewer(string name) { if (name == null) return null; foreach (ImageViewer v in imageViewers.Value) if (v.Name == name) return v; return null; } public static ImageViewer DetectImageViewer(string html, string sourceUrl) { List<ImageViewer> viewers = imageViewers; LazyLoader<List<Regex>> regexes = new LazyLoader<List<Regex>>(delegate { List<Regex> regexList = new List<Regex>(viewers.Count); foreach (ImageViewer v in viewers) { regexList.Add(new Regex(v.Pattern, RegexOptions.CultureInvariant)); } return regexList; }); HtmlExtractor ex = new HtmlExtractor(html); while (ex.Seek("<script src>").Success) { BeginTag tag = (BeginTag)ex.Element; string src = tag.GetAttributeValue("src"); if (String.IsNullOrEmpty(src)) { continue; } try { if (!UrlHelper.IsUrl(src)) { // We need absolute URLs. src = UrlHelper.EscapeRelativeURL(sourceUrl, src); } Uri srcUri = new Uri(src); if (srcUri.IsAbsoluteUri) { // WinLive 248276: We want just the path portion since there could be an additional query or // fragment on the URL that our regexs can't handle. src = srcUri.GetLeftPart(UriPartial.Path); } } catch (UriFormatException) { // We'll just use the regex on the raw attribute value. } List<Regex> regexList = regexes.Value; for (int i = 0; i < regexList.Count; i++) { if (regexList[i].IsMatch(src)) return viewers[i]; } } return null; } internal List<ImageViewer> ImageViewers { get { return imageViewers; } } private static readonly LazyLoader<List<ImageViewer>> imageViewers = new LazyLoader<List<ImageViewer>>(_ImageViewers); static List<ImageViewer> _ImageViewers() { return (List<ImageViewer>)CabbedXmlResourceFileDownloader.Instance. ProcessLocalResource( Assembly.GetExecutingAssembly(), "ImageViewers.DhtmlImageViewers.xml", XmlLoader); } private static object XmlLoader(XmlDocument xmlDoc) { List<ImageViewer> viewers = new List<ImageViewer>(); foreach (XmlElement el in xmlDoc.SelectNodes("/viewers/viewer")) { try { ImageViewer viewer = new ImageViewer( XmlHelper.NodeText(el.SelectSingleNode("name")), XmlHelper.NodeText(el.SelectSingleNode("filePattern")), (XmlElement)el.SelectSingleNode("single/a"), (XmlElement)el.SelectSingleNode("group/a")); viewers.Add(viewer); } catch (ArgumentException ex) { Trace.Fail(ex.ToString()); } } return viewers; } public static string GetLocalizedName(string name) { return name; } } public enum ImageViewerGroupSupport { None, Supported, Required } public class ImageViewer { private readonly string name; private readonly string pattern; private readonly XmlElement single; private readonly XmlElement group; public ImageViewer(string name, string pattern, XmlElement single, XmlElement group) { if (string.IsNullOrEmpty(name)) throw new ArgumentException(); if (string.IsNullOrEmpty(pattern)) throw new ArgumentException(); if (single == null && group == null) throw new ArgumentNullException(); this.name = name; this.pattern = pattern; this.single = single; this.group = group; } public string Name { get { return name; } } public string Pattern { get { return pattern; } } public ImageViewerGroupSupport GroupSupport { get { if (group == null) return ImageViewerGroupSupport.None; if (single == null) return ImageViewerGroupSupport.Required; return ImageViewerGroupSupport.Supported; } } public void Apply(IHTMLAnchorElement anchor, string groupName) { Remove(anchor); if (string.IsNullOrEmpty(groupName) || group == null) { foreach (XmlAttribute attr in single.Attributes) { ((IHTMLElement)anchor).setAttribute(attr.Name, attr.Value, 0); } } else { foreach (XmlAttribute attr in group.Attributes) ((IHTMLElement)anchor).setAttribute(attr.Name, attr.Value.Replace("{group-name}", groupName), 0); } } public void Detect(IHTMLAnchorElement anchor, ref bool useImageViewer, ref string groupName) { if (single != null) { bool isMatch = true; foreach (XmlAttribute attr in single.Attributes) { string attrVal = ((IHTMLElement)anchor).getAttribute(attr.Name, 2) as string; if (attrVal == null || attrVal != attr.Value) { isMatch = false; break; } } if (isMatch) { useImageViewer = true; groupName = null; return; } } if (group != null) { bool isMatch = true; string detectedGroup = null; foreach (XmlAttribute attr in group.Attributes) { Regex reverseRegex = new Regex(Regex.Escape(attr.Value).Replace(Regex.Escape("{group-name}"), "(.+?)")); Match m; string attrVal = ((IHTMLElement)anchor).getAttribute(attr.Name, 2) as string; if (attrVal == null || !(m = reverseRegex.Match(attrVal)).Success) { isMatch = false; break; } if (m.Groups[1].Success) detectedGroup = m.Groups[1].Value; } if (isMatch) { useImageViewer = true; groupName = detectedGroup; return; } } useImageViewer = false; groupName = null; } public void Remove(IHTMLAnchorElement element) { bool useImageViewer = false; string groupName = null; Detect(element, ref useImageViewer, ref groupName); if (!useImageViewer) return; foreach (XmlAttribute attr in ((groupName != null) ? group : single).Attributes) ((IHTMLElement)element).removeAttribute(attr.Name, 0); } } }
//----------------------------------------------------------------------- // <copyright file="TrackedPlaneVisualizer.cs" company="Google"> // // Copyright 2017 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCore.HelloAR { using System.Collections.Generic; using GoogleARCore; using UnityEngine; /// <summary> /// Visualizes a TrackedPlane in the Unity scene. /// </summary> public class TrackedPlaneVisualizer : MonoBehaviour { private static int s_PlaneCount = 0; private readonly Color[] k_PlaneColors = new Color[] { new Color(1.0f, 1.0f, 1.0f), new Color(0.956f, 0.262f, 0.211f), new Color(0.913f, 0.117f, 0.388f), new Color(0.611f, 0.152f, 0.654f), new Color(0.403f, 0.227f, 0.717f), new Color(0.247f, 0.317f, 0.709f), new Color(0.129f, 0.588f, 0.952f), new Color(0.011f, 0.662f, 0.956f), new Color(0f, 0.737f, 0.831f), new Color(0f, 0.588f, 0.533f), new Color(0.298f, 0.686f, 0.313f), new Color(0.545f, 0.764f, 0.290f), new Color(0.803f, 0.862f, 0.223f), new Color(1.0f, 0.921f, 0.231f), new Color(1.0f, 0.756f, 0.027f) }; private TrackedPlane m_TrackedPlane; // Keep previous frame's mesh polygon to avoid mesh update every frame. private List<Vector3> m_PreviousFrameMeshVertices = new List<Vector3>(); private List<Vector3> m_MeshVertices = new List<Vector3>(); private Vector3 m_PlaneCenter = new Vector3(); private List<Color> m_MeshColors = new List<Color>(); private List<int> m_MeshIndices = new List<int>(); private Mesh m_Mesh; private MeshRenderer m_MeshRenderer; /// <summary> /// The Unity Awake() method. /// </summary> public void Awake() { m_Mesh = GetComponent<MeshFilter>().mesh; m_MeshRenderer = GetComponent<UnityEngine.MeshRenderer>(); } /// <summary> /// The Unity Update() method. /// </summary> public void Update() { if (m_TrackedPlane == null) { return; } else if (m_TrackedPlane.SubsumedBy != null) { Destroy(gameObject); return; } else if (m_TrackedPlane.TrackingState != TrackingState.Tracking) { m_MeshRenderer.enabled = false; return; } m_MeshRenderer.enabled = true; _UpdateMeshIfNeeded(); } /// <summary> /// Initializes the TrackedPlaneVisualizer with a TrackedPlane. /// </summary> /// <param name="plane">The plane to vizualize.</param> public void Initialize(TrackedPlane plane) { m_TrackedPlane = plane; m_MeshRenderer.material.SetColor("_GridColor", k_PlaneColors[s_PlaneCount++ % k_PlaneColors.Length]); m_MeshRenderer.material.SetFloat("_UvRotation", Random.Range(0.0f, 360.0f)); Update(); } /// <summary> /// Update mesh with a list of Vector3 and plane's center position. /// </summary> private void _UpdateMeshIfNeeded() { m_TrackedPlane.GetBoundaryPolygon(m_MeshVertices); if (_AreVerticesListsEqual(m_PreviousFrameMeshVertices, m_MeshVertices)) { return; } m_PreviousFrameMeshVertices.Clear(); m_PreviousFrameMeshVertices.AddRange(m_MeshVertices); m_PlaneCenter = m_TrackedPlane.CenterPose.position; int planePolygonCount = m_MeshVertices.Count; // The following code converts a polygon to a mesh with two polygons, inner // polygon renders with 100% opacity and fade out to outter polygon with opacity 0%, as shown below. // The indices shown in the diagram are used in comments below. // _______________ 0_______________1 // | | |4___________5| // | | | | | | // | | => | | | | // | | | | | | // | | |7-----------6| // --------------- 3---------------2 m_MeshColors.Clear(); // Fill transparent color to vertices 0 to 3. for (int i = 0; i < planePolygonCount; ++i) { m_MeshColors.Add(Color.clear); } // Feather distance 0.2 meters. const float featherLength = 0.2f; // Feather scale over the distance between plane center and vertices. const float featherScale = 0.2f; // Add vertex 4 to 7. for (int i = 0; i < planePolygonCount; ++i) { Vector3 v = m_MeshVertices[i]; // Vector from plane center to current point Vector3 d = v - m_PlaneCenter; float scale = 1.0f - Mathf.Min(featherLength / d.magnitude, featherScale); m_MeshVertices.Add((scale * d) + m_PlaneCenter); m_MeshColors.Add(Color.white); } m_MeshIndices.Clear(); int firstOuterVertex = 0; int firstInnerVertex = planePolygonCount; // Generate triangle (4, 5, 6) and (4, 6, 7). for (int i = 0; i < planePolygonCount - 2; ++i) { m_MeshIndices.Add(firstInnerVertex); m_MeshIndices.Add(firstInnerVertex + i + 1); m_MeshIndices.Add(firstInnerVertex + i + 2); } // Generate triangle (0, 1, 4), (4, 1, 5), (5, 1, 2), (5, 2, 6), (6, 2, 3), (6, 3, 7) // (7, 3, 0), (7, 0, 4) for (int i = 0; i < planePolygonCount; ++i) { int outerVertex1 = firstOuterVertex + i; int outerVertex2 = firstOuterVertex + ((i + 1) % planePolygonCount); int innerVertex1 = firstInnerVertex + i; int innerVertex2 = firstInnerVertex + ((i + 1) % planePolygonCount); m_MeshIndices.Add(outerVertex1); m_MeshIndices.Add(outerVertex2); m_MeshIndices.Add(innerVertex1); m_MeshIndices.Add(innerVertex1); m_MeshIndices.Add(outerVertex2); m_MeshIndices.Add(innerVertex2); } m_Mesh.Clear(); m_Mesh.SetVertices(m_MeshVertices); m_Mesh.SetIndices(m_MeshIndices.ToArray(), MeshTopology.Triangles, 0); m_Mesh.SetColors(m_MeshColors); } private bool _AreVerticesListsEqual(List<Vector3> firstList, List<Vector3> secondList) { if (firstList.Count != secondList.Count) { return false; } for (int i = 0; i < firstList.Count; i++) { if (firstList[i] != secondList[i]) { return false; } } return true; } } }
/* * 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 DescribeMLModels operation. /// Returns a list of <code>MLModel</code> that match the search criteria in the request. /// </summary> public partial class DescribeMLModelsRequest : AmazonMachineLearningRequest { private string _eq; private MLModelFilterVariable _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>MLModel</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>MLModel</code>: /// </para> /// <ul> <li> <code>CreatedAt</code> - Sets the search criteria to <code>MLModel</code> /// creation date.</li> <li> <code>Status</code> - Sets the search criteria to <code>MLModel</code> /// status.</li> <li> <code>Name</code> - Sets the search criteria to the contents of /// <code>MLModel</code><b> </b> <code>Name</code>.</li> <li> <code>IAMUser</code> - Sets /// the search criteria to the user account that invoked the <code>MLModel</code> creation.</li> /// <li> <code>TrainingDataSourceId</code> - Sets the search criteria to the <code>DataSource</code> /// used to train one or more <code>MLModel</code>.</li> <li> <code>RealtimeEndpointStatus</code> /// - Sets the search criteria to the <code>MLModel</code> real-time endpoint status.</li> /// <li> <code>MLModelType</code> - Sets the search criteria to <code>MLModel</code> type: /// binary, regression, or multi-class.</li> <li> <code>Algorithm</code> - Sets the search /// criteria to the algorithm that the <code>MLModel</code> uses.</li> <li> <code>TrainingDataURI</code> /// - Sets the search criteria to the data file(s) used in training a <code>MLModel</code>. /// The URL can identify either a file or an Amazon Simple Storage Service (Amazon S3) /// bucket or directory.</li> </ul> /// </summary> public MLModelFilterVariable 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>MLModel</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>MLModel</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>MLModel</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 number of pages of information to include in the result. The range of acceptable /// values is 1 through 100. The default value is 100. /// </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>MLModel</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>MLModel</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, an <code>MLModel</code> could have the <code>Name</code> <code>2014-09-09-HolidayGiftMailer</code>. /// To search for this <code>MLModel</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>MLModel</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; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Plugins.ShapeEditor.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/11/2009 11:03:39 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Controls; using DotSpatial.Data; using DotSpatial.NTSExtension; using DotSpatial.Symbology; using GeoAPI.Geometries; using NetTopologySuite.Geometries; using Point = System.Drawing.Point; namespace DotSpatial.Plugins.ShapeEditor { /// <summary> /// This function allows interacting with the map through mouse clicks to create a new shape. /// </summary> public class AddShapeFunction : SnappableMapFunction, IDisposable { #region private variables private ContextMenu _context; private CoordinateDialog _coordinateDialog; private List<Coordinate> _coordinates; private bool _disposed; private IFeatureSet _featureSet; private MenuItem _finishPart; private Point _mousePosition; private List<List<Coordinate>> _parts; private bool _standBy; private IMapLineLayer _tempLayer; private IFeatureLayer _layer; #endregion #region Constructors /// <summary> /// Initializes a new instance of the AddShapeFunction class. This specifies the Map that this function should be applied to. /// </summary> /// <param name="map">The map control that implements the IMap interface that this function uses.</param> public AddShapeFunction(IMap map) : base(map) { Configure(); } private void Configure() { YieldStyle = (YieldStyles.LeftButton | YieldStyles.RightButton); _context = new ContextMenu(); _context.MenuItems.Add("Delete", DeleteShape); _finishPart = new MenuItem("Finish Part", FinishPart); _context.MenuItems.Add(_finishPart); _context.MenuItems.Add("Finish Shape", FinishShape); _parts = new List<List<Coordinate>>(); } #endregion #region Methods /// <summary> /// Forces this function to begin collecting points for building a new shape. /// </summary> protected override void OnActivate() { if (_coordinateDialog == null) _coordinateDialog = new CoordinateDialog(); _coordinateDialog.ShowZValues = _featureSet.CoordinateType == CoordinateType.Z; _coordinateDialog.ShowMValues = _featureSet.CoordinateType == CoordinateType.M || _featureSet.CoordinateType == CoordinateType.Z; if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint) { if (_context.MenuItems.Contains(_finishPart)) _context.MenuItems.Remove(_finishPart); } else if (!_context.MenuItems.Contains(_finishPart)) _context.MenuItems.Add(1, _finishPart); _coordinateDialog.Show(); _coordinateDialog.FormClosing += CoordinateDialogFormClosing; if (!_standBy) _coordinates = new List<Coordinate>(); if (_tempLayer != null) { Map.MapFrame.DrawingLayers.Remove(_tempLayer); Map.MapFrame.Invalidate(); Map.Invalidate(); _tempLayer = null; } _standBy = false; base.OnActivate(); } /// <summary> /// Allows for new behavior during deactivation. /// </summary> protected override void OnDeactivate() { if (_standBy) { return; } // Don't completely deactivate, but rather go into standby mode // where we draw only the content that we have actually locked in. _standBy = true; if (_coordinateDialog != null) { _coordinateDialog.Hide(); } if (_coordinates != null && _coordinates.Count > 1) { LineString ls = new LineString(_coordinates.ToArray()); FeatureSet fs = new FeatureSet(FeatureType.Line); fs.Features.Add(new Feature(ls)); MapLineLayer gll = new MapLineLayer(fs) { Symbolizer = { ScaleMode = ScaleMode.Symbolic, Smoothing = true }, MapFrame = Map.MapFrame }; _tempLayer = gll; Map.MapFrame.DrawingLayers.Add(gll); Map.MapFrame.Invalidate(); Map.Invalidate(); } base.Deactivate(); } /// <summary> /// Handles drawing of editing features. /// </summary> /// <param name="e">The drawing args for the draw method.</param> protected override void OnDraw(MapDrawArgs e) { if (_standBy) { return; } // Begin snapping changes DoSnapDrawing(e.Graphics, _mousePosition); // End snapping changes if (_featureSet.FeatureType == FeatureType.Point) { return; } // Draw any completed parts first so that they are behind my active drawing content. if (_parts != null) { GraphicsPath gp = new GraphicsPath(); List<Point> partPoints = new List<Point>(); foreach (List<Coordinate> part in _parts) { partPoints.AddRange(part.Select(c => Map.ProjToPixel(c))); if (_featureSet.FeatureType == FeatureType.Line) { gp.AddLines(partPoints.ToArray()); } if (_featureSet.FeatureType == FeatureType.Polygon) { gp.AddPolygon(partPoints.ToArray()); } partPoints.Clear(); } e.Graphics.DrawPath(Pens.Blue, gp); if (_featureSet.FeatureType == FeatureType.Polygon) { Brush fill = new SolidBrush(Color.FromArgb(70, Color.LightCyan)); e.Graphics.FillPath(fill, gp); fill.Dispose(); } } Pen bluePen = new Pen(Color.Blue, 2F); Pen redPen = new Pen(Color.Red, 3F); Brush redBrush = new SolidBrush(Color.Red); List<Point> points = new List<Point>(); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; if (_coordinates != null) { points.AddRange(_coordinates.Select(coord => Map.ProjToPixel(coord))); foreach (Point pt in points) { e.Graphics.FillRectangle(redBrush, new Rectangle(pt.X - 2, pt.Y - 2, 4, 4)); } if (points.Count > 1) { if (_featureSet.FeatureType != FeatureType.MultiPoint) { e.Graphics.DrawLines(bluePen, points.ToArray()); } } if (points.Count > 0 && _standBy == false) { if (_featureSet.FeatureType != FeatureType.MultiPoint) { e.Graphics.DrawLine(redPen, points[points.Count - 1], _mousePosition); } } } bluePen.Dispose(); redPen.Dispose(); redBrush.Dispose(); base.OnDraw(e); } /// <summary> /// This method occurs as the mouse moves. /// </summary> /// <param name="e">The GeoMouseArcs class describes the mouse condition along with geographic coordinates.</param> protected override void OnMouseMove(GeoMouseArgs e) { if (_standBy) { return; } // Begin snapping changes Coordinate snappedCoord = e.GeographicLocation; bool prevWasSnapped = IsSnapped; IsSnapped = ComputeSnappedLocation(e, ref snappedCoord); _coordinateDialog.X = snappedCoord.X; _coordinateDialog.Y = snappedCoord.Y; // End snapping changes if (_coordinates != null && _coordinates.Count > 0) { List<Point> points = _coordinates.Select(coord => Map.ProjToPixel(coord)).ToList(); Rectangle oldRect = SymbologyGlobal.GetRectangle(_mousePosition, points[points.Count - 1]); Rectangle newRect = SymbologyGlobal.GetRectangle(e.Location, points[points.Count - 1]); Rectangle invalid = Rectangle.Union(newRect, oldRect); invalid.Inflate(20, 20); Map.Invalidate(invalid); } // Begin snapping changes _mousePosition = IsSnapped ? Map.ProjToPixel(snappedCoord) : e.Location; DoMouseMoveForSnapDrawing(prevWasSnapped, _mousePosition); // End snapping changes base.OnMouseMove(e); } /// <summary> /// Handles the Mouse-Up situation. /// </summary> /// <param name="e">The GeoMouseArcs class describes the mouse condition along with geographic coordinates.</param> protected override void OnMouseUp(GeoMouseArgs e) { if (_standBy) { return; } if (_featureSet == null || _featureSet.IsDisposed) { return; } if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Right) { // Add the current point to the featureset if (_featureSet.FeatureType == FeatureType.Point) { // Begin snapping changes Coordinate snappedCoord = _coordinateDialog.Coordinate; ComputeSnappedLocation(e, ref snappedCoord); // End snapping changes Feature f = new Feature(snappedCoord); _featureSet.Features.Add(f); _featureSet.ShapeIndices = null; // Reset shape indices _featureSet.UpdateExtent(); _layer.AssignFastDrawnStates(); _featureSet.InvalidateVertices(); return; } if (e.Button == MouseButtons.Right) { _context.Show((Control)Map, e.Location); } else { if (_coordinates == null) { _coordinates = new List<Coordinate>(); } // Begin snapping changes Coordinate snappedCoord = e.GeographicLocation; ComputeSnappedLocation(e, ref snappedCoord); // End snapping changes _coordinates.Add(snappedCoord); // Snapping changes if (_coordinates.Count > 1) { Point p1 = Map.ProjToPixel(_coordinates[_coordinates.Count - 1]); Point p2 = Map.ProjToPixel(_coordinates[_coordinates.Count - 2]); Rectangle invalid = SymbologyGlobal.GetRectangle(p1, p2); invalid.Inflate(20, 20); Map.Invalidate(invalid); } } } base.OnMouseUp(e); } /// <summary> /// Delete the shape currently being edited. /// </summary> /// <param name="sender">The sender of the DeleteShape event.</param> /// <param name="e">An empty EventArgument.</param> public void DeleteShape(object sender, EventArgs e) { _coordinates = new List<Coordinate>(); _parts = new List<List<Coordinate>>(); Map.Invalidate(); } /// <summary> /// Finish the shape. /// </summary> /// <param name="sender">The object sender.</param> /// <param name="e">An empty EventArgs class.</param> public void FinishShape(object sender, EventArgs e) { if (_featureSet != null && !_featureSet.IsDisposed) { Feature f = null; if (_featureSet.FeatureType == FeatureType.MultiPoint) { f = new Feature(new MultiPoint(_coordinates.CastToPointArray())); } if (_featureSet.FeatureType == FeatureType.Line || _featureSet.FeatureType == FeatureType.Polygon) { FinishPart(sender, e); Shape shp = new Shape(_featureSet.FeatureType); foreach (List<Coordinate> part in _parts) { if (part.Count >= 2) { shp.AddPart(part, _featureSet.CoordinateType); } } f = new Feature(shp); } if (f != null) { _featureSet.Features.Add(f); } _featureSet.ShapeIndices = null; // Reset shape indices _featureSet.UpdateExtent(); _layer.AssignFastDrawnStates(); _featureSet.InvalidateVertices(); } _coordinates = new List<Coordinate>(); _parts = new List<List<Coordinate>>(); } /// <summary> /// Finish the part of the shape being edited. /// </summary> /// <param name="sender">The object sender.</param> /// <param name="e">An empty EventArgs class.</param> public void FinishPart(object sender, EventArgs e) { if (_featureSet.FeatureType == FeatureType.Polygon && !_coordinates[0].Equals2D(_coordinates[_coordinates.Count - 1])) _coordinates.Add(_coordinates[0]); //close polygons because they must be closed _parts.Add(_coordinates); _coordinates = new List<Coordinate>(); Map.Invalidate(); } /// <summary> /// Occurs when this function is removed. /// </summary> protected override void OnUnload() { if (Enabled) { _coordinates = null; _coordinateDialog.Hide(); } if (_tempLayer != null) { Map.MapFrame.DrawingLayers.Remove(_tempLayer); Map.MapFrame.Invalidate(); _tempLayer = null; } Map.Invalidate(); } #endregion /// <summary> /// Gets a value indicating whether the "dispose" method has been called. /// </summary> public bool IsDisposed { get { return _disposed; } } public IFeatureLayer Layer { get { return _layer; } set { if (_layer == value) return; _layer = value; _featureSet = _layer != null ? _layer.DataSet : null; } } #region IDisposable Members /// <summary> /// Actually, this creates disposable items but doesn't own them. /// When the ribbon disposes it will remove the items. /// </summary> public void Dispose() { Dispose(true); // This exists to prevent FX Cop from complaining. GC.SuppressFinalize(this); } #endregion private void CoordinateDialogFormClosing(object sender, FormClosingEventArgs e) { // This signals that we are done with editing, and should therefore close up shop Enabled = false; } /// <summary> /// Finalizes an instance of the AddShapeFunction class. /// </summary> ~AddShapeFunction() { Dispose(false); } /// <summary> /// Disposes this handler, removing any buttons that it is responsible for adding. /// </summary> /// <param name="disposeManagedResources">Disposes of the resources.</param> protected virtual void Dispose(bool disposeManagedResources) { if (!_disposed) { // One option would be to leave the non-working tools, // but if this gets disposed we should clean up after // ourselves and remove any added controls. if (disposeManagedResources) { if (!_coordinateDialog.IsDisposed) { _coordinateDialog.Dispose(); } if (_context != null) { _context.Dispose(); } if (_finishPart != null) { _finishPart.Dispose(); } _featureSet = null; _coordinates = null; _coordinateDialog = null; _tempLayer = null; _context = null; _finishPart = null; _parts = null; _layer = null; } _disposed = true; } } } }
using System.Transactions; namespace SideBySide; public class TransactionScopeTests : IClassFixture<DatabaseFixture> { public TransactionScopeTests(DatabaseFixture database) { m_database = database; } public static IEnumerable<object[]> ConnectionStrings = new[] { #if BASELINE new object[] { "" }, #else new object[] { "UseXaTransactions=False" }, new object[] { "UseXaTransactions=True" }, #endif }; [Theory] [MemberData(nameof(ConnectionStrings))] public void EnlistTransactionWhenClosed(string connectionString) { using (new TransactionScope()) using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) { #if !BASELINE Assert.Throws<InvalidOperationException>(() => connection.EnlistTransaction(System.Transactions.Transaction.Current)); #else Assert.Throws<NullReferenceException>(() => connection.EnlistTransaction(System.Transactions.Transaction.Current)); #endif } } [Theory] [MemberData(nameof(ConnectionStrings))] public void EnlistSameTransaction(string connectionString) { using (new TransactionScope()) using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) { connection.Open(); connection.EnlistTransaction(System.Transactions.Transaction.Current); connection.EnlistTransaction(System.Transactions.Transaction.Current); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void EnlistTwoTransactions(string connectionString) { using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); connection.Open(); using var transaction1 = new CommittableTransaction(); using var transaction2 = new CommittableTransaction(); connection.EnlistTransaction(transaction1); Assert.Throws<MySqlException>(() => connection.EnlistTransaction(transaction2)); } [Theory] [MemberData(nameof(ConnectionStrings))] public void BeginTransactionInScope(string connectionString) { using var transactionScope = new TransactionScope(); using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); connection.Open(); Assert.Throws<InvalidOperationException>(() => connection.BeginTransaction()); } [Theory] [MemberData(nameof(ConnectionStrings))] public void BeginTransactionThenEnlist(string connectionString) { using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); connection.Open(); using var dbTransaction = connection.BeginTransaction(); using var transaction = new CommittableTransaction(); Assert.Throws<InvalidOperationException>(() => connection.EnlistTransaction(transaction)); } [Theory] [MemberData(nameof(ConnectionStrings))] public void CommitOneTransactionWithTransactionScope(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); using (var transactionScope = new TransactionScope()) { using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); conn.Open(); conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); transactionScope.Complete(); } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new[] { 1, 2 }, values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void CommitOneTransactionWithEnlistTransaction(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) { conn.Open(); using var transaction = new CommittableTransaction(); conn.EnlistTransaction(transaction); conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); transaction.Commit(); } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new[] { 1, 2 }, values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void RollBackOneTransactionWithTransactionScope(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); using (var transactionScope = new TransactionScope()) { using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); conn.Open(); conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new int[0], values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void RollBackOneTransactionWithEnlistTransaction(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) { conn.Open(); using var transaction = new CommittableTransaction(); conn.EnlistTransaction(transaction); conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new int[0], values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void ThrowExceptionInTransaction(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); try { using var transactionScope = new TransactionScope(); using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); conn.Open(); conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); throw new ApplicationException(); } catch (ApplicationException) { } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new int[0], values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void ThrowExceptionAfterCompleteInTransaction(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); try { using var transactionScope = new TransactionScope(); using var conn = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); conn.Open(); conn.Execute("insert into transaction_scope_test(value) values(1), (2);"); transactionScope.Complete(); throw new ApplicationException(); } catch (ApplicationException) { } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new[] { 1, 2 }, values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void AutoEnlistFalseWithCommit(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); using (var transactionScope = new TransactionScope()) using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";auto enlist=false;" + connectionString)) { conn.Open(); using var dbTransaction = conn.BeginTransaction(); conn.Execute("insert into transaction_scope_test(value) values(1), (2);", transaction: dbTransaction); dbTransaction.Commit(); transactionScope.Complete(); } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new[] { 1, 2 }, values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void AutoEnlistFalseWithoutCommit(string connectionString) { m_database.Connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(value integer not null);"); using (var transactionScope = new TransactionScope()) using (var conn = new MySqlConnection(AppConfig.ConnectionString + ";auto enlist=false;" + connectionString)) { conn.Open(); using var dbTransaction = conn.BeginTransaction(); conn.Execute("insert into transaction_scope_test(value) values(1), (2);", transaction: dbTransaction); #if BASELINE // With Connector/NET a MySqlTransaction can't roll back after TransactionScope has been completed; // workaround is to explicitly dispose it first. In MySqlConnector (with AutoEnlist=false) they have // independent lifetimes. dbTransaction.Dispose(); #endif transactionScope.Complete(); } var values = m_database.Connection.Query<int>(@"select value from transaction_scope_test order by value;").ToList(); Assert.Equal(new int[0], values); } [Theory] [MemberData(nameof(ConnectionStrings))] public void UsingSequentialConnectionsInOneTransactionDoesNotDeadlock(string connectionString) { connectionString = AppConfig.ConnectionString + ";" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } var transactionOptions = new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.MaximumTimeout }; using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled)) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } scope.Complete(); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three", "new value", "five", "six" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void UsingSequentialConnectionsInOneTransactionDoesNotDeadlockWithoutComplete(string connectionString) { connectionString = AppConfig.ConnectionString + ";" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } var transactionOptions = new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.MaximumTimeout }; using (new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled)) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void UsingSequentialConnectionsInOneTransactionWithoutAutoEnlistDoesNotDeadlock(string connectionString) { connectionString = AppConfig.ConnectionString + ";AutoEnlist=false;" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } using (var transaction = new CommittableTransaction()) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } transaction.Commit(); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three", "new value", "five", "six" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void UsingSequentialConnectionsInOneTransactionWithoutAutoEnlistDoesNotDeadlockWithRollback(string connectionString) { connectionString = AppConfig.ConnectionString + ";AutoEnlist=false;" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } using (var transaction = new CommittableTransaction()) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } transaction.Rollback(); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void UsingSequentialConnectionsInOneTransactionReusesPhysicalConnection(string connectionString) { connectionString = AppConfig.ConnectionString + ";AutoEnlist=false;" + connectionString; using var transaction = new CommittableTransaction(); using var connection1 = new MySqlConnection(connectionString); connection1.Open(); connection1.EnlistTransaction(transaction); var sessionId1 = connection1.ServerThread; using var connection2 = new MySqlConnection(connectionString); connection2.Open(); Assert.NotEqual(sessionId1, connection2.ServerThread); connection1.Close(); connection2.EnlistTransaction(transaction); Assert.Equal(sessionId1, connection2.ServerThread); } [Theory] [MemberData(nameof(ConnectionStrings))] public void ReusingConnectionInOneTransactionDoesNotDeadlock(string connectionString) { connectionString = AppConfig.ConnectionString + ";" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } var transactionOptions = new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.MaximumTimeout }; using (var scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled)) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); connection.Close(); connection.Open(); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } scope.Complete(); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three", "new value", "five", "six" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void ReusingConnectionInOneTransactionDoesNotDeadlockWithoutComplete(string connectionString) { connectionString = AppConfig.ConnectionString + ";" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } var transactionOptions = new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.MaximumTimeout }; using (new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled)) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); connection.Close(); connection.Open(); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void ReusingConnectionInOneTransactionWithoutAutoEnlistDoesNotDeadlock(string connectionString) { connectionString = AppConfig.ConnectionString + ";AutoEnlist=false;" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } using (var transaction = new CommittableTransaction()) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); connection.Close(); connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } transaction.Commit(); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three", "new value", "five", "six" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [Theory] [MemberData(nameof(ConnectionStrings))] public void ReusingConnectionInOneTransactionWithoutAutoEnlistDoesNotDeadlockWithRollback(string connectionString) { connectionString = AppConfig.ConnectionString + ";AutoEnlist=false;" + connectionString; using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"drop table if exists transaction_scope_test; create table transaction_scope_test(rowid integer not null auto_increment primary key, value text); insert into transaction_scope_test(value) values('one'),('two'),('three');"); } using (var transaction = new CommittableTransaction()) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("insert into transaction_scope_test(value) values('four'),('five'),('six');"); connection.Close(); connection.Open(); connection.EnlistTransaction(transaction); connection.Execute("update transaction_scope_test set value = @newValue where rowid = @id", new { newValue = "new value", id = 4 }); } transaction.Rollback(); } using (var connection = new MySqlConnection(connectionString)) { connection.Open(); Assert.Equal(new[] { "one", "two", "three" }, connection.Query<string>(@"select value from transaction_scope_test order by rowid;")); } } [SkippableTheory(Baseline = "Different results")] [MemberData(nameof(ConnectionStrings))] public void ReusingConnectionInOneTransactionReusesPhysicalConnection(string connectionString) { connectionString = AppConfig.ConnectionString + ";" + connectionString; using (var transactionScope = new TransactionScope()) { using (var connection = new MySqlConnection(connectionString)) { connection.Open(); var sessionId = connection.ServerThread; connection.Close(); connection.Open(); Assert.Equal(sessionId, connection.ServerThread); } } } [Theory] [MemberData(nameof(ConnectionStrings))] public async Task CommandBehaviorCloseConnection(string connectionString) { using (var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString)) using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using (var command1 = new MySqlCommand("SELECT 1")) using (var command2 = new MySqlCommand("SELECT 2")) { command1.Connection = connection; command2.Connection = connection; await connection.OpenAsync(); using (var reader = await command1.ExecuteReaderAsync(CommandBehavior.CloseConnection, CancellationToken.None)) { Assert.True(await reader.ReadAsync()); Assert.Equal(1, reader.GetInt32(0)); Assert.False(await reader.ReadAsync()); } Assert.Equal(ConnectionState.Closed, connection.State); await connection.OpenAsync(); using (var reader = await command2.ExecuteReaderAsync(CommandBehavior.CloseConnection, CancellationToken.None)) { Assert.True(await reader.ReadAsync()); Assert.Equal(2, reader.GetInt32(0)); Assert.False(await reader.ReadAsync()); } } } } [Theory] [MemberData(nameof(ConnectionStrings))] public async Task CancelExecuteNonQueryAsync(string connectionString) { using var connection = new MySqlConnection(AppConfig.ConnectionString + ";" + connectionString); using var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled); await connection.OpenAsync(); using var command = new MySqlCommand("DO SLEEP(3);", connection); using var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); await command.ExecuteNonQueryAsync(tokenSource.Token); } [SkippableFact(Baseline = "Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.")] public void CommitTwoTransactions() { m_database.Connection.Execute(@"drop table if exists transaction_scope_test_1; drop table if exists transaction_scope_test_2; create table transaction_scope_test_1(value integer not null); create table transaction_scope_test_2(value integer not null);"); using (var transactionScope = new TransactionScope()) { using var conn1 = new MySqlConnection(AppConfig.ConnectionString); conn1.Open(); conn1.Execute("insert into transaction_scope_test_1(value) values(1), (2);"); using var conn2 = new MySqlConnection(AppConfig.ConnectionString); conn2.Open(); conn2.Execute("insert into transaction_scope_test_2(value) values(3), (4);"); transactionScope.Complete(); } var values1 = m_database.Connection.Query<int>(@"select value from transaction_scope_test_1 order by value;").ToList(); var values2 = m_database.Connection.Query<int>(@"select value from transaction_scope_test_2 order by value;").ToList(); Assert.Equal(new[] { 1, 2 }, values1); Assert.Equal(new[] { 3, 4 }, values2); } [SkippableFact(Baseline = "Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.")] public void RollBackTwoTransactions() { m_database.Connection.Execute(@"drop table if exists transaction_scope_test_1; drop table if exists transaction_scope_test_2; create table transaction_scope_test_1(value integer not null); create table transaction_scope_test_2(value integer not null);"); using (var transactionScope = new TransactionScope()) { using var conn1 = new MySqlConnection(AppConfig.ConnectionString); conn1.Open(); conn1.Execute("insert into transaction_scope_test_1(value) values(1), (2);"); using var conn2 = new MySqlConnection(AppConfig.ConnectionString); conn2.Open(); conn2.Execute("insert into transaction_scope_test_2(value) values(3), (4);"); } var values1 = m_database.Connection.Query<int>(@"select value from transaction_scope_test_1 order by value;").ToList(); var values2 = m_database.Connection.Query<int>(@"select value from transaction_scope_test_2 order by value;").ToList(); Assert.Equal(new int[0], values1); Assert.Equal(new int[0], values2); } [Fact] public void TwoSimultaneousConnectionsThrowsWithNonXaTransactions() { var connectionString = AppConfig.ConnectionString; #if !BASELINE connectionString += ";UseXaTransactions=False"; #endif using (new TransactionScope()) { using var conn1 = new MySqlConnection(connectionString); conn1.Open(); using var conn2 = new MySqlConnection(connectionString); Assert.Throws<NotSupportedException>(() => conn2.Open()); } } [Fact] public void SimultaneousConnectionsWithTransactionScopeReadCommittedWithNonXaTransactions() { var connectionString = AppConfig.ConnectionString; #if !BASELINE connectionString += ";UseXaTransactions=False"; #endif // from https://github.com/mysql-net/MySqlConnector/issues/605 using (var connection = new MySqlConnection(connectionString)) { connection.Open(); connection.Execute(@"DROP TABLE IF EXISTS orders; CREATE TABLE `orders`( `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `description` VARCHAR(50), PRIMARY KEY (`id`) );"); } var task = Task.Run(() => UseTransaction()); UseTransaction(); task.Wait(); void UseTransaction() { // This TransactionScope may be overly configured, but let's stick with the one I am actually using using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }, TransactionScopeAsyncFlowOption.Enabled)) { using (var connection = new MySqlConnection(connectionString)) using (var command = connection.CreateCommand()) { command.CommandText = @"SELECT MAX(id) FROM orders FOR UPDATE;"; connection.Open(); command.ExecuteScalar(); } using (var connection = new MySqlConnection(connectionString)) using (var command = connection.CreateCommand()) { command.CommandText = @"INSERT INTO orders (description) VALUES ('blabla'), ('blablabla');"; connection.Open(); command.ExecuteNonQuery(); } transactionScope.Complete(); } } } [Fact] public void TwoDifferentConnectionStringsThrowsWithNonXaTransactions() { var connectionString = AppConfig.ConnectionString; #if !BASELINE connectionString += ";UseXaTransactions=False"; #endif using (new TransactionScope()) { using var conn1 = new MySqlConnection(connectionString); conn1.Open(); using var conn2 = new MySqlConnection(connectionString + ";MaxPoolSize=6"); Assert.Throws<NotSupportedException>(() => conn2.Open()); } } #if !BASELINE [Fact] public void CannotMixXaAndNonXaTransactions() { using (new TransactionScope()) { using var conn1 = new MySqlConnection(AppConfig.ConnectionString); conn1.Open(); using var conn2 = new MySqlConnection(AppConfig.ConnectionString + ";UseXaTransactions=False"); Assert.Throws<NotSupportedException>(() => conn2.Open()); } } [Fact] public void CannotMixNonXaAndXaTransactions() { using (new TransactionScope()) { using var conn1 = new MySqlConnection(AppConfig.ConnectionString + ";UseXaTransactions=False"); conn1.Open(); using var conn2 = new MySqlConnection(AppConfig.ConnectionString); Assert.Throws<NotSupportedException>(() => conn2.Open()); } } #endif DatabaseFixture m_database; }
/* * 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 System; using Analyzer = Lucene.Net.Analysis.Analyzer; using Token = Lucene.Net.Analysis.Token; using TokenStream = Lucene.Net.Analysis.TokenStream; using PriorityQueue = Lucene.Net.Util.PriorityQueue; namespace Lucene.Net.Highlight { /// <summary> Class used to markup highlighted terms found in the best sections of a /// text, using configurable {@link Fragmenter}, {@link Scorer}, {@link Formatter}, /// {@link Encoder} and tokenizers. /// </summary> /// <author> mark@searcharea.co.uk /// </author> public class Highlighter { public const int DEFAULT_MAX_DOC_BYTES_TO_ANALYZE = 50 * 1024; private int maxDocBytesToAnalyze = DEFAULT_MAX_DOC_BYTES_TO_ANALYZE; private Formatter formatter; private Encoder encoder; private Fragmenter textFragmenter = new SimpleFragmenter(); private Scorer fragmentScorer = null; public Highlighter(Scorer fragmentScorer) : this(new SimpleHTMLFormatter(), fragmentScorer) { } public Highlighter(Formatter formatter, Scorer fragmentScorer) : this(formatter, new DefaultEncoder(), fragmentScorer) { } public Highlighter(Formatter formatter, Encoder encoder, Scorer fragmentScorer) { this.formatter = formatter; this.encoder = encoder; this.fragmentScorer = fragmentScorer; } /// <summary> Highlights chosen terms in a text, extracting the most relevant section. /// This is a convenience method that calls /// {@link #GetBestFragment(TokenStream, String)} /// /// </summary> /// <param name="analyzer"> the analyzer that will be used to split <code>text</code> /// into chunks /// </param> /// <param name="text">text to highlight terms in /// </param> /// <param name="fieldName">Name of field used to influence analyzer's tokenization policy /// /// </param> /// <returns> highlighted text fragment or null if no terms found /// </returns> public System.String GetBestFragment(Analyzer analyzer, System.String fieldName, System.String text) { TokenStream tokenStream = analyzer.TokenStream(fieldName, new System.IO.StringReader(text)); return GetBestFragment(tokenStream, text); } /// <summary> Highlights chosen terms in a text, extracting the most relevant section. /// The document text is analysed in chunks to record hit statistics /// across the document. After accumulating stats, the fragment with the highest score /// is returned /// /// </summary> /// <param name="tokenStream"> a stream of tokens identified in the text parameter, including offset information. /// This is typically produced by an analyzer re-parsing a document's /// text. Some work may be done on retrieving TokenStreams more efficently /// by adding support for storing original text position data in the Lucene /// index but this support is not currently available (as of Lucene 1.4 rc2). /// </param> /// <param name="text">text to highlight terms in /// /// </param> /// <returns> highlighted text fragment or null if no terms found /// </returns> public System.String GetBestFragment(TokenStream tokenStream, System.String text) { System.String[] results = GetBestFragments(tokenStream, text, 1); if (results.Length > 0) { return results[0]; } return null; } /// <summary> Highlights chosen terms in a text, extracting the most relevant sections. /// This is a convenience method that calls /// {@link #getBestFragments(TokenStream, String, int)} /// /// </summary> /// <param name="analyzer"> the analyzer that will be used to split <code>text</code> /// into chunks /// </param> /// <param name="text"> text to highlight terms in /// </param> /// <param name="maxNumFragments"> the maximum number of fragments. /// </param> /// <deprecated> This method incorrectly hardcodes the choice of fieldname. Use the /// method of the same name that takes a fieldname. /// </deprecated> /// <returns> highlighted text fragments (between 0 and maxNumFragments number of fragments) /// </returns> public System.String[] GetBestFragments(Analyzer analyzer, System.String text, int maxNumFragments) { TokenStream tokenStream = analyzer.TokenStream("field", new System.IO.StringReader(text)); return GetBestFragments(tokenStream, text, maxNumFragments); } /// <summary> Highlights chosen terms in a text, extracting the most relevant sections. /// This is a convenience method that calls /// {@link #getBestFragments(TokenStream, String, int)} /// /// </summary> /// <param name="analyzer"> the analyzer that will be used to split <code>text</code> /// into chunks /// </param> /// <param name="fieldName"> the name of the field being highlighted (used by analyzer) /// </param> /// <param name="text"> text to highlight terms in /// </param> /// <param name="maxNumFragments"> the maximum number of fragments. /// /// </param> /// <returns> highlighted text fragments (between 0 and maxNumFragments number of fragments) /// </returns> public System.String[] GetBestFragments(Analyzer analyzer, System.String fieldName, System.String text, int maxNumFragments) { TokenStream tokenStream = analyzer.TokenStream(fieldName, new System.IO.StringReader(text)); return GetBestFragments(tokenStream, text, maxNumFragments); } /// <summary> Highlights chosen terms in a text, extracting the most relevant sections. /// The document text is analysed in chunks to record hit statistics /// across the document. After accumulating stats, the fragments with the highest scores /// are returned as an array of strings in order of score (contiguous fragments are merged into /// one in their original order to improve readability) /// /// </summary> /// <param name="text"> text to highlight terms in /// </param> /// <param name="maxNumFragments"> the maximum number of fragments. /// /// </param> /// <returns> highlighted text fragments (between 0 and maxNumFragments number of fragments) /// </returns> public System.String[] GetBestFragments(TokenStream tokenStream, System.String text, int maxNumFragments) { maxNumFragments = System.Math.Max(1, maxNumFragments); //sanity check TextFragment[] frag = GetBestTextFragments(tokenStream, text, true, maxNumFragments); //Get text System.Collections.ArrayList fragTexts = new System.Collections.ArrayList(); for (int i = 0; i < frag.Length; i++) { if ((frag[i] != null) && (frag[i].GetScore() > 0)) { fragTexts.Add(frag[i].ToString()); } } return (System.String[]) fragTexts.ToArray(typeof(System.String)); } /// <summary> Low level api to get the most relevant (formatted) sections of the document. /// This method has been made public to allow visibility of score information held in TextFragment objects. /// Thanks to Jason Calabrese for help in redefining the interface. /// </summary> /// <param name="">tokenStream /// </param> /// <param name="">text /// </param> /// <param name="">maxNumFragments /// </param> /// <param name="">mergeContiguousFragments /// </param> /// <throws> IOException </throws> public TextFragment[] GetBestTextFragments(TokenStream tokenStream, System.String text, bool mergeContiguousFragments, int maxNumFragments) { System.Collections.ArrayList docFrags = new System.Collections.ArrayList(); System.Text.StringBuilder newText = new System.Text.StringBuilder(); TextFragment currentFrag = new TextFragment(newText, newText.Length, docFrags.Count); fragmentScorer.StartFragment(currentFrag); docFrags.Add(currentFrag); FragmentQueue fragQueue = new FragmentQueue(maxNumFragments); try { Lucene.Net.Analysis.Token token; System.String tokenText; int startOffset; int endOffset; int lastEndOffset = 0; textFragmenter.Start(text); TokenGroup tokenGroup = new TokenGroup(); token = tokenStream.Next(); while ((token != null) && (token.StartOffset() < maxDocBytesToAnalyze)) { if ((tokenGroup.numTokens > 0) && (tokenGroup.IsDistinct(token))) { //the current token is distinct from previous tokens - // markup the cached token group info startOffset = tokenGroup.matchStartOffset; endOffset = tokenGroup.matchEndOffset; tokenText = text.Substring(startOffset, (endOffset) - (startOffset)); System.String markedUpText = formatter.HighlightTerm(encoder.EncodeText(tokenText), tokenGroup); //store any whitespace etc from between this and last group if (startOffset > lastEndOffset) newText.Append(encoder.EncodeText(text.Substring(lastEndOffset, (startOffset) - (lastEndOffset)))); newText.Append(markedUpText); lastEndOffset = System.Math.Max(endOffset, lastEndOffset); tokenGroup.Clear(); //check if current token marks the start of a new fragment if (textFragmenter.IsNewFragment(token)) { currentFrag.SetScore(fragmentScorer.GetFragmentScore()); //record stats for a new fragment currentFrag.textEndPos = newText.Length; currentFrag = new TextFragment(newText, newText.Length, docFrags.Count); fragmentScorer.StartFragment(currentFrag); docFrags.Add(currentFrag); } } tokenGroup.AddToken(token, fragmentScorer.GetTokenScore(token)); // if(lastEndOffset>maxDocBytesToAnalyze) // { // break; // } token = tokenStream.Next(); } currentFrag.SetScore(fragmentScorer.GetFragmentScore()); if (tokenGroup.numTokens > 0) { //flush the accumulated text (same code as in above loop) startOffset = tokenGroup.matchStartOffset; endOffset = tokenGroup.matchEndOffset; tokenText = text.Substring(startOffset, (endOffset) - (startOffset)); System.String markedUpText = formatter.HighlightTerm(encoder.EncodeText(tokenText), tokenGroup); //store any whitespace etc from between this and last group if (startOffset > lastEndOffset) newText.Append(encoder.EncodeText(text.Substring(lastEndOffset, (startOffset) - (lastEndOffset)))); newText.Append(markedUpText); lastEndOffset = System.Math.Max(lastEndOffset, endOffset); } //Test what remains of the original text beyond the point where we stopped analyzing if ((lastEndOffset < text.Length) && (text.Length < maxDocBytesToAnalyze)) { //append it to the last fragment newText.Append(encoder.EncodeText(text.Substring(lastEndOffset))); } currentFrag.textEndPos = newText.Length; //sort the most relevant sections of the text for (System.Collections.IEnumerator i = docFrags.GetEnumerator(); i.MoveNext(); ) { currentFrag = (TextFragment) i.Current; //If you are running with a version of Lucene before 11th Sept 03 // you do not have PriorityQueue.insert() - so uncomment the code below /* if (currentFrag.getScore() >= minScore) { fragQueue.put(currentFrag); if (fragQueue.size() > maxNumFragments) { // if hit queue overfull fragQueue.pop(); // remove lowest in hit queue minScore = ((TextFragment) fragQueue.top()).getScore(); // reset minScore } } */ //The above code caused a problem as a result of Christoph Goller's 11th Sept 03 //fix to PriorityQueue. The correct method to use here is the new "insert" method // USE ABOVE CODE IF THIS DOES NOT COMPILE! fragQueue.Insert(currentFrag); } //return the most relevant fragments TextFragment[] frag = new TextFragment[fragQueue.Size()]; for (int i = frag.Length - 1; i >= 0; i--) { frag[i] = (TextFragment) fragQueue.Pop(); } //merge any contiguous fragments to improve readability if (mergeContiguousFragments) { MergeContiguousFragments(frag); System.Collections.ArrayList fragTexts = new System.Collections.ArrayList(); for (int i = 0; i < frag.Length; i++) { if ((frag[i] != null) && (frag[i].GetScore() > 0)) { fragTexts.Add(frag[i]); } } frag = (TextFragment[]) fragTexts.ToArray(typeof(TextFragment)); } return frag; } finally { if (tokenStream != null) { try { tokenStream.Close(); } catch (System.Exception e) { } } } } /// <summary>Improves readability of a score-sorted list of TextFragments by merging any fragments /// that were contiguous in the original text into one larger fragment with the correct order. /// This will leave a "null" in the array entry for the lesser scored fragment. /// /// </summary> /// <param name="frag">An array of document fragments in descending score /// </param> private void MergeContiguousFragments(TextFragment[] frag) { bool mergingStillBeingDone; if (frag.Length > 1) do { mergingStillBeingDone = false; //initialise loop control flag //for each fragment, scan other frags looking for contiguous blocks for (int i = 0; i < frag.Length; i++) { if (frag[i] == null) { continue; } //merge any contiguous blocks for (int x = 0; x < frag.Length; x++) { if (frag[x] == null) { continue; } if (frag[i] == null) { break; } TextFragment frag1 = null; TextFragment frag2 = null; int frag1Num = 0; int frag2Num = 0; int bestScoringFragNum; int worstScoringFragNum; //if blocks are contiguous.... if (frag[i].Follows(frag[x])) { frag1 = frag[x]; frag1Num = x; frag2 = frag[i]; frag2Num = i; } else if (frag[x].Follows(frag[i])) { frag1 = frag[i]; frag1Num = i; frag2 = frag[x]; frag2Num = x; } //merging required.. if (frag1 != null) { if (frag1.GetScore() > frag2.GetScore()) { bestScoringFragNum = frag1Num; worstScoringFragNum = frag2Num; } else { bestScoringFragNum = frag2Num; worstScoringFragNum = frag1Num; } frag1.Merge(frag2); frag[worstScoringFragNum] = null; mergingStillBeingDone = true; frag[bestScoringFragNum] = frag1; } } } } while (mergingStillBeingDone); } /// <summary> Highlights terms in the text , extracting the most relevant sections /// and concatenating the chosen fragments with a separator (typically "..."). /// The document text is analysed in chunks to record hit statistics /// across the document. After accumulating stats, the fragments with the highest scores /// are returned in order as "separator" delimited strings. /// /// </summary> /// <param name="text"> text to highlight terms in /// </param> /// <param name="maxNumFragments"> the maximum number of fragments. /// </param> /// <param name="separator"> the separator used to intersperse the document fragments (typically "...") /// /// </param> /// <returns> highlighted text /// </returns> public System.String GetBestFragments(TokenStream tokenStream, System.String text, int maxNumFragments, System.String separator) { System.String[] sections = GetBestFragments(tokenStream, text, maxNumFragments); System.Text.StringBuilder result = new System.Text.StringBuilder(); for (int i = 0; i < sections.Length; i++) { if (i > 0) { result.Append(separator); } result.Append(sections[i]); } return result.ToString(); } /// <returns> the maximum number of bytes to be tokenized per doc /// </returns> public virtual int GetMaxDocBytesToAnalyze() { return maxDocBytesToAnalyze; } /// <param name="byteCount">the maximum number of bytes to be tokenized per doc /// (This can improve performance with large documents) /// </param> public virtual void SetMaxDocBytesToAnalyze(int byteCount) { maxDocBytesToAnalyze = byteCount; } public virtual Fragmenter GetTextFragmenter() { return textFragmenter; } /// <param name="">fragmenter /// </param> public virtual void SetTextFragmenter(Fragmenter fragmenter) { textFragmenter = fragmenter; } /// <returns> Object used to score each text fragment /// </returns> public virtual Scorer GetFragmentScorer() { return fragmentScorer; } /// <param name="">scorer /// </param> public virtual void SetFragmentScorer(Scorer scorer) { fragmentScorer = scorer; } public virtual Encoder GetEncoder() { return encoder; } public virtual void SetEncoder(Encoder encoder) { this.encoder = encoder; } } class FragmentQueue : PriorityQueue { public FragmentQueue(int size) { Initialize(size); } public override bool LessThan(System.Object a, System.Object b) { TextFragment fragA = (TextFragment) a; TextFragment fragB = (TextFragment) b; if (fragA.GetScore() == fragB.GetScore()) return fragA.fragNum > fragB.fragNum; else return fragA.GetScore() < fragB.GetScore(); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Security.Permissions; namespace NLog.UnitTests { using System; using NLog.Common; using System.IO; using System.Text; using NLog.Layouts; using NLog.Config; using Xunit; #if SILVERLIGHT using System.Xml.Linq; #else using System.Xml; #endif public abstract class NLogTestBase { public void AssertDebugCounter(string targetName, int val) { var debugTarget = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName(targetName); Assert.NotNull(debugTarget); Assert.Equal(val, debugTarget.Counter); } public void AssertDebugLastMessage(string targetName, string msg) { NLog.Targets.DebugTarget debugTarget = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName(targetName); Assert.NotNull(debugTarget); Assert.Equal(msg, debugTarget.LastMessage); } public void AssertDebugLastMessageContains(string targetName, string msg) { NLog.Targets.DebugTarget debugTarget = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName(targetName); // Console.WriteLine("lastmsg: {0}", debugTarget.LastMessage); Assert.NotNull(debugTarget); Assert.True(debugTarget.LastMessage.Contains(msg), "Unexpected last message value on '" + targetName + "'"); } public string GetDebugLastMessage(string targetName) { var debugTarget = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName(targetName); return debugTarget.LastMessage; } public void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(true, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); Assert.True(encodedBuf.Length <= fi.Length); byte[] buf = new byte[encodedBuf.Length]; using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } public void AssertFileSize(string filename, long expectedSize) { var fi = new FileInfo(filename); if (!fi.Exists) { Assert.True(true, string.Format("File \"{0}\" doesn't exist.", filename)); } if (fi.Length != expectedSize) { Assert.True(true, string.Format("Filesize of \"{0}\" unequals {1}.", filename, expectedSize)); } } public void AssertFileContents(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(true, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); Assert.Equal(encodedBuf.Length, fi.Length); byte[] buf = new byte[(int)fi.Length]; using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } public string StringRepeat(int times, string s) { StringBuilder sb = new StringBuilder(s.Length * times); for (int i = 0; i < times; ++i) sb.Append(s); return sb.ToString(); } protected void AssertLayoutRendererOutput(Layout l, string expected) { l.Initialize(null); string actual = l.Render(LogEventInfo.Create(LogLevel.Info, "loggername", "message")); l.Close(); Assert.Equal(expected, actual); } protected XmlLoggingConfiguration CreateConfigurationFromString(string configXml) { #if SILVERLIGHT XElement element = XElement.Parse(configXml); return new XmlLoggingConfiguration(element.CreateReader(), null); #else XmlDocument doc = new XmlDocument(); doc.LoadXml(configXml); return new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory); #endif } protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel) { var stringWriter = new StringWriter(); var oldWriter = InternalLogger.LogWriter; var oldLevel = InternalLogger.LogLevel; var oldIncludeTimestamp = InternalLogger.IncludeTimestamp; try { InternalLogger.LogWriter = stringWriter; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; action(); return stringWriter.ToString(); } finally { InternalLogger.LogWriter = oldWriter; InternalLogger.LogLevel = oldLevel; InternalLogger.IncludeTimestamp = oldIncludeTimestamp; } } public delegate void SyncAction(); public class InternalLoggerScope : IDisposable { private readonly string logFile; private readonly LogLevel logLevel; private readonly bool logToConsole; private readonly bool includeTimestamp; private readonly bool logToConsoleError; private readonly LogLevel globalThreshold; private readonly bool throwExceptions; public InternalLoggerScope() { this.logFile = InternalLogger.LogFile; this.logLevel = InternalLogger.LogLevel; this.logToConsole = InternalLogger.LogToConsole; this.includeTimestamp = InternalLogger.IncludeTimestamp; this.logToConsoleError = InternalLogger.LogToConsoleError; this.globalThreshold = LogManager.GlobalThreshold; this.throwExceptions = LogManager.ThrowExceptions; } public void Dispose() { InternalLogger.LogFile = this.logFile; InternalLogger.LogLevel = this.logLevel; InternalLogger.LogToConsole = this.logToConsole; InternalLogger.IncludeTimestamp = this.includeTimestamp; InternalLogger.LogToConsoleError = this.logToConsoleError; LogManager.GlobalThreshold = this.globalThreshold; LogManager.ThrowExceptions = this.throwExceptions; } } } }
// <copyright file="EdgeDriverService.cs" company="Microsoft"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Globalization; using System.Text; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Edge { /// <summary> /// Exposes the service provided by the native MicrosoftWebDriver executable. /// </summary> public sealed class EdgeDriverService : DriverService { private const string MicrosoftWebDriverServiceFileName = "MicrosoftWebDriver.exe"; private static readonly Uri MicrosoftWebDriverDownloadUrl = new Uri("http://go.microsoft.com/fwlink/?LinkId=619687"); private string host; private string package; private bool useVerboseLogging; private bool? useSpecCompliantProtocol; /// <summary> /// Initializes a new instance of the <see cref="EdgeDriverService"/> class. /// </summary> /// <param name="executablePath">The full path to the EdgeDriver executable.</param> /// <param name="executableFileName">The file name of the EdgeDriver executable.</param> /// <param name="port">The port on which the EdgeDriver executable should listen.</param> private EdgeDriverService(string executablePath, string executableFileName, int port) : base(executablePath, port, executableFileName, MicrosoftWebDriverDownloadUrl) { } /// <summary> /// Gets or sets the value of the host adapter on which the Edge driver service should listen for connections. /// </summary> public string Host { get { return this.host; } set { this.host = value; } } /// <summary> /// Gets or sets the value of the package the Edge driver service will launch and automate. /// </summary> public string Package { get { return this.package; } set { this.package = value; } } /// <summary> /// Gets or sets a value indicating whether the service should use verbose logging. /// </summary> public bool UseVerboseLogging { get { return this.useVerboseLogging; } set { this.useVerboseLogging = value; } } /// <summary> /// Gets or sets a value indicating whether the <see cref="EdgeDriverService"/> instance /// should use the a protocol dialect compliant with the W3C WebDriver Specification. /// </summary> /// <remarks> /// Setting this property to a non-<see langword="null"/> value for driver /// executables matched to versions of Windows before the 2018 Fall Creators /// Update will result in a the driver executable shutting down without /// execution, and all commands will fail. Do not set this property unless /// you are certain your version of the MicrosoftWebDriver.exe supports the /// --w3c and --jwp command-line arguments. /// </remarks> public bool? UseSpecCompliantProtocol { get { return this.useSpecCompliantProtocol; } set { this.useSpecCompliantProtocol = value; } } /// <summary> /// Gets a value indicating whether the service has a shutdown API that can be called to terminate /// it gracefully before forcing a termination. /// </summary> protected override bool HasShutdown { get { if (this.useSpecCompliantProtocol.HasValue && !this.useSpecCompliantProtocol.Value) { return base.HasShutdown; } return false; } } /// <summary> /// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate. /// </summary> protected override TimeSpan TerminationTimeout { // Use a very small timeout for terminating the Edge driver, // because the executable does not have a clean shutdown command, // which means we have to kill the process. Using a short timeout // gets us to the termination point much faster. get { if (this.useSpecCompliantProtocol.HasValue && !this.useSpecCompliantProtocol.Value) { return base.TerminationTimeout; } return TimeSpan.FromMilliseconds(100); } } /// <summary> /// Gets the command-line arguments for the driver service. /// </summary> protected override string CommandLineArguments { get { StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments); if (!string.IsNullOrEmpty(this.host)) { argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --host={0}", this.host)); } if (!string.IsNullOrEmpty(this.package)) { argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --package={0}", this.package)); } if (this.useVerboseLogging) { argsBuilder.Append(" --verbose"); } if (this.SuppressInitialDiagnosticInformation) { argsBuilder.Append(" --silent"); } if (this.useSpecCompliantProtocol.HasValue) { if (this.useSpecCompliantProtocol.Value) { argsBuilder.Append(" --w3c"); } else { argsBuilder.Append(" --jwp"); } } return argsBuilder.ToString(); } } /// <summary> /// Creates a default instance of the EdgeDriverService. /// </summary> /// <returns>A EdgeDriverService that implements default settings.</returns> public static EdgeDriverService CreateDefaultService() { string serviceDirectory = DriverService.FindDriverServiceExecutable(MicrosoftWebDriverServiceFileName, MicrosoftWebDriverDownloadUrl); EdgeDriverService service = CreateDefaultService(serviceDirectory); return service; } /// <summary> /// Creates a default instance of the EdgeDriverService using a specified path to the EdgeDriver executable. /// </summary> /// <param name="driverPath">The directory containing the EdgeDriver executable.</param> /// <returns>A EdgeDriverService using a random port.</returns> public static EdgeDriverService CreateDefaultService(string driverPath) { return CreateDefaultService(driverPath, MicrosoftWebDriverServiceFileName); } /// <summary> /// Creates a default instance of the EdgeDriverService using a specified path to the EdgeDriver executable with the given name. /// </summary> /// <param name="driverPath">The directory containing the EdgeDriver executable.</param> /// <param name="driverExecutableFileName">The name of the EdgeDriver executable file.</param> /// <returns>A EdgeDriverService using a random port.</returns> public static EdgeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName) { return CreateDefaultService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort()); } /// <summary> /// Creates a default instance of the EdgeDriverService using a specified path to the EdgeDriver executable with the given name and listening port. /// </summary> /// <param name="driverPath">The directory containing the EdgeDriver executable.</param> /// <param name="driverExecutableFileName">The name of the EdgeDriver executable file</param> /// <param name="port">The port number on which the driver will listen</param> /// <returns>A EdgeDriverService using the specified port.</returns> public static EdgeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName, int port) { return new EdgeDriverService(driverPath, driverExecutableFileName, port); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/metric_service.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Monitoring.V3 { /// <summary> /// Manages metric descriptors, monitored resource descriptors, and /// time series data. /// </summary> public static partial class MetricService { static readonly string __ServiceName = "google.monitoring.v3.MetricService"; static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest> __Marshaller_ListMonitoredResourceDescriptorsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> __Marshaller_ListMonitoredResourceDescriptorsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest> __Marshaller_GetMonitoredResourceDescriptorRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Api.MonitoredResourceDescriptor> __Marshaller_MonitoredResourceDescriptor = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Api.MonitoredResourceDescriptor.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest> __Marshaller_ListMetricDescriptorsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> __Marshaller_ListMetricDescriptorsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest> __Marshaller_GetMetricDescriptorRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Api.MetricDescriptor> __Marshaller_MetricDescriptor = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Api.MetricDescriptor.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest> __Marshaller_CreateMetricDescriptorRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest> __Marshaller_DeleteMetricDescriptorRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest> __Marshaller_ListTimeSeriesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> __Marshaller_ListTimeSeriesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest> __Marshaller_CreateTimeSeriesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> __Method_ListMonitoredResourceDescriptors = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse>( grpc::MethodType.Unary, __ServiceName, "ListMonitoredResourceDescriptors", __Marshaller_ListMonitoredResourceDescriptorsRequest, __Marshaller_ListMonitoredResourceDescriptorsResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest, global::Google.Api.MonitoredResourceDescriptor> __Method_GetMonitoredResourceDescriptor = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest, global::Google.Api.MonitoredResourceDescriptor>( grpc::MethodType.Unary, __ServiceName, "GetMonitoredResourceDescriptor", __Marshaller_GetMonitoredResourceDescriptorRequest, __Marshaller_MonitoredResourceDescriptor); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> __Method_ListMetricDescriptors = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest, global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse>( grpc::MethodType.Unary, __ServiceName, "ListMetricDescriptors", __Marshaller_ListMetricDescriptorsRequest, __Marshaller_ListMetricDescriptorsResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest, global::Google.Api.MetricDescriptor> __Method_GetMetricDescriptor = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest, global::Google.Api.MetricDescriptor>( grpc::MethodType.Unary, __ServiceName, "GetMetricDescriptor", __Marshaller_GetMetricDescriptorRequest, __Marshaller_MetricDescriptor); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest, global::Google.Api.MetricDescriptor> __Method_CreateMetricDescriptor = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest, global::Google.Api.MetricDescriptor>( grpc::MethodType.Unary, __ServiceName, "CreateMetricDescriptor", __Marshaller_CreateMetricDescriptorRequest, __Marshaller_MetricDescriptor); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteMetricDescriptor = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteMetricDescriptor", __Marshaller_DeleteMetricDescriptorRequest, __Marshaller_Empty); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest, global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> __Method_ListTimeSeries = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest, global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse>( grpc::MethodType.Unary, __ServiceName, "ListTimeSeries", __Marshaller_ListTimeSeriesRequest, __Marshaller_ListTimeSeriesResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_CreateTimeSeries = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "CreateTimeSeries", __Marshaller_CreateTimeSeriesRequest, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.MetricServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of MetricService</summary> public abstract partial class MetricServiceBase { /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptors(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptor(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptors(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Api.MetricDescriptor> GetMetricDescriptor(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Api.MetricDescriptor> CreateMetricDescriptor(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptor(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeries(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeries(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for MetricService</summary> public partial class MetricServiceClient : grpc::ClientBase<MetricServiceClient> { /// <summary>Creates a new client for MetricService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public MetricServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for MetricService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public MetricServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected MetricServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected MetricServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMonitoredResourceDescriptors(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse ListMonitoredResourceDescriptors(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request); } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMonitoredResourceDescriptorsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsResponse> ListMonitoredResourceDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMonitoredResourceDescriptorsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListMonitoredResourceDescriptors, null, options, request); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Api.MonitoredResourceDescriptor GetMonitoredResourceDescriptor(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMonitoredResourceDescriptor(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Api.MonitoredResourceDescriptor GetMonitoredResourceDescriptor(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetMonitoredResourceDescriptor, null, options, request); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMonitoredResourceDescriptorAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single monitored resource descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Api.MonitoredResourceDescriptor> GetMonitoredResourceDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMonitoredResourceDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetMonitoredResourceDescriptor, null, options, request); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse ListMetricDescriptors(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMetricDescriptors(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse ListMetricDescriptors(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListMetricDescriptors, null, options, request); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListMetricDescriptorsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists metric descriptors that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsResponse> ListMetricDescriptorsAsync(global::Google.Cloud.Monitoring.V3.ListMetricDescriptorsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListMetricDescriptors, null, options, request); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Api.MetricDescriptor GetMetricDescriptor(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMetricDescriptor(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Api.MetricDescriptor GetMetricDescriptor(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetMetricDescriptor, null, options, request); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Api.MetricDescriptor> GetMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetMetricDescriptorAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets a single metric descriptor. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Api.MetricDescriptor> GetMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.GetMetricDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetMetricDescriptor, null, options, request); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Api.MetricDescriptor CreateMetricDescriptor(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateMetricDescriptor(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Api.MetricDescriptor CreateMetricDescriptor(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateMetricDescriptor, null, options, request); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Api.MetricDescriptor> CreateMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateMetricDescriptorAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a new metric descriptor. /// User-created metric descriptors define /// [custom metrics](/monitoring/custom-metrics). /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Api.MetricDescriptor> CreateMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.CreateMetricDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateMetricDescriptor, null, options, request); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMetricDescriptor(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteMetricDescriptor(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMetricDescriptor(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteMetricDescriptor, null, options, request); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteMetricDescriptorAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a metric descriptor. Only user-created /// [custom metrics](/monitoring/custom-metrics) can be deleted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMetricDescriptorAsync(global::Google.Cloud.Monitoring.V3.DeleteMetricDescriptorRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteMetricDescriptor, null, options, request); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse ListTimeSeries(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTimeSeries(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse ListTimeSeries(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListTimeSeries, null, options, request); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListTimeSeriesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists time series that match a filter. This method does not require a Stackdriver account. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListTimeSeriesResponse> ListTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.ListTimeSeriesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListTimeSeries, null, options, request); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty CreateTimeSeries(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateTimeSeries(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty CreateTimeSeries(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateTimeSeries, null, options, request); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateTimeSeriesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates or adds data to one or more time series. /// The response is empty if all time series in the request were written. /// If any time series could not be written, a corresponding failure message is /// included in the error response. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> CreateTimeSeriesAsync(global::Google.Cloud.Monitoring.V3.CreateTimeSeriesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateTimeSeries, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override MetricServiceClient NewInstance(ClientBaseConfiguration configuration) { return new MetricServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(MetricServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_ListMonitoredResourceDescriptors, serviceImpl.ListMonitoredResourceDescriptors) .AddMethod(__Method_GetMonitoredResourceDescriptor, serviceImpl.GetMonitoredResourceDescriptor) .AddMethod(__Method_ListMetricDescriptors, serviceImpl.ListMetricDescriptors) .AddMethod(__Method_GetMetricDescriptor, serviceImpl.GetMetricDescriptor) .AddMethod(__Method_CreateMetricDescriptor, serviceImpl.CreateMetricDescriptor) .AddMethod(__Method_DeleteMetricDescriptor, serviceImpl.DeleteMetricDescriptor) .AddMethod(__Method_ListTimeSeries, serviceImpl.ListTimeSeries) .AddMethod(__Method_CreateTimeSeries, serviceImpl.CreateTimeSeries).Build(); } } } #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.Generic; using System.Globalization; using System.IO; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.WebEncoders.Testing; using Xunit; namespace Microsoft.AspNetCore.Html.Test { public class HtmlContentBuilderExtensionsTest { [Fact] public void Builder_AppendLine_Empty() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendLine(); // Assert Assert.Collection( builder.Entries, entry => Assert.Equal(Environment.NewLine, HtmlContentToString(entry))); } [Fact] public void Builder_AppendLine_String() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendLine("Hi"); // Assert Assert.Collection( builder.Entries, entry => Assert.Equal("Hi", Assert.IsType<UnencodedString>(entry).Value), entry => Assert.Equal(Environment.NewLine, HtmlContentToString(entry))); } [Fact] public void Builder_AppendLine_IHtmlContent() { // Arrange var builder = new TestHtmlContentBuilder(); var content = new OtherHtmlContent("Hi"); // Act builder.AppendLine(content); // Assert Assert.Collection( builder.Entries, entry => Assert.Same(content, entry), entry => Assert.Equal(Environment.NewLine, HtmlContentToString(entry))); } [Fact] public void Builder_AppendHtmlLine_String() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendHtmlLine("Hi"); // Assert Assert.Collection( builder.Entries, entry => Assert.Equal("Hi", Assert.IsType<EncodedString>(entry).Value), entry => Assert.Equal(Environment.NewLine, HtmlContentToString(entry))); } [Fact] public void Builder_SetContent_String() { // Arrange var builder = new TestHtmlContentBuilder(); builder.Append("Existing Content. Will be Cleared."); // Act builder.SetContent("Hi"); // Assert Assert.Collection( builder.Entries, entry => Assert.Equal("Hi", Assert.IsType<UnencodedString>(entry).Value)); } [Fact] public void Builder_SetContent_IHtmlContent() { // Arrange var builder = new TestHtmlContentBuilder(); builder.Append("Existing Content. Will be Cleared."); var content = new OtherHtmlContent("Hi"); // Act builder.SetHtmlContent(content); // Assert Assert.Collection( builder.Entries, entry => Assert.Same(content, entry)); } [Fact] public void Builder_SetHtmlContent_String() { // Arrange var builder = new TestHtmlContentBuilder(); builder.Append("Existing Content. Will be Cleared."); // Act builder.SetHtmlContent("Hi"); // Assert Assert.Collection( builder.Entries, entry => Assert.Equal("Hi", Assert.IsType<EncodedString>(entry).Value)); } [Fact] public void Builder_AppendFormat() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("{0} {1} {2} {3}!", "First", "Second", "Third", "Fourth"); // Assert Assert.Equal( "HtmlEncode[[First]] HtmlEncode[[Second]] HtmlEncode[[Third]] HtmlEncode[[Fourth]]!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_HtmlContent() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("{0}!", new EncodedString("First")); // Assert Assert.Equal( "First!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_HtmlString() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("{0}!", new HtmlString("First")); // Assert Assert.Equal("First!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormatContent_With1Argument() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("0x{0:X} - hex equivalent for 50.", 50); // Assert Assert.Equal( "0xHtmlEncode[[32]] - hex equivalent for 50.", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormatContent_With2Arguments() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("0x{0:X} - hex equivalent for {1}.", 50, 50); // Assert Assert.Equal( "0xHtmlEncode[[32]] - hex equivalent for HtmlEncode[[50]].", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormatContent_With3Arguments() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("0x{0:X} - {1} equivalent for {2}.", 50, "hex", 50); // Assert Assert.Equal( "0xHtmlEncode[[32]] - HtmlEncode[[hex]] equivalent for HtmlEncode[[50]].", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithAlignmentComponent() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("{0, -25} World!", "Hello"); // Assert Assert.Equal( "HtmlEncode[[Hello]] World!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithFormatStringComponent() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat("0x{0:X}", 50); // Assert Assert.Equal("0xHtmlEncode[[32]]", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithCulture() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat( CultureInfo.InvariantCulture, "Numbers in InvariantCulture - {0, -5:N} {1} {2} {3}!", 1.1, 2.98, 145.82, 32.86); // Assert Assert.Equal( "Numbers in InvariantCulture - HtmlEncode[[1.10]] HtmlEncode[[2.98]] " + "HtmlEncode[[145.82]] HtmlEncode[[32.86]]!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithCulture_1Argument() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat( CultureInfo.InvariantCulture, "Numbers in InvariantCulture - {0:N}!", 1.1); // Assert Assert.Equal( "Numbers in InvariantCulture - HtmlEncode[[1.10]]!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithCulture_2Arguments() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat( CultureInfo.InvariantCulture, "Numbers in InvariantCulture - {0:N} {1}!", 1.1, 2.98); // Assert Assert.Equal( "Numbers in InvariantCulture - HtmlEncode[[1.10]] HtmlEncode[[2.98]]!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithCulture_3Arguments() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat( CultureInfo.InvariantCulture, "Numbers in InvariantCulture - {0:N} {1} {2}!", 1.1, 2.98, 3.12); // Assert Assert.Equal( "Numbers in InvariantCulture - HtmlEncode[[1.10]] HtmlEncode[[2.98]] HtmlEncode[[3.12]]!", HtmlContentToString(builder)); } [Fact] public void Builder_AppendFormat_WithDifferentCulture() { // Arrange var builder = new TestHtmlContentBuilder(); var culture = new CultureInfo("fr-FR"); // Act builder.AppendFormat(culture, "{0} in french!", 1.21); // Assert Assert.Equal( "HtmlEncode[[1,21]] in french!", HtmlContentToString(builder)); } [Fact] [ReplaceCulture("de-DE", "de-DE")] public void Builder_AppendFormat_WithDifferentCurrentCulture() { // Arrange var builder = new TestHtmlContentBuilder(); // Act builder.AppendFormat(CultureInfo.CurrentCulture, "{0:D}", new DateTime(2015, 02, 01)); // Assert Assert.Equal( "HtmlEncode[[Sonntag, 1. Februar 2015]]", HtmlContentToString(builder)); } private static string HtmlContentToString(IHtmlContent content) { using (var writer = new StringWriter()) { content.WriteTo(writer, new HtmlTestEncoder()); return writer.ToString(); } } private class TestHtmlContentBuilder : IHtmlContentBuilder { public List<IHtmlContent> Entries { get; } = new List<IHtmlContent>(); public IHtmlContentBuilder Append(string unencoded) { Entries.Add(new UnencodedString(unencoded)); return this; } public IHtmlContentBuilder AppendHtml(IHtmlContent content) { Entries.Add(content); return this; } public IHtmlContentBuilder AppendHtml(string encoded) { Entries.Add(new EncodedString(encoded)); return this; } public IHtmlContentBuilder Clear() { Entries.Clear(); return this; } public void CopyTo(IHtmlContentBuilder destination) { foreach (var entry in Entries) { destination.AppendHtml(entry); } } public void MoveTo(IHtmlContentBuilder destination) { CopyTo(destination); Clear(); } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { foreach (var entry in Entries) { entry.WriteTo(writer, encoder); } } } private class EncodedString : IHtmlContent { public EncodedString(string value) { Value = value; } public string Value { get; } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { writer.Write(Value); } } private class UnencodedString : IHtmlContent { public UnencodedString(string value) { Value = value; } public string Value { get; } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { encoder.Encode(writer, Value); } } private class OtherHtmlContent : IHtmlContent { public OtherHtmlContent(string value) { Value = value; } public string Value { get; } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { throw new NotImplementedException(); } } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public class QuantizedBvhNode : IDisposable { internal IntPtr _native; internal QuantizedBvhNode(IntPtr native) { _native = native; } public QuantizedBvhNode() { _native = btQuantizedBvhNode_new(); } public int EscapeIndex { get { return btQuantizedBvhNode_getEscapeIndex(_native); } } public int EscapeIndexOrTriangleIndex { get { return btQuantizedBvhNode_getEscapeIndexOrTriangleIndex(_native); } set { btQuantizedBvhNode_setEscapeIndexOrTriangleIndex(_native, value); } } public bool IsLeafNode { get { return btQuantizedBvhNode_isLeafNode(_native); } } public int PartId { get { return btQuantizedBvhNode_getPartId(_native); } } /* public UShortArray QuantizedAabbMax { get { return btQuantizedBvhNode_getQuantizedAabbMax(_native); } } public UShortArray QuantizedAabbMin { get { return btQuantizedBvhNode_getQuantizedAabbMin(_native); } } */ public int TriangleIndex { get { return btQuantizedBvhNode_getTriangleIndex(_native); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btQuantizedBvhNode_delete(_native); _native = IntPtr.Zero; } } ~QuantizedBvhNode() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvhNode_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btQuantizedBvhNode_getEscapeIndex(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btQuantizedBvhNode_getEscapeIndexOrTriangleIndex(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btQuantizedBvhNode_getPartId(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvhNode_getQuantizedAabbMax(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvhNode_getQuantizedAabbMin(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btQuantizedBvhNode_getTriangleIndex(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btQuantizedBvhNode_isLeafNode(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvhNode_setEscapeIndexOrTriangleIndex(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvhNode_delete(IntPtr obj); } public class OptimizedBvhNode : IDisposable { internal IntPtr _native; internal OptimizedBvhNode(IntPtr native) { _native = native; } public OptimizedBvhNode() { _native = btOptimizedBvhNode_new(); } public Vector3 AabbMaxOrg { get { Vector3 value; btOptimizedBvhNode_getAabbMaxOrg(_native, out value); return value; } set { btOptimizedBvhNode_setAabbMaxOrg(_native, ref value); } } public Vector3 AabbMinOrg { get { Vector3 value; btOptimizedBvhNode_getAabbMinOrg(_native, out value); return value; } set { btOptimizedBvhNode_setAabbMinOrg(_native, ref value); } } public int EscapeIndex { get { return btOptimizedBvhNode_getEscapeIndex(_native); } set { btOptimizedBvhNode_setEscapeIndex(_native, value); } } public int SubPart { get { return btOptimizedBvhNode_getSubPart(_native); } set { btOptimizedBvhNode_setSubPart(_native, value); } } public int TriangleIndex { get { return btOptimizedBvhNode_getTriangleIndex(_native); } set { btOptimizedBvhNode_setTriangleIndex(_native, value); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btOptimizedBvhNode_delete(_native); _native = IntPtr.Zero; } } ~OptimizedBvhNode() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btOptimizedBvhNode_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_getAabbMaxOrg(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_getAabbMinOrg(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btOptimizedBvhNode_getEscapeIndex(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btOptimizedBvhNode_getSubPart(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btOptimizedBvhNode_getTriangleIndex(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_setAabbMaxOrg(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_setAabbMinOrg(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_setEscapeIndex(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_setSubPart(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_setTriangleIndex(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btOptimizedBvhNode_delete(IntPtr obj); } public class NodeOverlapCallback : IDisposable { internal IntPtr _native; internal NodeOverlapCallback(IntPtr native) { _native = native; } public void ProcessNode(int subPart, int triangleIndex) { btNodeOverlapCallback_processNode(_native, subPart, triangleIndex); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { btNodeOverlapCallback_delete(_native); _native = IntPtr.Zero; } } ~NodeOverlapCallback() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btNodeOverlapCallback_processNode(IntPtr obj, int subPart, int triangleIndex); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btNodeOverlapCallback_delete(IntPtr obj); } public class QuantizedBvh : IDisposable { public enum TraversalMode { Stackless, StacklessCacheFriendly, Recursive } internal IntPtr _native; bool _preventDelete; internal QuantizedBvh(IntPtr native, bool preventDelete) { _native = native; _preventDelete = preventDelete; } public QuantizedBvh() { _native = btQuantizedBvh_new(); } public void BuildInternal() { btQuantizedBvh_buildInternal(_native); } public uint CalculateSerializeBufferSize() { return btQuantizedBvh_calculateSerializeBufferSize(_native); } public int CalculateSerializeBufferSizeNew() { return btQuantizedBvh_calculateSerializeBufferSizeNew(_native); } public void DeSerializeDouble(IntPtr quantizedBvhDoubleData) { btQuantizedBvh_deSerializeDouble(_native, quantizedBvhDoubleData); } public void DeSerializeFloat(IntPtr quantizedBvhFloatData) { btQuantizedBvh_deSerializeFloat(_native, quantizedBvhFloatData); } /* public static QuantizedBvh DeSerializeInPlace(IntPtr alignedDataBuffer, uint dataBufferSize, bool swapEndian) { return btQuantizedBvh_deSerializeInPlace(alignedDataBuffer, dataBufferSize, swapEndian); } public void Quantize(unsigned short out, Vector3 point, int isMax) { btQuantizedBvh_quantize(_native, out._native, ref point, isMax); } public void QuantizeWithClamp(unsigned short out, Vector3 point2, int isMax) { btQuantizedBvh_quantizeWithClamp(_native, out._native, ref point2, isMax); } */ public void ReportAabbOverlappingNodex(NodeOverlapCallback nodeCallback, Vector3 aabbMin, Vector3 aabbMax) { btQuantizedBvh_reportAabbOverlappingNodex(_native, nodeCallback._native, ref aabbMin, ref aabbMax); } public void ReportBoxCastOverlappingNodex(NodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget, Vector3 aabbMin, Vector3 aabbMax) { btQuantizedBvh_reportBoxCastOverlappingNodex(_native, nodeCallback._native, ref raySource, ref rayTarget, ref aabbMin, ref aabbMax); } public void ReportRayOverlappingNodex(NodeOverlapCallback nodeCallback, Vector3 raySource, Vector3 rayTarget) { btQuantizedBvh_reportRayOverlappingNodex(_native, nodeCallback._native, ref raySource, ref rayTarget); } public bool Serialize(IntPtr alignedDataBuffer, uint dataBufferSize, bool swapEndian) { return btQuantizedBvh_serialize(_native, alignedDataBuffer, dataBufferSize, swapEndian); } public string Serialize(IntPtr dataBuffer, Serializer serializer) { return Marshal.PtrToStringAnsi(btQuantizedBvh_serialize2(_native, dataBuffer, serializer._native)); } public void SetQuantizationValues(Vector3 bvhAabbMin, Vector3 bvhAabbMax) { btQuantizedBvh_setQuantizationValues(_native, ref bvhAabbMin, ref bvhAabbMax); } public void SetQuantizationValues(Vector3 bvhAabbMin, Vector3 bvhAabbMax, float quantizationMargin) { btQuantizedBvh_setQuantizationValues2(_native, ref bvhAabbMin, ref bvhAabbMax, quantizationMargin); } public void SetTraversalMode(TraversalMode traversalMode) { btQuantizedBvh_setTraversalMode(_native, traversalMode); } /* public Vector3 UnQuantize(unsigned short vecIn) { Vector3 value; btQuantizedBvh_unQuantize(_native, vecIn._native, out value); return value; } */ public static uint AlignmentSerializationPadding { get { return btQuantizedBvh_getAlignmentSerializationPadding(); } } public bool IsQuantized { get { return btQuantizedBvh_isQuantized(_native); } } /* public QuantizedNodeArray LeafNodeArray { get { return btQuantizedBvh_getLeafNodeArray(_native); } } public QuantizedNodeArray QuantizedNodeArray { get { return btQuantizedBvh_getQuantizedNodeArray(_native); } } public BvhSubtreeInfoArray SubtreeInfoArray { get { return btQuantizedBvh_getSubtreeInfoArray(_native); } } */ public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_native != IntPtr.Zero) { if (!_preventDelete) { btQuantizedBvh_delete(_native); } _native = IntPtr.Zero; } } ~QuantizedBvh() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvh_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_buildInternal(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern uint btQuantizedBvh_calculateSerializeBufferSize(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btQuantizedBvh_calculateSerializeBufferSizeNew(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_deSerializeDouble(IntPtr obj, IntPtr quantizedBvhDoubleData); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_deSerializeFloat(IntPtr obj, IntPtr quantizedBvhFloatData); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvh_deSerializeInPlace(IntPtr i_alignedDataBuffer, uint i_dataBufferSize, bool i_swapEndian); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern uint btQuantizedBvh_getAlignmentSerializationPadding(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvh_getLeafNodeArray(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvh_getQuantizedNodeArray(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvh_getSubtreeInfoArray(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btQuantizedBvh_isQuantized(IntPtr obj); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btQuantizedBvh_quantize(IntPtr obj, IntPtr out, [In] ref Vector3 point, int isMax); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btQuantizedBvh_quantizeWithClamp(IntPtr obj, IntPtr out, [In] ref Vector3 point2, int isMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_reportAabbOverlappingNodex(IntPtr obj, IntPtr nodeCallback, [In] ref Vector3 aabbMin, [In] ref Vector3 aabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_reportBoxCastOverlappingNodex(IntPtr obj, IntPtr nodeCallback, [In] ref Vector3 raySource, [In] ref Vector3 rayTarget, [In] ref Vector3 aabbMin, [In] ref Vector3 aabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_reportRayOverlappingNodex(IntPtr obj, IntPtr nodeCallback, [In] ref Vector3 raySource, [In] ref Vector3 rayTarget); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btQuantizedBvh_serialize(IntPtr obj, IntPtr o_alignedDataBuffer, uint i_dataBufferSize, bool i_swapEndian); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btQuantizedBvh_serialize2(IntPtr obj, IntPtr dataBuffer, IntPtr serializer); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_setQuantizationValues(IntPtr obj, [In] ref Vector3 bvhAabbMin, [In] ref Vector3 bvhAabbMax); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_setQuantizationValues2(IntPtr obj, [In] ref Vector3 bvhAabbMin, [In] ref Vector3 bvhAabbMax, float quantizationMargin); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_setTraversalMode(IntPtr obj, TraversalMode traversalMode); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_unQuantize(IntPtr obj, IntPtr vecIn, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btQuantizedBvh_delete(IntPtr obj); } [StructLayout(LayoutKind.Sequential)] internal struct QuantizedBvhFloatData { public Vector3FloatData BvhAabbMin; public Vector3FloatData BvhAabbMax; public Vector3FloatData BvhQuantization; public int CurNodeIndex; public int UseQuantization; public int NumContiguousLeafNodes; public int NumQuantizedContiguousNodes; public IntPtr ContiguousNodesPtr; public IntPtr QuantizedContiguousNodesPtr; public IntPtr SubTreeInfoPtr; public int TraversalMode; public int NumSubtreeHeaders; public static int Offset(string fieldName) { return Marshal.OffsetOf(typeof(QuantizedBvhFloatData), fieldName).ToInt32(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Specialized; using System.Drawing; using System.Drawing.Imaging; using System.Reflection; using System.IO; using System.Web; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Capabilities.Handlers { public class GetTextureHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_assetService; public const string DefaultFormat = "x-j2c"; // TODO: Change this to a config option const string REDIRECT_URL = null; public GetTextureHandler(string path, IAssetService assService, string name, string description) : base("GET", path, name, description) { m_assetService = assService; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string textureStr = query.GetOne("texture_id"); string format = query.GetOne("format"); //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); string[] formats; if (format != null && format != string.Empty) { formats = new string[1] { format.ToLower() }; } else { formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); if (formats.Length == 0) formats = new string[1] { DefaultFormat }; // default } // OK, we have an array with preferred formats, possibly with only one entry httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; foreach (string f in formats) { if (FetchTexture(httpRequest, httpResponse, textureID, f)) break; } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); } // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", // textureID, httpResponse.StatusCode, httpResponse.ContentLength); return null; } /// <summary> /// /// </summary> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <param name="textureID"></param> /// <param name="format"></param> /// <returns>False for "caller try another codec"; true otherwise</returns> private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format) { // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); AssetBase texture; string fullID = textureID.ToString(); if (format != DefaultFormat) fullID = fullID + "-" + format; if (!String.IsNullOrEmpty(REDIRECT_URL)) { // Only try to fetch locally cached textures. Misses are redirected texture = m_assetService.GetCached(fullID); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } WriteTextureData(httpRequest, httpResponse, texture, format); } else { string textureUrl = REDIRECT_URL + textureID.ToString(); m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); httpResponse.RedirectLocation = textureUrl; return true; } } else // no redirect { // try the cache texture = m_assetService.GetCached(fullID); if (texture == null) { // m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache"); // Fetch locally or remotely. Misses return a 404 texture = m_assetService.Get(textureID.ToString()); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } if (format == DefaultFormat) { WriteTextureData(httpRequest, httpResponse, texture, format); return true; } else { AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); newTexture.Data = ConvertTextureData(texture, format); if (newTexture.Data.Length == 0) return false; // !!! Caller try another codec, please! newTexture.Flags = AssetFlags.Collectable; newTexture.Temporary = true; newTexture.Local = true; m_assetService.Store(newTexture); WriteTextureData(httpRequest, httpResponse, newTexture, format); return true; } } } else // it was on the cache { // m_log.DebugFormat("[GETTEXTURE]: texture was in the cache"); WriteTextureData(httpRequest, httpResponse, texture, format); return true; } } // not found // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format) { string range = request.Headers.GetOne("Range"); if (!String.IsNullOrEmpty(range)) // JP2's only { // Range request int start, end; if (TryParseRange(range, out start, out end)) { // Before clamping start make sure we can satisfy it in order to avoid // sending back the last byte instead of an error status if (start >= texture.Data.Length) { // m_log.DebugFormat( // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}", // texture.ID, start, texture.Data.Length); // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously // received a very small texture may attempt to fetch bytes from the server past the // range of data that it received originally. Whether this happens appears to depend on whether // the viewer's estimation of how large a request it needs to make for certain discard levels // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable // here will cause the viewer to treat the texture as bad and never display the full resolution // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length)); // response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentType = texture.Metadata.ContentType; } else { // Handle the case where no second range value was given. This is equivalent to requesting // the rest of the entity. if (end == -1) end = int.MaxValue; end = Utils.Clamp(end, 0, texture.Data.Length - 1); start = Utils.Clamp(start, 0, end); int len = end - start + 1; // m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); // Always return PartialContent, even if the range covered the entire data length // We were accidentally sending back 404 before in this situation // https://issues.apache.org/bugzilla/show_bug.cgi?id=51878 supports sending 206 even if the // entire range is requested, and viewer 3.2.2 (and very probably earlier) seems fine with this. // // We also do not want to send back OK even if the whole range was satisfiable since this causes // HTTP textures on at least Imprudence 1.4.0-beta2 to never display the final texture quality. // if (end > maxEnd) // response.StatusCode = (int)System.Net.HttpStatusCode.OK; // else response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.ContentLength = len; response.ContentType = texture.Metadata.ContentType; response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); response.Body.Write(texture.Data, start, len); } } else { m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; } } else // JP2's or other formats { // Full content request response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.ContentLength = texture.Data.Length; if (format == DefaultFormat) response.ContentType = texture.Metadata.ContentType; else response.ContentType = "image/" + format; response.Body.Write(texture.Data, 0, texture.Data.Length); } // if (response.StatusCode < 200 || response.StatusCode > 299) // m_log.WarnFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // else // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); } /// <summary> /// Parse a range header. /// </summary> /// <remarks> /// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, /// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-). /// Where there is no value, -1 is returned. /// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1 /// for start.</remarks> /// <returns></returns> /// <param name='header'></param> /// <param name='start'>Start of the range. Undefined if this was not a number.</param> /// <param name='end'>End of the range. Will be -1 if no end specified. Undefined if there was a raw string but this was not a number.</param> private bool TryParseRange(string header, out int start, out int end) { start = end = 0; if (header.StartsWith("bytes=")) { string[] rangeValues = header.Substring(6).Split('-'); if (rangeValues.Length == 2) { if (!Int32.TryParse(rangeValues[0], out start)) return false; string rawEnd = rangeValues[1]; if (rawEnd == "") { end = -1; return true; } else if (Int32.TryParse(rawEnd, out end)) { return true; } } } start = end = 0; return false; } private byte[] ConvertTextureData(AssetBase texture, string format) { m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format); byte[] data = new byte[0]; MemoryStream imgstream = new MemoryStream(); Bitmap mTexture = new Bitmap(1, 1); ManagedImage managedImage; Image image = (Image)mTexture; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data imgstream = new MemoryStream(); // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image)) { // Save to bitmap mTexture = new Bitmap(image); EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream ImageCodecInfo codec = GetEncoderInfo("image/" + format); if (codec != null) { mTexture.Save(imgstream, codec, myEncoderParameters); // Write the stream to a byte array for output data = imgstream.ToArray(); } else m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); } } catch (Exception e) { m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message); } finally { // Reclaim memory, these are unmanaged resources // If we encountered an exception, one or more of these will be null if (mTexture != null) mTexture.Dispose(); if (image != null) image.Dispose(); if (imgstream != null) { imgstream.Close(); imgstream.Dispose(); } } return data; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using Aurora.Framework; namespace Aurora.DataManager.Migration { public interface IMigrator { string MigrationName { get; } } public class Migrator : IMigrator, IRestorePoint { private readonly Dictionary<string, string> renameSchema = new Dictionary<string, string>(); public Dictionary<string, string> renameColumns = new Dictionary<string, string>(); public List<SchemaDefinition> schema; public Version Version { get; protected set; } #region IMigrator Members public String MigrationName { get; protected set; } #endregion #region IRestorePoint Members public virtual void DoRestore(IDataConnector genericData) { RestoreTempTablesToReal(genericData); } #endregion public bool Validate(IDataConnector genericData) { if (genericData.GetAuroraVersion(MigrationName) != Version) { return false; } return DoValidate(genericData); } protected virtual bool DoValidate(IDataConnector genericData) { return true; } public IRestorePoint PrepareRestorePoint(IDataConnector genericData) { DoPrepareRestorePoint(genericData); return this; } protected virtual void DoPrepareRestorePoint(IDataConnector genericData) { } public void Migrate(IDataConnector genericData) { DoMigrate(genericData); genericData.WriteAuroraVersion(Version, MigrationName); } protected virtual void DoMigrate(IDataConnector genericData) { } public void CreateDefaults(IDataConnector genericData) { DoCreateDefaults(genericData); genericData.WriteAuroraVersion(Version, MigrationName); } protected virtual void DoCreateDefaults(IDataConnector genericData) { } protected ColumnDefinition[] ColDefs(params ColumnDefinition[] defs) { return defs; } protected ColumnDefinition ColDef(string name, ColumnTypes columnType) { ColumnTypeDef type = new ColumnTypeDef(); switch (columnType) { case ColumnTypes.Blob: type.Type = ColumnType.Blob; break; case ColumnTypes.Char32: type.Type = ColumnType.Char; type.Size = 32; break; case ColumnTypes.Char36: type.Type = ColumnType.Char; type.Size = 36; break; case ColumnTypes.Char5: type.Type = ColumnType.Char; type.Size = 5; break; case ColumnTypes.Date: type.Type = ColumnType.Date; break; case ColumnTypes.DateTime: type.Type = ColumnType.DateTime; break; case ColumnTypes.Double: type.Type = ColumnType.Double; break; case ColumnTypes.Float: type.Type = ColumnType.Float; break; case ColumnTypes.Integer11: type.Type = ColumnType.Integer; type.Size = 11; break; case ColumnTypes.Integer30: type.Type = ColumnType.Integer; type.Size = 30; break; case ColumnTypes.LongBlob: type.Type = ColumnType.LongBlob; break; case ColumnTypes.LongText: type.Type = ColumnType.LongText; break; case ColumnTypes.MediumText: type.Type = ColumnType.MediumText; break; case ColumnTypes.String: type.Type = ColumnType.Text; break; case ColumnTypes.String1: type.Type = ColumnType.String; type.Size = 1; break; case ColumnTypes.String10: type.Type = ColumnType.String; type.Size = 10; break; case ColumnTypes.String100: type.Type = ColumnType.String; type.Size = 100; break; case ColumnTypes.String1024: type.Type = ColumnType.String; type.Size = 1024; break; case ColumnTypes.String128: type.Type = ColumnType.String; type.Size = 128; break; case ColumnTypes.String16: type.Type = ColumnType.String; type.Size = 16; break; case ColumnTypes.String2: type.Type = ColumnType.String; type.Size = 2; break; case ColumnTypes.String255: type.Type = ColumnType.String; type.Size = 255; break; case ColumnTypes.String30: type.Type = ColumnType.String; type.Size = 30; break; case ColumnTypes.String32: type.Type = ColumnType.String; type.Size = 32; break; case ColumnTypes.String36: type.Type = ColumnType.String; type.Size = 36; break; case ColumnTypes.String45: type.Type = ColumnType.String; type.Size = 45; break; case ColumnTypes.String50: type.Type = ColumnType.String; type.Size = 50; break; case ColumnTypes.String512: type.Type = ColumnType.String; type.Size = 512; break; case ColumnTypes.String64: type.Type = ColumnType.String; type.Size = 64; break; case ColumnTypes.String8196: type.Type = ColumnType.String; type.Size = 8196; break; case ColumnTypes.Text: type.Type = ColumnType.Text; break; case ColumnTypes.TinyInt1: type.Type = ColumnType.TinyInt; type.Size = 1; break; case ColumnTypes.TinyInt4: type.Type = ColumnType.TinyInt; type.Size = 4; break; default: type.Type = ColumnType.Unknown; break; } return new ColumnDefinition {Name = name, Type = type}; } protected IndexDefinition[] IndexDefs(params IndexDefinition[] defs) { return defs; } protected IndexDefinition IndexDef(string[] fields, IndexType indexType) { return new IndexDefinition { Fields = fields, Type = indexType }; } protected void AddSchema(string table, ColumnDefinition[] definitions) { AddSchema(table, definitions, new IndexDefinition[0]); } protected void AddSchema(string table, ColumnDefinition[] definitions, IndexDefinition[] indexes) { schema.Add(new SchemaDefinition(table, definitions, indexes)); } protected void RenameSchema(string oldTable, string newTable) { renameSchema.Add(oldTable, newTable); } protected void RemoveSchema(string table) { //Remove all of the tables that have this name schema.RemoveAll(delegate(SchemaDefinition r) { if (r.Name == table) return true; return false; }); } protected void EnsureAllTablesInSchemaExist(IDataConnector genericData) { foreach (System.Collections.Generic.KeyValuePair<string, string> r in renameSchema) { genericData.RenameTable(r.Key, r.Value); } foreach (var s in schema) { genericData.EnsureTableExists(s.Name, s.Columns, s.Indices, renameColumns); } } protected bool TestThatAllTablesValidate(IDataConnector genericData) { #if (!ISWIN) foreach (SchemaDefinition s in schema) { if (!genericData.VerifyTableExists(s.Name, s.Columns, s.Indices)) return false; } return true; #else return schema.All(s => genericData.VerifyTableExists(s.Name, s.Columns, s.Indices)); #endif } public bool DebugTestThatAllTablesValidate(IDataConnector genericData, out SchemaDefinition reason) { reason = null; #if (!ISWIN) foreach (var s in schema) { if (!genericData.VerifyTableExists(s.Name, s.Columns, s.Indices)) { reason = s; return false; } } #else foreach (var s in schema.Where(s => !genericData.VerifyTableExists(s.Name, s.Columns, s.Indices))) { reason = s; return false; } #endif return true; } protected void CopyAllTablesToTempVersions(IDataConnector genericData) { foreach (var s in schema) { CopyTableToTempVersion(genericData, s.Name, s.Columns, s.Indices); } } protected void RestoreTempTablesToReal(IDataConnector genericData) { foreach (var s in schema) { RestoreTempTableToReal(genericData, s.Name, s.Columns, s.Indices); } } private void CopyTableToTempVersion(IDataConnector genericData, string tablename, ColumnDefinition[] columnDefinitions, IndexDefinition[] indexDefinitions) { genericData.CopyTableToTable(tablename, GetTempTableNameFromTableName(tablename), columnDefinitions, indexDefinitions); } private string GetTempTableNameFromTableName(string tablename) { return tablename + "_temp"; } private void RestoreTempTableToReal(IDataConnector genericData, string tablename, ColumnDefinition[] columnDefinitions, IndexDefinition[] indexDefinitions) { genericData.CopyTableToTable(GetTempTableNameFromTableName(GetTempTableNameFromTableName(tablename)), tablename, columnDefinitions, indexDefinitions); } public void ClearRestorePoint(IDataConnector genericData) { foreach (var s in schema) { DeleteTempVersion(genericData, s.Name); } } private void DeleteTempVersion(IDataConnector genericData, string tableName) { string tempTableName = GetTempTableNameFromTableName(tableName); if (genericData.TableExists(tempTableName)) { genericData.DropTable(tempTableName); } } public virtual void FinishedMigration(IDataConnector genericData) { } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Compute.Fluent { using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.Definition; using Microsoft.Azure.Management.Compute.Fluent.VirtualMachineScaleSetExtension.UpdateDefinition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResourceActions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Collections.Generic; /// <summary> /// Implementation of VirtualMachineScaleSetExtension. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmNvbXB1dGUuaW1wbGVtZW50YXRpb24uVmlydHVhbE1hY2hpbmVTY2FsZVNldEV4dGVuc2lvbkltcGw= internal partial class VirtualMachineScaleSetExtensionImpl : ChildResource<Models.VirtualMachineScaleSetExtensionInner, VirtualMachineScaleSetImpl, IVirtualMachineScaleSet>, IVirtualMachineScaleSetExtension, IDefinition<VirtualMachineScaleSet.Definition.IWithCreate>, IUpdateDefinition<VirtualMachineScaleSet.Update.IWithApply>, VirtualMachineScaleSetExtension.Update.IUpdate { ///GENMHASH:F8C651BFA96A5C2B1BE72B024FE8AEEF:815BF11DE6127502A0AFCB14BE98F20E internal VirtualMachineScaleSetExtensionImpl(Models.VirtualMachineScaleSetExtensionInner inner, VirtualMachineScaleSetImpl parent) : base(inner, parent) { } ///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:61C1065B307679F3800C701AE0D87070 public override string Name() { return Inner.Name; } ///GENMHASH:06BBF1077FAA38CC78AFC6E69E23FB58:2E1C21AC97868331579C4445DFF8B199 public string PublisherName() { return Inner.Publisher; } ///GENMHASH:062496BB5D915E140ABE560B4E1D89B1:605B8FC69F180AFC7CE18C754024B46C public string TypeName() { return Inner.Type; } ///GENMHASH:59C1C6208A5C449165066C7E1FDE11ED:D218DCBF15733B59D5054B1545063FEA public string VersionName() { return Inner.TypeHandlerVersion; } ///GENMHASH:38030CBAE29B9F2F38D72F365E2E629A:E94F2D3DAC3B970EABC385A12F44BB26 public bool AutoUpgradeMinorVersionEnabled() { return Inner.AutoUpgradeMinorVersion.Value; } ///GENMHASH:E8B034BE63B3FB3349E5BCFC76224AF8:CA9E3FB93CD214E58089AA8C2C20B7A3 public IReadOnlyDictionary<string, object> PublicSettings() { if (Inner.Settings == null) { return new Dictionary<string, object>(); } else if (Inner.Settings is JObject) { var jObject = (JObject)(Inner.Settings); return jObject.ToObject<Dictionary<string, object>>(); } else { return this.Inner.Settings as Dictionary<string, object>; } } ///GENMHASH:316D51C271754F67D70A4782C8F17E3A:9790D012FA64E47343F12DB13F0AA212 public string PublicSettingsAsJsonString() { if (this.PublicSettings() != null) { return JsonConvert.SerializeObject(this.PublicSettings()); } return null; } ///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:220D4662AAC7DF3BEFAF2B253278E85C public string ProvisioningState() { return Inner.ProvisioningState; } ///GENMHASH:467F635EADCCCC617A72CEB57E5B3D41:7B7B2063CA85FFEC8E5F9CF53A22CED0 public VirtualMachineScaleSetExtensionImpl WithMinorVersionAutoUpgrade() { Inner.AutoUpgradeMinorVersion = true; return this; } ///GENMHASH:23B0698FE3BB00936E77BFAAD4E8C173:2897633350A3881BCCEECEB8CBDCFF63 public VirtualMachineScaleSetExtensionImpl WithoutMinorVersionAutoUpgrade() { Inner.AutoUpgradeMinorVersion = false; return this; } ///GENMHASH:FCA44D692D2CBD47AF19A7B5D9CEB263:E932E565C84B68E30D666C77ECF8F4E9 public VirtualMachineScaleSetExtensionImpl WithImage(IVirtualMachineExtensionImage image) { Inner.Publisher = image.PublisherName; Inner.Type = image.TypeName; Inner.TypeHandlerVersion = image.VersionName; return this; } ///GENMHASH:D09614E022482293C9A2EEE2C6E4098E:86E8D4D3B2BDB9EEBA09E6F348394801 public VirtualMachineScaleSetExtensionImpl WithPublisher(string extensionImagePublisherName) { Inner.Publisher = extensionImagePublisherName; return this; } ///GENMHASH:F4E714A8C40DF6CD0AE34FBA3BC4C770:79A077AE3BFC0D04AB2B4B8492338A57 public VirtualMachineScaleSetExtensionImpl WithPublicSetting(string key, object value) { if (this.EnsurePublicSettings().ContainsKey(key)) { this.EnsurePublicSettings()[key] = value; } else { this.EnsurePublicSettings().Add(key, value); } return this; } ///GENMHASH:4E0AB82616606C4EEBD304EE7CA95448:C69FF63CB6446E393F7AC97CBA0B0631 public VirtualMachineScaleSetExtensionImpl WithProtectedSetting(string key, object value) { if (this.EnsureProtectedSettings().ContainsKey(key)) { this.EnsureProtectedSettings()[key] = value; } else { this.EnsureProtectedSettings().Add(key, value); } return this; } ///GENMHASH:1D0CC09D7108E079E0215F59B279BCA8:2D5C9E48A5341416C6BDFB5BC6014FAE public VirtualMachineScaleSetExtensionImpl WithPublicSettings(IDictionary<string, object> settings) { this.EnsurePublicSettings().Clear(); foreach (var entry in settings) { this.EnsurePublicSettings().Add(entry.Key, entry.Value); } return this; } ///GENMHASH:47A9BC4FAD4EEB04D8AA50F23064B253:8123EC3071CE1111531A48B680D93AAF public VirtualMachineScaleSetExtensionImpl WithProtectedSettings(IDictionary<string, object> settings) { this.EnsureProtectedSettings().Clear(); foreach (var entry in settings) { this.EnsureProtectedSettings().Add(entry.Key, entry.Value); } return this; } ///GENMHASH:1B55955986893FF406609C78FCC96FEE:1DF9D56E59684CD39EB87D1AF4CCF411 public VirtualMachineScaleSetExtensionImpl WithType(string extensionImageTypeName) { Inner.Type = extensionImageTypeName; return this; } ///GENMHASH:5A056156A7C92738B7A05BFFB861E1B4:DA8B164AFF802F7E1F62BE36FA742A8D public VirtualMachineScaleSetExtensionImpl WithVersion(string extensionImageVersionName) { Inner.TypeHandlerVersion = extensionImageVersionName; return this; } ///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:A7E70E6A25505D4B6F0EF5B2C0549275 public VirtualMachineScaleSetImpl Attach() { return Parent.WithExtension(this); } // // Note: Internal handling of VMSS extensions are different from VM extension. // VM extensions are external child resources so only new, added or updated extensions will be committed. // // VMSS extensions are inline child resources hence all extensions are always part of VMSS PUT payload // i.e including the one that user didn't choose to update. EnsurePublicSettings and EnsureProtectedSettings // are used to ensure we initialize settings/protectedSettings of an extension only if user choose to update it. // private IDictionary<string, object> EnsurePublicSettings() { if (Inner.Settings == null) { Inner.Settings = new Dictionary<string, object>(); return (Dictionary<string, object>)Inner.Settings; } else if (Inner.Settings is JObject) { var jObject = (JObject)(Inner.Settings); Inner.Settings = jObject.ToObject<Dictionary<string, object>>(); return (Dictionary<string, object>)Inner.Settings; } else { return (Dictionary<string, object>)Inner.Settings; } } private IDictionary<string, object> EnsureProtectedSettings() { if (Inner.ProtectedSettings == null) { Inner.ProtectedSettings = new Dictionary<string, object>(); return (Dictionary<string, object>)Inner.ProtectedSettings; } else if (Inner.ProtectedSettings is JObject) { var jObject = (JObject)(Inner.ProtectedSettings); Inner.ProtectedSettings = jObject.ToObject<Dictionary<string, object>>(); return (Dictionary<string, object>)Inner.ProtectedSettings; } else { return Inner.ProtectedSettings as Dictionary<string, object>; } } VirtualMachineScaleSet.Update.IUpdate ISettable<VirtualMachineScaleSet.Update.IUpdate>.Parent() { return base.Parent; } } }
using System; using System.Collections.Generic; using Android.Content; using Android.Graphics; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace MyVote.UI.Extensions { /// <summary> /// Interface of TypefaceCaches /// </summary> public interface ITypefaceCache { /// <summary> /// Removes typeface from cache /// </summary> /// <param name="key">Key.</param> /// <param name="typeface">Typeface.</param> void StoreTypeface(string key, Typeface typeface); void RemoveTypeface(string key); Typeface RetrieveTypeface(string key); } /// <summary> /// TypefaceCache caches used typefaces for performance and memory reasons. /// Typeface cache is singleton shared through execution of the application. /// You can replace default implementation of the cache by implementing ITypefaceCache /// interface and setting instance of your cache to static property SharedCache of this class /// </summary> public static class TypefaceCache { private static ITypefaceCache sharedCache; /// <summary> /// Returns the shared typeface cache. /// </summary> /// <value>The shared cache.</value> public static ITypefaceCache SharedCache { get { if (sharedCache == null) { sharedCache = new DefaultTypefaceCache(); } return sharedCache; } set { if (sharedCache != null && sharedCache.GetType() == typeof(DefaultTypefaceCache)) { ((DefaultTypefaceCache)sharedCache).PurgeCache(); } sharedCache = value; } } } /// <summary> /// Default implementation of the typeface cache. /// </summary> internal class DefaultTypefaceCache : ITypefaceCache { private Dictionary<string, Typeface> _cacheDict; public DefaultTypefaceCache() { _cacheDict = new Dictionary<string, Typeface>(); } public Typeface RetrieveTypeface(string key) { if (_cacheDict.ContainsKey(key)) { return _cacheDict[key]; } else { return null; } } public void StoreTypeface(string key, Typeface typeface) { _cacheDict[key] = typeface; } public void RemoveTypeface(string key) { _cacheDict.Remove(key); } public void PurgeCache() { _cacheDict = new Dictionary<string, Typeface>(); } } /// <summary> /// Andorid specific extensions for Font class. /// </summary> public static class FontExtensions { /// <summary> /// This method returns typeface for given typeface using following rules: /// 1. Lookup in the cache /// 2. If not found, look in the assets in the fonts folder. Save your font under its FontFamily name. /// If no extension is written in the family name .ttf is asumed /// 3. If not found look in the files under fonts/ folder /// If no extension is written in the family name .ttf is asumed /// 4. If not found, try to return typeface from Xamarin.Forms ToTypeface() method /// 5. If not successfull, return Typeface.Default /// </summary> /// <returns>The extended typeface.</returns> /// <param name="font">Font</param> /// <param name="context">Android Context</param> public static Typeface ToExtendedTypeface(this Font font, Context context) { Typeface typeface = null; //1. Lookup in the cache var hashKey = font.ToHasmapKey(); typeface = TypefaceCache.SharedCache.RetrieveTypeface(hashKey); #if DEBUG if (typeface != null) Console.WriteLine("Typeface for font {0} found in cache", font); #endif //2. If not found, try custom asset folder if (typeface == null && !string.IsNullOrEmpty(font.FontFamily)) { string filename = font.FontFamily; //if no extension given then assume and add .ttf if (filename.LastIndexOf(".", System.StringComparison.Ordinal) != filename.Length - 4) { filename = string.Format("{0}.ttf", filename); } try { var path = "fonts/" + filename; #if DEBUG Console.WriteLine("Lookking for font file: {0}", path); #endif typeface = Typeface.CreateFromAsset(context.Assets, path); #if DEBUG Console.WriteLine("Found in assets and cached."); #endif } catch (Exception ex) { #if DEBUG Console.WriteLine("not found in assets. Exception: {0}", ex); Console.WriteLine("Trying creation from file"); #endif try { typeface = Typeface.CreateFromFile("fonts/" + filename); #if DEBUG Console.WriteLine("Found in file and cached."); #endif } catch (Exception ex1) { #if DEBUG Console.WriteLine("not found by file. Exception: {0}", ex1); Console.WriteLine("Trying creation using Xamarin.Forms implementation"); #endif } } } //3. If not found, fall back to default Xamarin.Forms implementation to load system font if (typeface == null) { typeface = font.ToTypeface(); } if (typeface == null) { #if DEBUG Console.WriteLine("Falling back to default typeface"); #endif typeface = Typeface.Default; } //Store in cache TypefaceCache.SharedCache.StoreTypeface(hashKey, typeface); return typeface; } /// <summary> /// Provides unique identifier for the given font. /// </summary> /// <returns>Unique string identifier for the given font</returns> /// <param name="font">Font.</param> private static string ToHasmapKey(this Font font) { return string.Format("{0}.{1}.{2}.{3}", font.FontFamily, font.FontSize, font.NamedSize, (int)font.FontAttributes); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Avalonia.Platform; using Avalonia.Utilities; #nullable enable namespace Avalonia.Shared.PlatformSupport { /// <summary> /// Loads assets compiled into the application binary. /// </summary> public class AssetLoader : IAssetLoader { private const string AvaloniaResourceName = "!AvaloniaResources"; private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache = new Dictionary<string, AssemblyDescriptor>(); private AssemblyDescriptor? _defaultResmAssembly; /// <summary> /// Initializes a new instance of the <see cref="AssetLoader"/> class. /// </summary> /// <param name="assembly"> /// The default assembly from which to load resm: assets for which no assembly is specified. /// </param> public AssetLoader(Assembly? assembly = null) { if (assembly == null) assembly = Assembly.GetEntryAssembly(); if (assembly != null) _defaultResmAssembly = new AssemblyDescriptor(assembly); } /// <summary> /// Sets the default assembly from which to load assets for which no assembly is specified. /// </summary> /// <param name="assembly">The default assembly.</param> public void SetDefaultAssembly(Assembly assembly) { _defaultResmAssembly = new AssemblyDescriptor(assembly); } /// <summary> /// Checks if an asset with the specified URI exists. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns>True if the asset could be found; otherwise false.</returns> public bool Exists(Uri uri, Uri? baseUri = null) { return GetAsset(uri, baseUri) != null; } /// <summary> /// Opens the asset with the requested URI. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns>A stream containing the asset contents.</returns> /// <exception cref="FileNotFoundException"> /// The asset could not be found. /// </exception> public Stream Open(Uri uri, Uri? baseUri = null) => OpenAndGetAssembly(uri, baseUri).Item1; /// <summary> /// Opens the asset with the requested URI and returns the asset stream and the /// assembly containing the asset. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri"> /// A base URI to use if <paramref name="uri"/> is relative. /// </param> /// <returns> /// The stream containing the resource contents together with the assembly. /// </returns> /// <exception cref="FileNotFoundException"> /// The asset could not be found. /// </exception> public (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri? baseUri = null) { var asset = GetAsset(uri, baseUri); if (asset == null) { throw new FileNotFoundException($"The resource {uri} could not be found."); } return (asset.GetStream(), asset.Assembly); } public Assembly? GetAssembly(Uri uri, Uri? baseUri) { if (!uri.IsAbsoluteUri && baseUri != null) uri = new Uri(baseUri, uri); return GetAssembly(uri)?.Assembly; } /// <summary> /// Gets all assets of a folder and subfolders that match specified uri. /// </summary> /// <param name="uri">The URI.</param> /// <param name="baseUri">Base URI that is used if <paramref name="uri"/> is relative.</param> /// <returns>All matching assets as a tuple of the absolute path to the asset and the assembly containing the asset</returns> public IEnumerable<Uri> GetAssets(Uri uri, Uri? baseUri) { if (uri.IsAbsoluteUri && uri.Scheme == "resm") { var assembly = GetAssembly(uri); return assembly?.Resources?.Where(x => x.Key.Contains(uri.AbsolutePath)) .Select(x =>new Uri($"resm:{x.Key}?assembly={assembly.Name}")) ?? Enumerable.Empty<Uri>(); } uri = EnsureAbsolute(uri, baseUri); if (uri.Scheme == "avares") { var (asm, path) = GetResAsmAndPath(uri); if (asm == null) { throw new ArgumentException( "No default assembly, entry assembly or explicit assembly specified; " + "don't know where to look up for the resource, try specifying assembly explicitly."); } if (asm?.AvaloniaResources == null) return Enumerable.Empty<Uri>(); path = path.TrimEnd('/') + '/'; return asm.AvaloniaResources.Where(r => r.Key.StartsWith(path)) .Select(x => new Uri($"avares://{asm.Name}{x.Key}")); } return Enumerable.Empty<Uri>(); } private Uri EnsureAbsolute(Uri uri, Uri? baseUri) { if (uri.IsAbsoluteUri) return uri; if(baseUri == null) throw new ArgumentException($"Relative uri {uri} without base url"); if (!baseUri.IsAbsoluteUri) throw new ArgumentException($"Base uri {baseUri} is relative"); if (baseUri.Scheme == "resm") throw new ArgumentException( $"Relative uris for 'resm' scheme aren't supported; {baseUri} uses resm"); return new Uri(baseUri, uri); } private IAssetDescriptor? GetAsset(Uri uri, Uri? baseUri) { if (uri.IsAbsoluteUri && uri.Scheme == "resm") { var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultResmAssembly; if (asm == null) { throw new ArgumentException( "No default assembly, entry assembly or explicit assembly specified; " + "don't know where to look up for the resource, try specifying assembly explicitly."); } var resourceKey = uri.AbsolutePath; IAssetDescriptor? rv = null; asm.Resources?.TryGetValue(resourceKey, out rv); return rv; } uri = EnsureAbsolute(uri, baseUri); if (uri.Scheme == "avares") { var (asm, path) = GetResAsmAndPath(uri); if (asm.AvaloniaResources == null) return null; asm.AvaloniaResources.TryGetValue(path, out var desc); return desc; } throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri)); } private (AssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri) { var asm = GetAssembly(uri.Authority); return (asm, uri.AbsolutePath); } private AssemblyDescriptor? GetAssembly(Uri? uri) { if (uri != null) { if (!uri.IsAbsoluteUri) return null; if (uri.Scheme == "avares") return GetResAsmAndPath(uri).asm; if (uri.Scheme == "resm") { var qs = ParseQueryString(uri); if (qs.TryGetValue("assembly", out var assemblyName)) { return GetAssembly(assemblyName); } } } return null; } private AssemblyDescriptor GetAssembly(string name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (!AssemblyNameCache.TryGetValue(name, out var rv)) { var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name); if (match != null) { AssemblyNameCache[name] = rv = new AssemblyDescriptor(match); } else { // iOS does not support loading assemblies dynamically! // #if __IOS__ throw new InvalidOperationException( $"Assembly {name} needs to be referenced and explicitly loaded before loading resources"); #else name = Uri.UnescapeDataString(name); AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name)); #endif } } return rv; } private Dictionary<string, string> ParseQueryString(Uri uri) { return uri.Query.TrimStart('?') .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => p.Split('=')) .ToDictionary(p => p[0], p => p[1]); } private interface IAssetDescriptor { Stream GetStream(); Assembly Assembly { get; } } private class AssemblyResourceDescriptor : IAssetDescriptor { private readonly Assembly _asm; private readonly string _name; public AssemblyResourceDescriptor(Assembly asm, string name) { _asm = asm; _name = name; } public Stream GetStream() { var s = _asm.GetManifestResourceStream(_name); return s ?? throw new InvalidOperationException($"Could not find manifest resource stream '{_name}',"); } public Assembly Assembly => _asm; } private class AvaloniaResourceDescriptor : IAssetDescriptor { private readonly int _offset; private readonly int _length; public Assembly Assembly { get; } public AvaloniaResourceDescriptor(Assembly asm, int offset, int length) { _offset = offset; _length = length; Assembly = asm; } public Stream GetStream() { var s = Assembly.GetManifestResourceStream(AvaloniaResourceName) ?? throw new InvalidOperationException($"Could not find manifest resource stream '{AvaloniaResourceName}',"); return new SlicedStream(s, _offset, _length); } } class SlicedStream : Stream { private readonly Stream _baseStream; private readonly int _from; public SlicedStream(Stream baseStream, int from, int length) { Length = length; _baseStream = baseStream; _from = from; _baseStream.Position = from; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return _baseStream.Read(buffer, offset, (int)Math.Min(count, Length - Position)); } public override long Seek(long offset, SeekOrigin origin) { if (origin == SeekOrigin.Begin) Position = offset; if (origin == SeekOrigin.End) Position = _from + Length + offset; if (origin == SeekOrigin.Current) Position = Position + offset; return Position; } public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override bool CanRead => true; public override bool CanSeek => _baseStream.CanRead; public override bool CanWrite => false; public override long Length { get; } public override long Position { get => _baseStream.Position - _from; set => _baseStream.Position = value + _from; } protected override void Dispose(bool disposing) { if (disposing) _baseStream.Dispose(); } public override void Close() => _baseStream.Close(); } private class AssemblyDescriptor { public AssemblyDescriptor(Assembly assembly) { Assembly = assembly; if (assembly != null) { Resources = assembly.GetManifestResourceNames() .ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n)); Name = assembly.GetName().Name; using (var resources = assembly.GetManifestResourceStream(AvaloniaResourceName)) { if (resources != null) { Resources.Remove(AvaloniaResourceName); var indexLength = new BinaryReader(resources).ReadInt32(); var index = AvaloniaResourcesIndexReaderWriter.Read(new SlicedStream(resources, 4, indexLength)); var baseOffset = indexLength + 4; AvaloniaResources = index.ToDictionary(r => "/" + r.Path!.TrimStart('/'), r => (IAssetDescriptor) new AvaloniaResourceDescriptor(assembly, baseOffset + r.Offset, r.Size)); } } } } public Assembly Assembly { get; } public Dictionary<string, IAssetDescriptor>? Resources { get; } public Dictionary<string, IAssetDescriptor>? AvaloniaResources { get; } public string? Name { get; } } public static void RegisterResUriParsers() { if (!UriParser.IsKnownScheme("avares")) UriParser.Register(new GenericUriParser( GenericUriParserOptions.GenericAuthority | GenericUriParserOptions.NoUserInfo | GenericUriParserOptions.NoPort | GenericUriParserOptions.NoQuery | GenericUriParserOptions.NoFragment), "avares", -1); } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IEmployeeOriginalData : ISchemaBaseOriginalData { string NationalIDNumber { get; } int LoginID { get; } string JobTitle { get; } System.DateTime BirthDate { get; } string MaritalStatus { get; } string Gender { get; } System.DateTime HireDate { get; } bool SalariedFlag { get; } int VacationHours { get; } int SickLeaveHours { get; } bool Currentflag { get; } string rowguid { get; } EmployeePayHistory EmployeePayHistory { get; } SalesPerson SalesPerson { get; } EmployeeDepartmentHistory EmployeeDepartmentHistory { get; } Shift Shift { get; } JobCandidate JobCandidate { get; } IEnumerable<Vendor> Vendors { get; } } public partial class Employee : OGM<Employee, Employee.EmployeeData, System.String>, ISchemaBase, INeo4jBase, IEmployeeOriginalData { #region Initialize static Employee() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, Employee> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.EmployeeAlias, IWhereQuery> query) { q.EmployeeAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.Employee.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"Employee => NationalIDNumber : {this.NationalIDNumber}, LoginID : {this.LoginID}, JobTitle : {this.JobTitle}, BirthDate : {this.BirthDate}, MaritalStatus : {this.MaritalStatus}, Gender : {this.Gender}, HireDate : {this.HireDate}, SalariedFlag : {this.SalariedFlag}, VacationHours : {this.VacationHours}, SickLeaveHours : {this.SickLeaveHours}, Currentflag : {this.Currentflag}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new EmployeeData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.NationalIDNumber == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the NationalIDNumber cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.LoginID == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the LoginID cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.JobTitle == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the JobTitle cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.BirthDate == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the BirthDate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.MaritalStatus == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the MaritalStatus cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Gender == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the Gender cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.HireDate == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the HireDate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.SalariedFlag == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the SalariedFlag cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.VacationHours == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the VacationHours cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.SickLeaveHours == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the SickLeaveHours cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Currentflag == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the Currentflag cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.rowguid == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save Employee with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class EmployeeData : Data<System.String> { public EmployeeData() { } public EmployeeData(EmployeeData data) { NationalIDNumber = data.NationalIDNumber; LoginID = data.LoginID; JobTitle = data.JobTitle; BirthDate = data.BirthDate; MaritalStatus = data.MaritalStatus; Gender = data.Gender; HireDate = data.HireDate; SalariedFlag = data.SalariedFlag; VacationHours = data.VacationHours; SickLeaveHours = data.SickLeaveHours; Currentflag = data.Currentflag; rowguid = data.rowguid; EmployeePayHistory = data.EmployeePayHistory; SalesPerson = data.SalesPerson; EmployeeDepartmentHistory = data.EmployeeDepartmentHistory; Shift = data.Shift; JobCandidate = data.JobCandidate; Vendors = data.Vendors; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "Employee"; EmployeePayHistory = new EntityCollection<EmployeePayHistory>(Wrapper, Members.EmployeePayHistory); SalesPerson = new EntityCollection<SalesPerson>(Wrapper, Members.SalesPerson); EmployeeDepartmentHistory = new EntityCollection<EmployeeDepartmentHistory>(Wrapper, Members.EmployeeDepartmentHistory); Shift = new EntityCollection<Shift>(Wrapper, Members.Shift); JobCandidate = new EntityCollection<JobCandidate>(Wrapper, Members.JobCandidate, item => { if (Members.JobCandidate.Events.HasRegisteredChangeHandlers) { object loadHack = item.Employee; } }); Vendors = new EntityCollection<Vendor>(Wrapper, Members.Vendors, item => { if (Members.Vendors.Events.HasRegisteredChangeHandlers) { object loadHack = item.Employee; } }); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("NationalIDNumber", NationalIDNumber); dictionary.Add("LoginID", Conversion<int, long>.Convert(LoginID)); dictionary.Add("JobTitle", JobTitle); dictionary.Add("BirthDate", Conversion<System.DateTime, long>.Convert(BirthDate)); dictionary.Add("MaritalStatus", MaritalStatus); dictionary.Add("Gender", Gender); dictionary.Add("HireDate", Conversion<System.DateTime, long>.Convert(HireDate)); dictionary.Add("SalariedFlag", SalariedFlag); dictionary.Add("VacationHours", Conversion<int, long>.Convert(VacationHours)); dictionary.Add("SickLeaveHours", Conversion<int, long>.Convert(SickLeaveHours)); dictionary.Add("Currentflag", Currentflag); dictionary.Add("rowguid", rowguid); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("NationalIDNumber", out value)) NationalIDNumber = (string)value; if (properties.TryGetValue("LoginID", out value)) LoginID = Conversion<long, int>.Convert((long)value); if (properties.TryGetValue("JobTitle", out value)) JobTitle = (string)value; if (properties.TryGetValue("BirthDate", out value)) BirthDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("MaritalStatus", out value)) MaritalStatus = (string)value; if (properties.TryGetValue("Gender", out value)) Gender = (string)value; if (properties.TryGetValue("HireDate", out value)) HireDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("SalariedFlag", out value)) SalariedFlag = (bool)value; if (properties.TryGetValue("VacationHours", out value)) VacationHours = Conversion<long, int>.Convert((long)value); if (properties.TryGetValue("SickLeaveHours", out value)) SickLeaveHours = Conversion<long, int>.Convert((long)value); if (properties.TryGetValue("Currentflag", out value)) Currentflag = (bool)value; if (properties.TryGetValue("rowguid", out value)) rowguid = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IEmployee public string NationalIDNumber { get; set; } public int LoginID { get; set; } public string JobTitle { get; set; } public System.DateTime BirthDate { get; set; } public string MaritalStatus { get; set; } public string Gender { get; set; } public System.DateTime HireDate { get; set; } public bool SalariedFlag { get; set; } public int VacationHours { get; set; } public int SickLeaveHours { get; set; } public bool Currentflag { get; set; } public string rowguid { get; set; } public EntityCollection<EmployeePayHistory> EmployeePayHistory { get; private set; } public EntityCollection<SalesPerson> SalesPerson { get; private set; } public EntityCollection<EmployeeDepartmentHistory> EmployeeDepartmentHistory { get; private set; } public EntityCollection<Shift> Shift { get; private set; } public EntityCollection<JobCandidate> JobCandidate { get; private set; } public EntityCollection<Vendor> Vendors { get; private set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IEmployee public string NationalIDNumber { get { LazyGet(); return InnerData.NationalIDNumber; } set { if (LazySet(Members.NationalIDNumber, InnerData.NationalIDNumber, value)) InnerData.NationalIDNumber = value; } } public int LoginID { get { LazyGet(); return InnerData.LoginID; } set { if (LazySet(Members.LoginID, InnerData.LoginID, value)) InnerData.LoginID = value; } } public string JobTitle { get { LazyGet(); return InnerData.JobTitle; } set { if (LazySet(Members.JobTitle, InnerData.JobTitle, value)) InnerData.JobTitle = value; } } public System.DateTime BirthDate { get { LazyGet(); return InnerData.BirthDate; } set { if (LazySet(Members.BirthDate, InnerData.BirthDate, value)) InnerData.BirthDate = value; } } public string MaritalStatus { get { LazyGet(); return InnerData.MaritalStatus; } set { if (LazySet(Members.MaritalStatus, InnerData.MaritalStatus, value)) InnerData.MaritalStatus = value; } } public string Gender { get { LazyGet(); return InnerData.Gender; } set { if (LazySet(Members.Gender, InnerData.Gender, value)) InnerData.Gender = value; } } public System.DateTime HireDate { get { LazyGet(); return InnerData.HireDate; } set { if (LazySet(Members.HireDate, InnerData.HireDate, value)) InnerData.HireDate = value; } } public bool SalariedFlag { get { LazyGet(); return InnerData.SalariedFlag; } set { if (LazySet(Members.SalariedFlag, InnerData.SalariedFlag, value)) InnerData.SalariedFlag = value; } } public int VacationHours { get { LazyGet(); return InnerData.VacationHours; } set { if (LazySet(Members.VacationHours, InnerData.VacationHours, value)) InnerData.VacationHours = value; } } public int SickLeaveHours { get { LazyGet(); return InnerData.SickLeaveHours; } set { if (LazySet(Members.SickLeaveHours, InnerData.SickLeaveHours, value)) InnerData.SickLeaveHours = value; } } public bool Currentflag { get { LazyGet(); return InnerData.Currentflag; } set { if (LazySet(Members.Currentflag, InnerData.Currentflag, value)) InnerData.Currentflag = value; } } public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } } public EmployeePayHistory EmployeePayHistory { get { return ((ILookupHelper<EmployeePayHistory>)InnerData.EmployeePayHistory).GetItem(null); } set { if (LazySet(Members.EmployeePayHistory, ((ILookupHelper<EmployeePayHistory>)InnerData.EmployeePayHistory).GetItem(null), value)) ((ILookupHelper<EmployeePayHistory>)InnerData.EmployeePayHistory).SetItem(value, null); } } public SalesPerson SalesPerson { get { return ((ILookupHelper<SalesPerson>)InnerData.SalesPerson).GetItem(null); } set { if (LazySet(Members.SalesPerson, ((ILookupHelper<SalesPerson>)InnerData.SalesPerson).GetItem(null), value)) ((ILookupHelper<SalesPerson>)InnerData.SalesPerson).SetItem(value, null); } } public EmployeeDepartmentHistory EmployeeDepartmentHistory { get { return ((ILookupHelper<EmployeeDepartmentHistory>)InnerData.EmployeeDepartmentHistory).GetItem(null); } set { if (LazySet(Members.EmployeeDepartmentHistory, ((ILookupHelper<EmployeeDepartmentHistory>)InnerData.EmployeeDepartmentHistory).GetItem(null), value)) ((ILookupHelper<EmployeeDepartmentHistory>)InnerData.EmployeeDepartmentHistory).SetItem(value, null); } } public Shift Shift { get { return ((ILookupHelper<Shift>)InnerData.Shift).GetItem(null); } set { if (LazySet(Members.Shift, ((ILookupHelper<Shift>)InnerData.Shift).GetItem(null), value)) ((ILookupHelper<Shift>)InnerData.Shift).SetItem(value, null); } } public JobCandidate JobCandidate { get { return ((ILookupHelper<JobCandidate>)InnerData.JobCandidate).GetItem(null); } set { if (LazySet(Members.JobCandidate, ((ILookupHelper<JobCandidate>)InnerData.JobCandidate).GetItem(null), value)) ((ILookupHelper<JobCandidate>)InnerData.JobCandidate).SetItem(value, null); } } private void ClearJobCandidate(DateTime? moment) { ((ILookupHelper<JobCandidate>)InnerData.JobCandidate).ClearLookup(moment); } public EntityCollection<Vendor> Vendors { get { return InnerData.Vendors; } } private void ClearVendors(DateTime? moment) { ((ILookupHelper<Vendor>)InnerData.Vendors).ClearLookup(moment); } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static EmployeeMembers members = null; public static EmployeeMembers Members { get { if (members == null) { lock (typeof(Employee)) { if (members == null) members = new EmployeeMembers(); } } return members; } } public class EmployeeMembers { internal EmployeeMembers() { } #region Members for interface IEmployee public Property NationalIDNumber { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["NationalIDNumber"]; public Property LoginID { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["LoginID"]; public Property JobTitle { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["JobTitle"]; public Property BirthDate { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["BirthDate"]; public Property MaritalStatus { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["MaritalStatus"]; public Property Gender { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["Gender"]; public Property HireDate { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["HireDate"]; public Property SalariedFlag { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["SalariedFlag"]; public Property VacationHours { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["VacationHours"]; public Property SickLeaveHours { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["SickLeaveHours"]; public Property Currentflag { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["Currentflag"]; public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["rowguid"]; public Property EmployeePayHistory { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["EmployeePayHistory"]; public Property SalesPerson { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["SalesPerson"]; public Property EmployeeDepartmentHistory { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["EmployeeDepartmentHistory"]; public Property Shift { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["Shift"]; public Property JobCandidate { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["JobCandidate"]; public Property Vendors { get; } = Datastore.AdventureWorks.Model.Entities["Employee"].Properties["Vendors"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static EmployeeFullTextMembers fullTextMembers = null; public static EmployeeFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(Employee)) { if (fullTextMembers == null) fullTextMembers = new EmployeeFullTextMembers(); } } return fullTextMembers; } } public class EmployeeFullTextMembers { internal EmployeeFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(Employee)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["Employee"]; } } return entity; } private static EmployeeEvents events = null; public static EmployeeEvents Events { get { if (events == null) { lock (typeof(Employee)) { if (events == null) events = new EmployeeEvents(); } } return events; } } public class EmployeeEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<Employee, EntityEventArgs> onNew; public event EventHandler<Employee, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<Employee, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<Employee, EntityEventArgs> onDelete; public event EventHandler<Employee, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<Employee, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<Employee, EntityEventArgs> onSave; public event EventHandler<Employee, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<Employee, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnNationalIDNumber private static bool onNationalIDNumberIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onNationalIDNumber; public static event EventHandler<Employee, PropertyEventArgs> OnNationalIDNumber { add { lock (typeof(OnPropertyChange)) { if (!onNationalIDNumberIsRegistered) { Members.NationalIDNumber.Events.OnChange -= onNationalIDNumberProxy; Members.NationalIDNumber.Events.OnChange += onNationalIDNumberProxy; onNationalIDNumberIsRegistered = true; } onNationalIDNumber += value; } } remove { lock (typeof(OnPropertyChange)) { onNationalIDNumber -= value; if (onNationalIDNumber == null && onNationalIDNumberIsRegistered) { Members.NationalIDNumber.Events.OnChange -= onNationalIDNumberProxy; onNationalIDNumberIsRegistered = false; } } } } private static void onNationalIDNumberProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onNationalIDNumber; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnLoginID private static bool onLoginIDIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onLoginID; public static event EventHandler<Employee, PropertyEventArgs> OnLoginID { add { lock (typeof(OnPropertyChange)) { if (!onLoginIDIsRegistered) { Members.LoginID.Events.OnChange -= onLoginIDProxy; Members.LoginID.Events.OnChange += onLoginIDProxy; onLoginIDIsRegistered = true; } onLoginID += value; } } remove { lock (typeof(OnPropertyChange)) { onLoginID -= value; if (onLoginID == null && onLoginIDIsRegistered) { Members.LoginID.Events.OnChange -= onLoginIDProxy; onLoginIDIsRegistered = false; } } } } private static void onLoginIDProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onLoginID; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnJobTitle private static bool onJobTitleIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onJobTitle; public static event EventHandler<Employee, PropertyEventArgs> OnJobTitle { add { lock (typeof(OnPropertyChange)) { if (!onJobTitleIsRegistered) { Members.JobTitle.Events.OnChange -= onJobTitleProxy; Members.JobTitle.Events.OnChange += onJobTitleProxy; onJobTitleIsRegistered = true; } onJobTitle += value; } } remove { lock (typeof(OnPropertyChange)) { onJobTitle -= value; if (onJobTitle == null && onJobTitleIsRegistered) { Members.JobTitle.Events.OnChange -= onJobTitleProxy; onJobTitleIsRegistered = false; } } } } private static void onJobTitleProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onJobTitle; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnBirthDate private static bool onBirthDateIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onBirthDate; public static event EventHandler<Employee, PropertyEventArgs> OnBirthDate { add { lock (typeof(OnPropertyChange)) { if (!onBirthDateIsRegistered) { Members.BirthDate.Events.OnChange -= onBirthDateProxy; Members.BirthDate.Events.OnChange += onBirthDateProxy; onBirthDateIsRegistered = true; } onBirthDate += value; } } remove { lock (typeof(OnPropertyChange)) { onBirthDate -= value; if (onBirthDate == null && onBirthDateIsRegistered) { Members.BirthDate.Events.OnChange -= onBirthDateProxy; onBirthDateIsRegistered = false; } } } } private static void onBirthDateProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onBirthDate; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnMaritalStatus private static bool onMaritalStatusIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onMaritalStatus; public static event EventHandler<Employee, PropertyEventArgs> OnMaritalStatus { add { lock (typeof(OnPropertyChange)) { if (!onMaritalStatusIsRegistered) { Members.MaritalStatus.Events.OnChange -= onMaritalStatusProxy; Members.MaritalStatus.Events.OnChange += onMaritalStatusProxy; onMaritalStatusIsRegistered = true; } onMaritalStatus += value; } } remove { lock (typeof(OnPropertyChange)) { onMaritalStatus -= value; if (onMaritalStatus == null && onMaritalStatusIsRegistered) { Members.MaritalStatus.Events.OnChange -= onMaritalStatusProxy; onMaritalStatusIsRegistered = false; } } } } private static void onMaritalStatusProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onMaritalStatus; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnGender private static bool onGenderIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onGender; public static event EventHandler<Employee, PropertyEventArgs> OnGender { add { lock (typeof(OnPropertyChange)) { if (!onGenderIsRegistered) { Members.Gender.Events.OnChange -= onGenderProxy; Members.Gender.Events.OnChange += onGenderProxy; onGenderIsRegistered = true; } onGender += value; } } remove { lock (typeof(OnPropertyChange)) { onGender -= value; if (onGender == null && onGenderIsRegistered) { Members.Gender.Events.OnChange -= onGenderProxy; onGenderIsRegistered = false; } } } } private static void onGenderProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onGender; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnHireDate private static bool onHireDateIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onHireDate; public static event EventHandler<Employee, PropertyEventArgs> OnHireDate { add { lock (typeof(OnPropertyChange)) { if (!onHireDateIsRegistered) { Members.HireDate.Events.OnChange -= onHireDateProxy; Members.HireDate.Events.OnChange += onHireDateProxy; onHireDateIsRegistered = true; } onHireDate += value; } } remove { lock (typeof(OnPropertyChange)) { onHireDate -= value; if (onHireDate == null && onHireDateIsRegistered) { Members.HireDate.Events.OnChange -= onHireDateProxy; onHireDateIsRegistered = false; } } } } private static void onHireDateProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onHireDate; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnSalariedFlag private static bool onSalariedFlagIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onSalariedFlag; public static event EventHandler<Employee, PropertyEventArgs> OnSalariedFlag { add { lock (typeof(OnPropertyChange)) { if (!onSalariedFlagIsRegistered) { Members.SalariedFlag.Events.OnChange -= onSalariedFlagProxy; Members.SalariedFlag.Events.OnChange += onSalariedFlagProxy; onSalariedFlagIsRegistered = true; } onSalariedFlag += value; } } remove { lock (typeof(OnPropertyChange)) { onSalariedFlag -= value; if (onSalariedFlag == null && onSalariedFlagIsRegistered) { Members.SalariedFlag.Events.OnChange -= onSalariedFlagProxy; onSalariedFlagIsRegistered = false; } } } } private static void onSalariedFlagProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onSalariedFlag; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnVacationHours private static bool onVacationHoursIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onVacationHours; public static event EventHandler<Employee, PropertyEventArgs> OnVacationHours { add { lock (typeof(OnPropertyChange)) { if (!onVacationHoursIsRegistered) { Members.VacationHours.Events.OnChange -= onVacationHoursProxy; Members.VacationHours.Events.OnChange += onVacationHoursProxy; onVacationHoursIsRegistered = true; } onVacationHours += value; } } remove { lock (typeof(OnPropertyChange)) { onVacationHours -= value; if (onVacationHours == null && onVacationHoursIsRegistered) { Members.VacationHours.Events.OnChange -= onVacationHoursProxy; onVacationHoursIsRegistered = false; } } } } private static void onVacationHoursProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onVacationHours; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnSickLeaveHours private static bool onSickLeaveHoursIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onSickLeaveHours; public static event EventHandler<Employee, PropertyEventArgs> OnSickLeaveHours { add { lock (typeof(OnPropertyChange)) { if (!onSickLeaveHoursIsRegistered) { Members.SickLeaveHours.Events.OnChange -= onSickLeaveHoursProxy; Members.SickLeaveHours.Events.OnChange += onSickLeaveHoursProxy; onSickLeaveHoursIsRegistered = true; } onSickLeaveHours += value; } } remove { lock (typeof(OnPropertyChange)) { onSickLeaveHours -= value; if (onSickLeaveHours == null && onSickLeaveHoursIsRegistered) { Members.SickLeaveHours.Events.OnChange -= onSickLeaveHoursProxy; onSickLeaveHoursIsRegistered = false; } } } } private static void onSickLeaveHoursProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onSickLeaveHours; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnCurrentflag private static bool onCurrentflagIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onCurrentflag; public static event EventHandler<Employee, PropertyEventArgs> OnCurrentflag { add { lock (typeof(OnPropertyChange)) { if (!onCurrentflagIsRegistered) { Members.Currentflag.Events.OnChange -= onCurrentflagProxy; Members.Currentflag.Events.OnChange += onCurrentflagProxy; onCurrentflagIsRegistered = true; } onCurrentflag += value; } } remove { lock (typeof(OnPropertyChange)) { onCurrentflag -= value; if (onCurrentflag == null && onCurrentflagIsRegistered) { Members.Currentflag.Events.OnChange -= onCurrentflagProxy; onCurrentflagIsRegistered = false; } } } } private static void onCurrentflagProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onCurrentflag; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region Onrowguid private static bool onrowguidIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onrowguid; public static event EventHandler<Employee, PropertyEventArgs> Onrowguid { add { lock (typeof(OnPropertyChange)) { if (!onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; Members.rowguid.Events.OnChange += onrowguidProxy; onrowguidIsRegistered = true; } onrowguid += value; } } remove { lock (typeof(OnPropertyChange)) { onrowguid -= value; if (onrowguid == null && onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; onrowguidIsRegistered = false; } } } } private static void onrowguidProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onrowguid; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnEmployeePayHistory private static bool onEmployeePayHistoryIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onEmployeePayHistory; public static event EventHandler<Employee, PropertyEventArgs> OnEmployeePayHistory { add { lock (typeof(OnPropertyChange)) { if (!onEmployeePayHistoryIsRegistered) { Members.EmployeePayHistory.Events.OnChange -= onEmployeePayHistoryProxy; Members.EmployeePayHistory.Events.OnChange += onEmployeePayHistoryProxy; onEmployeePayHistoryIsRegistered = true; } onEmployeePayHistory += value; } } remove { lock (typeof(OnPropertyChange)) { onEmployeePayHistory -= value; if (onEmployeePayHistory == null && onEmployeePayHistoryIsRegistered) { Members.EmployeePayHistory.Events.OnChange -= onEmployeePayHistoryProxy; onEmployeePayHistoryIsRegistered = false; } } } } private static void onEmployeePayHistoryProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onEmployeePayHistory; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnSalesPerson private static bool onSalesPersonIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onSalesPerson; public static event EventHandler<Employee, PropertyEventArgs> OnSalesPerson { add { lock (typeof(OnPropertyChange)) { if (!onSalesPersonIsRegistered) { Members.SalesPerson.Events.OnChange -= onSalesPersonProxy; Members.SalesPerson.Events.OnChange += onSalesPersonProxy; onSalesPersonIsRegistered = true; } onSalesPerson += value; } } remove { lock (typeof(OnPropertyChange)) { onSalesPerson -= value; if (onSalesPerson == null && onSalesPersonIsRegistered) { Members.SalesPerson.Events.OnChange -= onSalesPersonProxy; onSalesPersonIsRegistered = false; } } } } private static void onSalesPersonProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onSalesPerson; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnEmployeeDepartmentHistory private static bool onEmployeeDepartmentHistoryIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onEmployeeDepartmentHistory; public static event EventHandler<Employee, PropertyEventArgs> OnEmployeeDepartmentHistory { add { lock (typeof(OnPropertyChange)) { if (!onEmployeeDepartmentHistoryIsRegistered) { Members.EmployeeDepartmentHistory.Events.OnChange -= onEmployeeDepartmentHistoryProxy; Members.EmployeeDepartmentHistory.Events.OnChange += onEmployeeDepartmentHistoryProxy; onEmployeeDepartmentHistoryIsRegistered = true; } onEmployeeDepartmentHistory += value; } } remove { lock (typeof(OnPropertyChange)) { onEmployeeDepartmentHistory -= value; if (onEmployeeDepartmentHistory == null && onEmployeeDepartmentHistoryIsRegistered) { Members.EmployeeDepartmentHistory.Events.OnChange -= onEmployeeDepartmentHistoryProxy; onEmployeeDepartmentHistoryIsRegistered = false; } } } } private static void onEmployeeDepartmentHistoryProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onEmployeeDepartmentHistory; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnShift private static bool onShiftIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onShift; public static event EventHandler<Employee, PropertyEventArgs> OnShift { add { lock (typeof(OnPropertyChange)) { if (!onShiftIsRegistered) { Members.Shift.Events.OnChange -= onShiftProxy; Members.Shift.Events.OnChange += onShiftProxy; onShiftIsRegistered = true; } onShift += value; } } remove { lock (typeof(OnPropertyChange)) { onShift -= value; if (onShift == null && onShiftIsRegistered) { Members.Shift.Events.OnChange -= onShiftProxy; onShiftIsRegistered = false; } } } } private static void onShiftProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onShift; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnJobCandidate private static bool onJobCandidateIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onJobCandidate; public static event EventHandler<Employee, PropertyEventArgs> OnJobCandidate { add { lock (typeof(OnPropertyChange)) { if (!onJobCandidateIsRegistered) { Members.JobCandidate.Events.OnChange -= onJobCandidateProxy; Members.JobCandidate.Events.OnChange += onJobCandidateProxy; onJobCandidateIsRegistered = true; } onJobCandidate += value; } } remove { lock (typeof(OnPropertyChange)) { onJobCandidate -= value; if (onJobCandidate == null && onJobCandidateIsRegistered) { Members.JobCandidate.Events.OnChange -= onJobCandidateProxy; onJobCandidateIsRegistered = false; } } } } private static void onJobCandidateProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onJobCandidate; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnVendors private static bool onVendorsIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onVendors; public static event EventHandler<Employee, PropertyEventArgs> OnVendors { add { lock (typeof(OnPropertyChange)) { if (!onVendorsIsRegistered) { Members.Vendors.Events.OnChange -= onVendorsProxy; Members.Vendors.Events.OnChange += onVendorsProxy; onVendorsIsRegistered = true; } onVendors += value; } } remove { lock (typeof(OnPropertyChange)) { onVendors -= value; if (onVendors == null && onVendorsIsRegistered) { Members.Vendors.Events.OnChange -= onVendorsProxy; onVendorsIsRegistered = false; } } } } private static void onVendorsProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onVendors; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onModifiedDate; public static event EventHandler<Employee, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<Employee, PropertyEventArgs> onUid; public static event EventHandler<Employee, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<Employee, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((Employee)sender, args); } #endregion } #endregion } #endregion #region IEmployeeOriginalData public IEmployeeOriginalData OriginalVersion { get { return this; } } #region Members for interface IEmployee string IEmployeeOriginalData.NationalIDNumber { get { return OriginalData.NationalIDNumber; } } int IEmployeeOriginalData.LoginID { get { return OriginalData.LoginID; } } string IEmployeeOriginalData.JobTitle { get { return OriginalData.JobTitle; } } System.DateTime IEmployeeOriginalData.BirthDate { get { return OriginalData.BirthDate; } } string IEmployeeOriginalData.MaritalStatus { get { return OriginalData.MaritalStatus; } } string IEmployeeOriginalData.Gender { get { return OriginalData.Gender; } } System.DateTime IEmployeeOriginalData.HireDate { get { return OriginalData.HireDate; } } bool IEmployeeOriginalData.SalariedFlag { get { return OriginalData.SalariedFlag; } } int IEmployeeOriginalData.VacationHours { get { return OriginalData.VacationHours; } } int IEmployeeOriginalData.SickLeaveHours { get { return OriginalData.SickLeaveHours; } } bool IEmployeeOriginalData.Currentflag { get { return OriginalData.Currentflag; } } string IEmployeeOriginalData.rowguid { get { return OriginalData.rowguid; } } EmployeePayHistory IEmployeeOriginalData.EmployeePayHistory { get { return ((ILookupHelper<EmployeePayHistory>)OriginalData.EmployeePayHistory).GetOriginalItem(null); } } SalesPerson IEmployeeOriginalData.SalesPerson { get { return ((ILookupHelper<SalesPerson>)OriginalData.SalesPerson).GetOriginalItem(null); } } EmployeeDepartmentHistory IEmployeeOriginalData.EmployeeDepartmentHistory { get { return ((ILookupHelper<EmployeeDepartmentHistory>)OriginalData.EmployeeDepartmentHistory).GetOriginalItem(null); } } Shift IEmployeeOriginalData.Shift { get { return ((ILookupHelper<Shift>)OriginalData.Shift).GetOriginalItem(null); } } JobCandidate IEmployeeOriginalData.JobCandidate { get { return ((ILookupHelper<JobCandidate>)OriginalData.JobCandidate).GetOriginalItem(null); } } IEnumerable<Vendor> IEmployeeOriginalData.Vendors { get { return OriginalData.Vendors.OriginalData; } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using UnitTests.GrainInterfaces; using Xunit; using System.Linq; using UnitTests.TimerTests; // ReSharper disable InconsistentNaming // ReSharper disable UnusedVariable namespace Tester.AzureUtils.TimerTests { [TestCategory("ReminderService"), TestCategory("Azure")] public class ReminderTests_AzureTable : ReminderTests_Base, IClassFixture<ReminderTests_AzureTable.Fixture> { public class Fixture : BaseAzureTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { Guid serviceId = Guid.NewGuid(); builder.ConfigureLegacyConfiguration(legacy => { legacy.ClusterConfiguration.Globals.ServiceId = serviceId; legacy.ClusterConfiguration.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.AzureTable; }); } } public ReminderTests_AzureTable(Fixture fixture) : base(fixture) { fixture.EnsurePreconditionsMet(); } // Basic tests [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic_StopByRef() { await Test_Reminders_Basic_StopByRef(); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic_ListOps() { await Test_Reminders_Basic_ListOps(); } // Single join tests ... multi grain, multi reminders [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_1J_MultiGrainMultiReminders() { await Test_Reminders_1J_MultiGrainMultiReminders(); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_ReminderNotFound() { await Test_Reminders_ReminderNotFound(); } #region Basic test [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic() { // start up a test grain and get the period that it's programmed to use. IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await grain.GetReminderPeriod(DR); // start up the 'DR' reminder and wait for two ticks to pass. await grain.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway // retrieve the value of the counter-- it should match the sequence number which is the number of periods // we've waited. long last = await grain.GetCounter(DR); Assert.Equal(2, last); // stop the timer and wait for a whole period. await grain.StopReminder(DR); Thread.Sleep(period.Multiply(1) + LEEWAY); // giving some leeway // the counter should not have changed. long curr = await grain.GetCounter(DR); Assert.Equal(last, curr); } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Basic_Restart() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await grain.GetReminderPeriod(DR); await grain.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway long last = await grain.GetCounter(DR); Assert.Equal(2, last); await grain.StopReminder(DR); TimeSpan sleepFor = period.Multiply(1) + LEEWAY; Thread.Sleep(sleepFor); // giving some leeway long curr = await grain.GetCounter(DR); Assert.Equal(last, curr); AssertIsInRange(curr, last, last + 1, grain, DR, sleepFor); // start the same reminder again await grain.StartReminder(DR); sleepFor = period.Multiply(2) + LEEWAY; Thread.Sleep(sleepFor); // giving some leeway curr = await grain.GetCounter(DR); AssertIsInRange(curr, 2, 3, grain, DR, sleepFor); await grain.StopReminder(DR); // cleanup } #endregion #region Basic single grain multi reminders test [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_MultipleReminders() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); await PerGrainMultiReminderTest(grain); } #endregion #region Multiple joins ... multi grain, multi reminders [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_2J_MultiGrainMultiReminders() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task<bool>[] tasks = { Task.Run(() => PerGrainMultiReminderTestChurn(g1)), Task.Run(() => PerGrainMultiReminderTestChurn(g2)), Task.Run(() => PerGrainMultiReminderTestChurn(g3)), Task.Run(() => PerGrainMultiReminderTestChurn(g4)), Task.Run(() => PerGrainMultiReminderTestChurn(g5)), }; await Task.Delay(period.Multiply(5)); // start two extra silos ... although it will take it a while before they stabilize log.Info("Starting 2 extra silos"); await this.HostedCluster.StartAdditionalSilos(2, true); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); //Block until all tasks complete. await Task.WhenAll(tasks).WithTimeout(ENDWAIT); } #endregion #region Multi grains multi reminders/grain test [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_MultiGrainMultiReminders() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); Task<bool>[] tasks = { Task.Run(() => PerGrainMultiReminderTest(g1)), Task.Run(() => PerGrainMultiReminderTest(g2)), Task.Run(() => PerGrainMultiReminderTest(g3)), Task.Run(() => PerGrainMultiReminderTest(g4)), Task.Run(() => PerGrainMultiReminderTest(g5)), }; //Block until all tasks complete. await Task.WhenAll(tasks).WithTimeout(ENDWAIT); } #endregion #region Secondary failure ... Basic test [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_1F_Basic() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task<bool> test = Task.Run(async () => { await PerGrainFailureTest(g1); return true; }); Thread.Sleep(period.Multiply(failAfter)); // stop the secondary silo log.Info("Stopping secondary silo"); this.HostedCluster.StopSilo(this.HostedCluster.SecondarySilos.First()); await test; // Block until test completes. } #endregion #region Multiple failures ... multiple grains [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_2F_MultiGrain() { List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilos(2,true); IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task[] tasks = { Task.Run(() => PerGrainFailureTest(g1)), Task.Run(() => PerGrainFailureTest(g2)), Task.Run(() => PerGrainFailureTest(g3)), Task.Run(() => PerGrainFailureTest(g4)), Task.Run(() => PerGrainFailureTest(g5)), }; Thread.Sleep(period.Multiply(failAfter)); // stop a couple of silos log.Info("Stopping 2 silos"); int i = random.Next(silos.Count); this.HostedCluster.StopSilo(silos[i]); silos.RemoveAt(i); this.HostedCluster.StopSilo(silos[random.Next(silos.Count)]); await Task.WhenAll(tasks).WithTimeout(ENDWAIT); // Block until all tasks complete. } #endregion #region 1 join 1 failure simulateneously ... multiple grains [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_1F1J_MultiGrain() { List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilos(1); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task[] tasks = { Task.Run(() => PerGrainFailureTest(g1)), Task.Run(() => PerGrainFailureTest(g2)), Task.Run(() => PerGrainFailureTest(g3)), Task.Run(() => PerGrainFailureTest(g4)), Task.Run(() => PerGrainFailureTest(g5)), }; Thread.Sleep(period.Multiply(failAfter)); var siloToKill = silos[random.Next(silos.Count)]; // stop a silo and join a new one in parallel log.Info("Stopping a silo and joining a silo"); Task<bool> t1 = Task.Factory.StartNew(() => { this.HostedCluster.StopSilo(siloToKill); return true; }); Task<bool> t2 = this.HostedCluster.StartAdditionalSilos(1, true).ContinueWith(t => { t.GetAwaiter().GetResult(); return true; }); await Task.WhenAll(new[] { t1, t2 }).WithTimeout(ENDWAIT); await Task.WhenAll(tasks).WithTimeout(ENDWAIT); // Block until all tasks complete. log.Info("\n\n\nReminderTest_1F1J_MultiGrain passed OK.\n\n\n"); } #endregion #region Register same reminder multiple times [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_RegisterSameReminderTwice() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); Task<IGrainReminder> promise1 = grain.StartReminder(DR); Task<IGrainReminder> promise2 = grain.StartReminder(DR); Task<IGrainReminder>[] tasks = { promise1, promise2 }; await Task.WhenAll(tasks).WithTimeout(TimeSpan.FromSeconds(15)); //Assert.NotEqual(promise1.Result, promise2.Result); // TODO: write tests where period of a reminder is changed } #endregion #region Multiple grain types [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_GT_Basic() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestCopyGrain g2 = this.GrainFactory.GetGrain<IReminderTestCopyGrain>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); // using same period await g1.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway await g2.StartReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway long last1 = await g1.GetCounter(DR); Assert.Equal(4, last1); long last2 = await g2.GetCounter(DR); Assert.Equal(2, last2); // CopyGrain fault await g1.StopReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway await g2.StopReminder(DR); long curr1 = await g1.GetCounter(DR); Assert.Equal(last1, curr1); long curr2 = await g2.GetCounter(DR); Assert.Equal(4, curr2); // CopyGrain fault } [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_GT_1F1J_MultiGrain() { List<SiloHandle> silos = await this.HostedCluster.StartAdditionalSilos(1); await this.HostedCluster.WaitForLivenessToStabilizeAsync(); IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestCopyGrain g3 = this.GrainFactory.GetGrain<IReminderTestCopyGrain>(Guid.NewGuid()); IReminderTestCopyGrain g4 = this.GrainFactory.GetGrain<IReminderTestCopyGrain>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task[] tasks = { Task.Run(() => PerGrainFailureTest(g1)), Task.Run(() => PerGrainFailureTest(g2)), Task.Run(() => PerCopyGrainFailureTest(g3)), Task.Run(() => PerCopyGrainFailureTest(g4)), }; Thread.Sleep(period.Multiply(failAfter)); var siloToKill = silos[random.Next(silos.Count)]; // stop a silo and join a new one in parallel log.Info("Stopping a silo and joining a silo"); Task<bool> t1 = Task.Run(() => { this.HostedCluster.StopSilo(siloToKill); return true; }); Task<bool> t2 = Task.Run(async () => { await this.HostedCluster.StartAdditionalSilos(1); return true; }); await Task.WhenAll(new[] { t1, t2 }).WithTimeout(ENDWAIT); await Task.WhenAll(tasks).WithTimeout(ENDWAIT); // Block until all tasks complete. } #endregion #region Testing things that should fail #region Lower than allowed reminder period [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Wrong_LowerThanAllowedPeriod() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); await Assert.ThrowsAsync<ArgumentException>(() => grain.StartReminder(DR, TimeSpan.FromMilliseconds(3000), true)); } #endregion #region The wrong reminder grain [SkippableFact, TestCategory("Functional")] public async Task Rem_Azure_Wrong_Grain() { IReminderGrainWrong grain = this.GrainFactory.GetGrain<IReminderGrainWrong>(0); await Assert.ThrowsAsync<InvalidOperationException>(() => grain.StartReminder(DR)); } #endregion #endregion } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedVariable
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Net; using System.IO; using System.Threading; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; using WebsitePanel.Updater.Common; using WebsitePanel.Updater.Services; using Ionic.Zip; namespace WebsitePanel.Updater { internal partial class UpdaterForm : Form { private const int ChunkSize = 262144; private Thread thread; private InstallerService service; public UpdaterForm() { CheckForIllegalCrossThreadCalls = false; InitializeComponent(); this.DialogResult = DialogResult.Cancel; Start(); } private void Start() { thread = new Thread(new ThreadStart(ShowProcess)); thread.Start(); } private void btnCancel_Click(object sender, EventArgs e) { Close(); } /// <summary> /// Displays process progress. /// </summary> public void ShowProcess() { progressBar.Value = 0; lblProcess.Text = "Downloading installation files..."; Update(); try { string url = GetCommandLineArgument("url"); string targetFile = GetCommandLineArgument("target"); string fileToDownload = GetCommandLineArgument("file"); string proxyServer = GetCommandLineArgument("proxy"); string user = GetCommandLineArgument("user"); string password = GetCommandLineArgument("password"); service = new InstallerService(); service.Url = url; if (!String.IsNullOrEmpty(proxyServer)) { IWebProxy proxy = new WebProxy(proxyServer); if (!String.IsNullOrEmpty(user)) proxy.Credentials = new NetworkCredential(user, password); service.Proxy = proxy; } string destinationFile = Path.GetTempFileName(); string baseDir = Path.GetDirectoryName(targetFile); // download file DownloadFile(fileToDownload, destinationFile, progressBar); progressBar.Value = 100; // unzip file lblProcess.Text = "Unzipping files..."; progressBar.Value = 0; UnzipFile(destinationFile, baseDir, progressBar); progressBar.Value = 100; FileUtils.DeleteFile(destinationFile); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = targetFile; info.Arguments = "nocheck"; //info.WindowStyle = ProcessWindowStyle.Normal; Process process = Process.Start(info); //activate window if (process.Handle != IntPtr.Zero) { User32.SetForegroundWindow(process.Handle); /*if (User32.IsIconic(process.Handle)) { User32.ShowWindowAsync(process.Handle, User32.SW_RESTORE); } else { User32.ShowWindowAsync(process.Handle, User32.SW_SHOWNORMAL); }*/ } this.DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; string message = ex.ToString(); ShowError(); return; } } private void DownloadFile(string sourceFile, string destinationFile, ProgressBar progressBar) { try { long downloaded = 0; long fileSize = service.GetFileSize(sourceFile); if (fileSize == 0) { throw new FileNotFoundException("Service returned empty file.", sourceFile); } byte[] content; while (downloaded < fileSize) { content = service.GetFileChunk(sourceFile, (int)downloaded, ChunkSize); if (content == null) { throw new FileNotFoundException("Service returned NULL file content.", sourceFile); } FileUtils.AppendFileContent(destinationFile, content); downloaded += content.Length; //update progress bar progressBar.Value = Convert.ToInt32((downloaded * 100) / fileSize); if (content.Length < ChunkSize) break; } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; throw; } } private void UnzipFile(string zipFile, string destFolder, ProgressBar progressBar) { try { //calculate size long zipSize = 0; using (ZipFile zip = ZipFile.Read(zipFile)) { foreach (ZipEntry entry in zip) { if ( !entry.IsDirectory) zipSize += entry.UncompressedSize; } } progressBar.Minimum = 0; progressBar.Maximum = 100; progressBar.Value = 0; long unzipped = 0; using (ZipFile zip = ZipFile.Read(zipFile)) { foreach (ZipEntry entry in zip) { entry.Extract(destFolder, ExtractExistingFileAction.OverwriteSilently); // overwrite == true if (!entry.IsDirectory) unzipped += entry.UncompressedSize; if (zipSize != 0) { progressBar.Value = Convert.ToInt32(unzipped * 100 / zipSize); } } } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; throw; } } private void OnFormClosing(object sender, FormClosingEventArgs e) { if (this.DialogResult != DialogResult.OK && this.thread != null) { if (this.thread.IsAlive) { this.thread.Abort(); } this.thread.Join(); } } private string GetCommandLineArgument(string argName) { argName = "\\" + argName + ":"; string[] args = Environment.GetCommandLineArgs(); for (int i = 1; i < args.Length; i++) { string arg = args[i]; if (arg.StartsWith(argName)) { string text = arg.Substring(argName.Length); if (text.StartsWith("\"") && text.EndsWith("\"")) { text = text.Substring(1, text.Length - 2); } return text; } } return string.Empty; } /// <summary> /// Shows error message /// </summary> /// <param name="message">Message</param> private void ShowError(string message) { MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } private void ShowError() { string message = "An unexpected error has occurred. We apologize for this inconvenience.\n" + "Please contact Technical Support at info@websitepanel.net"; MessageBox.Show(this, message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Drawing; using System.Globalization; using System.IO; using System.Text; using Solenoid.Expressions.Support.Collections; #endregion namespace Solenoid.Expressions.Tests.Objects { /// <summary> /// Simple test object used for testing object factories, AOP framework etc. /// </summary> /// <author>Rod Johnson</author> /// <author>Mark Pollack (.NET)</author> public class TestObject : MarshalByRefObject, ITestObject, IComparable, IOther { #region Event testing members public event EventHandler Click; public static event EventHandler StaticClick; /// <summary> /// Public method to programmatically raise the <event>Click</event> event /// while testing. /// </summary> public void OnClick() { if (Click != null) { Click(this, EventArgs.Empty); } } /// <summary> /// Public method to programmatically raise the <b>static</b> /// <event>Click</event> event while testing. /// </summary> public static void OnStaticClick() { if (TestObject.StaticClick != null) { TestObject.StaticClick(typeof (TestObject), EventArgs.Empty); } } #endregion #region Properties public int ObjectNumber { get { return objectNumber; } set { objectNumber = value; } } // for use in ObjectWrapperTests.SetPropertyValuesFailsWhenSettingReadOnlyProperty public int ReadOnlyObjectNumber { get { return objectNumber; } } /// <summary> /// Public Enumeration Property for FileMode. /// </summary> public FileMode FileMode { get { return FileModeEnum; } set { FileModeEnum = value; } } public CultureInfo MyCulture { get { return myCulture; } set { myCulture = value; } } public string Touchy { get { return touchy; } set { if (value.IndexOf('.') != - 1) { throw new Exception("Can't contain a ."); } if (value.IndexOf(',') != - 1) { throw new FormatException("Number format exception: contains a ,"); } this.touchy = value; } } public bool PostProcessed { get { return postProcessed; } set { this.postProcessed = value; } } public string Name { get { return name; } set { this.name = value; } } public string Nickname { get { return nickname; } set { this.nickname = value; } } public virtual int Age { get { return age; } set { this.age = value; } } public virtual DateTime Date { get { return date; } set { this.date = value; } } public virtual Single MyFloat { get { return myFloat; } set { this.myFloat = value; } } public virtual ITestObject Spouse { get { return spouse; } set { this.spouse = value; } } public virtual ITestObject Sibling { get { return sibling; } set { this.sibling = value; } } public virtual INestedTestObject Doctor { get { return doctor; } set { this.doctor = value; } } public virtual INestedTestObject Lawyer { get { return lawyer; } set { this.lawyer = value; } } public virtual NestedTestObject RealLawyer { get { return myRealLawyer; } set { this.myRealLawyer = value; } } /// <summary> /// A collection of friends. /// </summary> public virtual ICollection Friends { get { return friends; } set { this.friends = value; } } /// <summary> /// A read-only collection of pets. /// </summary> public virtual ICollection Pets { get { return pets; } } public virtual TestObjectList TypedFriends { get { return typedFriends; } set { typedFriends = value; } } /// <summary> /// A read-only map of periodic table values. /// </summary> public virtual IDictionary PeriodicTable { get { return periodicTable; } } /// <summary> /// A read-only set of computer names /// </summary> public virtual ISet Computers { get { return computers; } } public virtual ISet SomeSet { get { return someSet; } set { this.someSet = value; } } public virtual string[] Hats { get { return hats; } set { hats = value; } } public virtual IDictionary SomeMap { get { return someMap; } set { this.someMap = value; } } public virtual IList SomeList { get { return someList; } set { this.someList = value;} } public virtual List<string> SomeGenericStringList { get { return someGenericStringList; } set { this.someGenericStringList = value; } } private IList<int> someGenericIListInt32; public virtual IList<int> SomeGenericIListInt32 { get { return someGenericIListInt32; } set { someGenericIListInt32 = value; } } private IDictionary<string, int> someGenericIDictionaryStringInt32; public virtual IDictionary<string, int> SomeGenericIDictionaryStringInt32 { get { return someGenericIDictionaryStringInt32; } set { someGenericIDictionaryStringInt32 = value; } } private IEnumerable<int> someGenericIEnumerableInt32; public virtual IEnumerable<int> SomeGenericIEnumerableInt32 { get { return someGenericIEnumerableInt32; } set { someGenericIEnumerableInt32 = value; } } public virtual NameValueCollection SomeNameValueCollection { get { return someNameValueCollection; } set { this.someNameValueCollection = value;} } protected virtual string HappyPlace { get { return _happyPlace; } set { _happyPlace = value; } } // used in reflective tests, so don't remove this property... private string[] SamsoniteSuitcase { get { return _samsoniteSuitcase; } set { _samsoniteSuitcase = value; } } public Type ClassProperty { get { return classProperty; } set { classProperty = value; } } public string ObjectName { get { return objectName; } set { objectName = value; } } public int ExceptionMethodCallCount { get { return exceptionMethodCallCount; } } public bool InitCompleted { get { return initCompleted; } set { initCompleted = value; } } public Size Size { get { return size; } set { size = value;} } #endregion #region Indexers public string this[int index] { get { if (index < 0 || index >= favoriteQuotes.Length) { throw new ArgumentException("Index out of range"); } return favoriteQuotes[index]; } set { if (index < 0 || index >= favoriteQuotes.Length) { throw new ArgumentException("index is out of range."); } favoriteQuotes[index] = value; } } #endregion #region Fields private int exceptionMethodCallCount; private int objectNumber = 0; public FileMode FileModeEnum; // private IObjectFactory objectFactory; private bool postProcessed; private int age; private string name; private string nickname; private ITestObject spouse; private ITestObject sibling; private string touchy; private ICollection friends = new LinkedList(); private TestObjectList typedFriends = new TestObjectList(); private ICollection pets = new LinkedList(); private IDictionary periodicTable = new Hashtable(); private string[] favoriteQuotes = new string[] { "He who ha-ha ho-ho", "The quick brown fox jumped over the lazy dogs." }; private Type classProperty; private ISet computers = new HybridSet(); private ISet someSet = new HybridSet(); private IDictionary someMap = new Hashtable(); private IList someList = new ArrayList(); private DateTime date = DateTime.Now; private Single myFloat = (float) 0.0; private CultureInfo myCulture = CultureInfo.InvariantCulture; private string[] hats = null; private INestedTestObject doctor = new NestedTestObject(); private INestedTestObject lawyer = new NestedTestObject(); private NestedTestObject myRealLawyer = new NestedTestObject(); private string _happyPlace = DefaultHappyPlace; private string[] _samsoniteSuitcase = DefaultContentsOfTheSuitcase; public const string DefaultHappyPlace = "The_SeaBass_Diner"; public static readonly string[] DefaultContentsOfTheSuitcase = new string[] {"John Pryor's 'Leaving On A Jet Plane' LP"}; private string objectName; private Size size; private bool initCompleted; private IDictionary sharedState; private NameValueCollection someNameValueCollection; private List<string> someGenericStringList; #endregion #region Constructor (s) / Destructor public TestObject() { } public TestObject(string name, int age) { this.name = name; this.age = age; } public TestObject(string name, int age, INestedTestObject doctor) { this.name = name; this.age = age; this.doctor = doctor; } public TestObject(string name, int age, INestedTestObject doctor, INestedTestObject lawyer) { this.name = name; this.age = age; this.doctor = doctor; this.lawyer = lawyer; } public TestObject(ITestObject spouse) { this.spouse = spouse; } public TestObject(IList someList) { this.someList = someList; } public TestObject(ISet someSet) { this.someSet = someSet; } public TestObject(IDictionary someMap) { this.someMap = someMap; } public TestObject(NameValueCollection someProps) { this.someNameValueCollection = someProps; } #endregion #region Static Methods public static TestObject Create(string name) { return new TestObject(name, 30); } #endregion #region Methods public void AfterPropertiesSet() { initCompleted = true; } public void AddComputerName(string name) { if (computers == null) { computers = new HybridSet(); } computers.Add(name); } public void AddPeriodicElement(string name, string element) { if (periodicTable == null) { periodicTable = new Hashtable(); } periodicTable.Add(name, element); } public string GetNameWithHonorific(bool isFemale, params string[] lettersAfterName) { StringBuilder buffer = new StringBuilder(); buffer.Append(isFemale ? "Ms " : "Mr "); buffer.Append(Name); buffer.Append(" "); foreach (string letters in lettersAfterName) { buffer.Append(letters); } return buffer.ToString(); } public override bool Equals(object other) { return Equals(this, other); } new public static bool Equals(object @this, object other) { if (other == null || !(other is ITestObject)) { return false; } ITestObject tb2 = (ITestObject) other; ITestObject tb1 = (ITestObject) @this; if (tb2.Age != tb1.Age) { return false; } if ((object) tb1.Name == null) { return (object) tb2.Name == null; } if (!tb2.Name.Equals(tb1.Name)) { return false; } return true; } public override int GetHashCode() { return (name != null ? name.GetHashCode() : base.GetHashCode()); } public virtual int CompareTo(object other) { if ((object) this.name != null && other is TestObject) { return String.CompareOrdinal(this.name, ((TestObject) other).name); } else { return 1; } } public virtual string GetDescription() { string s = "name=" + name + "; age=" + age + "; touchy=" + touchy; s += ("; spouse={" + (spouse != null ? spouse.Name : null) + "}"); return s; } public override string ToString() { string s = "name=" + name + "; age=" + age + "; touchy=" + touchy; s += ("; spouse={" + (spouse != null ? spouse.Name : null) + "}"); return s; } //Used in testing messaging public void SetName(string name) { this.name = name; } /// <summary> /// Throw the given exception /// </summary> /// <param name="t">An exception to throw.</param> public virtual void Exceptional(Exception t) { exceptionMethodCallCount++; if (t != null) { throw t; } } /// <summary> /// Throw the given exception /// </summary> /// <param name="t">An exception to throw.</param> /// <returns>314 if exception is null</returns> public virtual int ExceptionalWithReturnValue(Exception t) { exceptionMethodCallCount++; if (t != null) { throw t; } return 314; } /// <summary> /// Return a reference to the object itself. 'Return this' /// </summary> /// <returns>a reference to the object itse.f</returns> public virtual object ReturnsThis() { return this; } #endregion #region IOther Implementation /// <summary> /// Funny Named method. /// </summary> public virtual void Absquatulate() { } #endregion public IDictionary SharedState { get { return sharedState; } set { sharedState = value; } } } #region Inner Class : TestObjectConverter public class TestObjectConverter : TypeConverter { public override bool CanConvertTo( ITypeDescriptorContext context, Type destinationType) { if ((destinationType == typeof (TestObjectConverter)) || (destinationType == typeof (InstanceDescriptor))) { return true; } return base.CanConvertTo(context, destinationType); } public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof (string)) { return true; } return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object text_obj) { if (text_obj is string) { string text = (string) text_obj; TestObject tb = new TestObject(); string[] split = text.Split(new char[] {'_'}); tb.Name = split[0]; tb.Age = int.Parse(split[1]); return tb; } return base.ConvertFrom(context, culture, text_obj); } public override object ConvertTo( ITypeDescriptorContext context, CultureInfo culture, object param, Type destinationType) { return base.ConvertTo(context, culture, param, destinationType); } } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Serialization; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace YamlDotNet.RepresentationModel.Serialization { /// <summary> /// Reads and writes objects from and to YAML. /// </summary> public class YamlSerializer { private readonly YamlSerializerModes mode; private readonly Type serializedType; private class ObjectInfo { public string anchor; public bool serialized; } /// <summary> /// Contains additional information about a deserialization. /// </summary> private class DeserializationContext : IDeserializationContext { private readonly ObjectAnchorCollection anchors = new ObjectAnchorCollection(); internal ObjectAnchorCollection Anchors { get { return anchors; } } private readonly DeserializationOptions options; internal DeserializationOptions Options { get { return options; } } /// <summary> /// Initializes a new instance of the <see cref="DeserializationContext"/> class. /// </summary> /// <param name="options">The mode.</param> internal DeserializationContext(DeserializationOptions options) { this.options = options ?? new DeserializationOptions(); } /// <summary> /// Gets the anchor of the specified object. /// </summary> /// <param name="value">The object that has an anchor.</param> /// <returns>Returns the anchor of the object, or null if no anchor was defined.</returns> public string GetAnchor(object value) { string anchor; if (anchors.TryGetAnchor(value, out anchor)) { return anchor; } return null; } } private readonly Dictionary<object, ObjectInfo> anchors; private bool Roundtrip { get { return (mode & YamlSerializerModes.Roundtrip) != 0; } } private bool DisableAliases { get { return (mode & YamlSerializerModes.DisableAliases) != 0; } } private bool EmitDefaults { get { return (mode & YamlSerializerModes.EmitDefaults) != 0; } } /// <summary> /// Initializes a new instance of the <see cref="YamlSerializer"/> class. /// </summary> /// <remarks> /// When deserializing, the stream must contain type information for the root element. /// </remarks> public YamlSerializer() : this(typeof(object), YamlSerializerModes.None) { } /// <summary> /// Initializes a new instance of the <see cref="YamlSerializer"/> class. /// </summary> /// <param name="mode">The options the specify the behavior of the serializer.</param> /// <remarks> /// When deserializing, the stream must contain type information for the root element. /// </remarks> public YamlSerializer(YamlSerializerModes mode) : this(typeof(object), mode) { } /// <summary> /// Initializes a new instance of the <see cref="YamlSerializer"/> class. /// </summary> /// <param name="serializedType">Type of the serialized.</param> public YamlSerializer(Type serializedType) : this(serializedType, YamlSerializerModes.None) { } /// <summary> /// Initializes a new instance of the <see cref="YamlSerializer"/> class. /// </summary> /// <param name="serializedType">Type of the serialized.</param> /// <param name="mode">The options the specify the behavior of the serializer.</param> public YamlSerializer(Type serializedType, YamlSerializerModes mode) { this.serializedType = serializedType; this.mode = mode; if (!DisableAliases) { anchors = new Dictionary<object, ObjectInfo>(); } } /// <summary> /// Creates a new instance of <see cref="YamlSerializer{TSerialized}"/>. /// </summary> /// <typeparam name="TSerialized">The type of the serialized.</typeparam> /// <param name="serialized">An object of the serialized type. This parameter is necessary to allow type inference.</param> /// <returns></returns> public static YamlSerializer<TSerialized> Create<TSerialized>(TSerialized serialized) { return new YamlSerializer<TSerialized>(); } /// <summary> /// Creates a new instance of <see cref="YamlSerializer{TSerialized}"/>. /// </summary> /// <typeparam name="TSerialized">The type of the serialized.</typeparam> /// <param name="serialized">An object of the serialized type. This parameter is necessary to allow type inference.</param> /// <param name="mode">The mode.</param> /// <returns></returns> public static YamlSerializer<TSerialized> Create<TSerialized>(TSerialized serialized, YamlSerializerModes mode) { return new YamlSerializer<TSerialized>(mode); } #region Serialization /// <summary> /// Serializes the specified object. /// </summary> /// <param name="output">The writer where to serialize the object.</param> /// <param name="o">The object to serialize.</param> public void Serialize(TextWriter output, object o) { if (output == null) { throw new ArgumentNullException("output", "The output is null."); } if (!DisableAliases) { anchors.Clear(); int nextId = 0; LoadAliases(serializedType, o, ref nextId); } Emitter emitter = new Emitter(output); emitter.Emit(new StreamStart()); emitter.Emit(new DocumentStart()); SerializeValue(emitter, serializedType, o); emitter.Emit(new DocumentEnd(true)); emitter.Emit(new StreamEnd()); } private void LoadAliases(Type type, object o, ref int nextId) { if (type.IsValueType) { return; } if (anchors.ContainsKey(o)) { if (anchors[o] == null) { anchors[o] = new ObjectInfo { anchor = string.Format(CultureInfo.InvariantCulture, "o{0}", nextId++) }; } } else { anchors.Add(o, null); if (typeof(IDictionary).IsAssignableFrom(type)) { LoadDictionaryAliases(type, (IDictionary)o, ref nextId); return; } Type iDictionaryType = GetImplementedGenericInterface(type, typeof(IDictionary<,>)); if (iDictionaryType != null) { LoadGenericDictionaryAliases(type, iDictionaryType, o, ref nextId); return; } if (typeof(IEnumerable).IsAssignableFrom(type)) { LoadListAliases(type, (IEnumerable)o, ref nextId); return; } LoadObjectAliases(type, o, ref nextId); } } private void LoadObjectAliases(Type type, object o, ref int nextId) { foreach (var property in GetProperties(type)) { object value = property.GetValue(o, null); if (value != null && value.GetType().IsClass && !(value is string)) { LoadAliases(property.PropertyType, value, ref nextId); } } } private void LoadListAliases(Type type, IEnumerable list, ref int nextId) { foreach (var item in list) { if (item != null) { LoadAliases(item.GetType(), item, ref nextId); } } } private void LoadGenericDictionaryAliases(Type type, Type iDictionaryType, object o, ref int nextId) { foreach (var item in (IEnumerable)o) { LoadObjectAliases(item.GetType(), item, ref nextId); } } private void LoadDictionaryAliases(Type type, IDictionary dictionary, ref int nextId) { foreach (DictionaryEntry item in dictionary) { LoadAliases(item.Key.GetType(), item.Key, ref nextId); if (item.Value != null) { LoadAliases(item.Value.GetType(), item.Value, ref nextId); } } } private void SerializeObject(Emitter emitter, Type type, object value, string anchor) { if (Roundtrip && !HasDefaultConstructor(type)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type '{0}' cannot be deserialized because it does not have a default constructor.", type)); } if (typeof(IDictionary).IsAssignableFrom(type)) { SerializeDictionary(emitter, value, anchor); return; } Type iDictionaryType = GetImplementedGenericInterface(type, typeof(IDictionary<,>)); if(iDictionaryType != null) { SerializeGenericDictionary(emitter, iDictionaryType, value, anchor); return; } if (typeof(IEnumerable).IsAssignableFrom(type)) { SerializeList(emitter, type, value, anchor); return; } SerializeProperties(emitter, type, value, anchor); } private void SerializeGenericDictionary(Emitter emitter, Type iDictionaryType, object value, string anchor) { emitter.Emit(new MappingStart(anchor, null, true, MappingStyle.Any)); Func<object, object> getKey = MakeKeyValuePairGetter(iDictionaryType, "Key"); Func<object, object> getValue = MakeKeyValuePairGetter(iDictionaryType, "Value"); foreach (object entry in (IEnumerable)value) { var entryKey = getKey(entry); SerializeValue(emitter, entryKey.GetType(), entryKey); var entryValue = getValue(entry); SerializeValue(emitter, entryValue.GetType(), entryValue); } emitter.Emit(new MappingEnd()); } private Func<object, object> MakeKeyValuePairGetter(Type iDictionaryType, string propertyName) { var getKeyValuePairKeyGeneric = typeof(YamlSerializer).GetMethod("GetKeyValuePair" + propertyName, BindingFlags.Static | BindingFlags.NonPublic); var getKeyValuePairKey = getKeyValuePairKeyGeneric.MakeGenericMethod(iDictionaryType.GetGenericArguments()); return (Func<object, object>)Delegate.CreateDelegate(typeof(Func<object, object>), getKeyValuePairKey); } // ReSharper disable UnusedPrivateMember // This methid is invoked using reflection. private static object GetKeyValuePairKey<T, U>(object pair) { return ((KeyValuePair<T, U>)pair).Key; } // ReSharper restore UnusedPrivateMember // ReSharper disable UnusedPrivateMember // This methid is invoked using reflection. private static object GetKeyValuePairValue<T, U>(object pair) { return ((KeyValuePair<T, U>)pair).Value; } // ReSharper restore UnusedPrivateMember private void SerializeDictionary(Emitter emitter, object value, string anchor) { emitter.Emit(new MappingStart(anchor, null, true, MappingStyle.Any)); foreach(DictionaryEntry entry in (IDictionary)value) { SerializeValue(emitter, GetObjectType(entry.Key), entry.Key); SerializeValue(emitter, GetObjectType(entry.Value), entry.Value); } emitter.Emit(new MappingEnd()); } private void SerializeList(Emitter emitter, Type type, object value, string anchor) { Type itemType = GetItemType(type, typeof(IEnumerable<>)); SequenceStyle sequenceStyle; switch (Type.GetTypeCode(itemType)) { case TypeCode.String: case TypeCode.Object: sequenceStyle = SequenceStyle.Any; break; default: sequenceStyle = SequenceStyle.Flow; break; } emitter.Emit(new SequenceStart(anchor, null, true, sequenceStyle)); foreach (object item in (IEnumerable)value) { SerializeValue(emitter, itemType, item); } emitter.Emit(new SequenceEnd()); } /// <summary> /// Serializes the properties of the specified object into a mapping. /// </summary> /// <param name="emitter">The emitter.</param> /// <param name="type">The type of the object.</param> /// <param name="o">The o.</param> /// <param name="anchor">The anchor.</param> private void SerializeProperties(Emitter emitter, Type type, object o, string anchor) { if (Roundtrip && !HasDefaultConstructor(type)) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type '{0}' cannot be deserialized because it does not have a default constructor.", type)); } emitter.Emit(new MappingStart(anchor, null, true, MappingStyle.Block)); foreach (var property in GetProperties(type)) { object value = property.GetValue(o, null); var propertyType = property.PropertyType; if (!EmitDefaults && (value == null || (propertyType.IsValueType && value.Equals(Activator.CreateInstance(propertyType))))) { continue; } emitter.Emit(new Scalar(null, null, property.Name, ScalarStyle.Plain, true, false)); SerializeValue(emitter, propertyType, value); } emitter.Emit(new MappingEnd()); } private IEnumerable<PropertyInfo> GetProperties(Type type) { foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (property.CanRead && property.GetGetMethod().GetParameters().Length == 0) { if (!Roundtrip || property.CanWrite) { yield return property; } } } } /// <summary> /// Determines whether the specified type has a default constructor. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the type has a default constructor; otherwise, <c>false</c>. /// </returns> private static bool HasDefaultConstructor(Type type) { return type.IsValueType || type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null) != null; } private static readonly NumberFormatInfo numberFormat = CreateNumberFormatInfo(); private static NumberFormatInfo CreateNumberFormatInfo() { NumberFormatInfo format = new NumberFormatInfo(); format.CurrencyDecimalSeparator = "."; format.CurrencyGroupSeparator = "_"; format.CurrencyGroupSizes = new[] { 3 }; format.CurrencySymbol = string.Empty; format.CurrencyDecimalDigits = 99; format.NumberDecimalSeparator = "."; format.NumberGroupSeparator = "_"; format.NumberGroupSizes = new[] { 3 }; format.NumberDecimalDigits = 99; return format; } /// <summary> /// Serializes the specified value. /// </summary> /// <param name="emitter">The emitter.</param> /// <param name="type">The type.</param> /// <param name="value">The value.</param> private void SerializeValue(Emitter emitter, Type type, object value) { if (value == null) { emitter.Emit(new Scalar(null, "tag:yaml.org,2002:null", "", ScalarStyle.Plain, false, false)); return; } IYamlSerializable serializable = value as IYamlSerializable; if (serializable != null) { serializable.WriteYaml(emitter); return; } string anchor = null; ObjectInfo info; if (!DisableAliases && anchors.TryGetValue(value, out info) && info != null) { if (info.serialized) { emitter.Emit(new AnchorAlias(info.anchor)); return; } info.serialized = true; anchor = info.anchor; } TypeCode typeCode = Type.GetTypeCode(type); switch (typeCode) { case TypeCode.Boolean: emitter.Emit(new Scalar(anchor, "tag:yaml.org,2002:bool", value.ToString())); break; case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: emitter.Emit(new Scalar(anchor, "tag:yaml.org,2002:int", Convert.ToString(value, numberFormat))); break; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: emitter.Emit(new Scalar(anchor, "tag:yaml.org,2002:float", Convert.ToString(value, numberFormat))); break; case TypeCode.String: case TypeCode.Char: emitter.Emit(new Scalar(anchor, "tag:yaml.org,2002:str", value.ToString())); break; case TypeCode.DateTime: emitter.Emit(new Scalar(anchor, "tag:yaml.org,2002:timestamp", ((DateTime)value).ToString("o", CultureInfo.InvariantCulture))); break; case TypeCode.DBNull: case TypeCode.Empty: throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode)); default: SerializeObject(emitter, type, value, anchor); break; } } #endregion #region Deserialization /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public object Deserialize(TextReader input, out IDeserializationContext context) { return Deserialize(input, null, out context); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <param name="options">The mode.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public object Deserialize(TextReader input, DeserializationOptions options, out IDeserializationContext context) { return Deserialize(new EventReader(new Parser(input)), options, out context); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public object Deserialize(TextReader input) { return Deserialize(input, null); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <param name="options">The mode.</param> /// <returns></returns> public object Deserialize(TextReader input, DeserializationOptions options) { return Deserialize(new EventReader(new Parser(input)), options); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> public object Deserialize(EventReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="options">The mode.</param> /// <returns></returns> public object Deserialize(EventReader reader, DeserializationOptions options) { IDeserializationContext context; return Deserialize(reader, options, out context); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public object Deserialize(EventReader reader, out IDeserializationContext context) { return Deserialize(reader, null, out context); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="options">The mode.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public object Deserialize(EventReader reader, DeserializationOptions options, out IDeserializationContext context) { var internalContext = new DeserializationContext(options); bool hasStreamStart = reader.Accept<StreamStart>(); if (hasStreamStart) { reader.Expect<StreamStart>(); } bool hasDocumentStart = reader.Accept<DocumentStart>(); if (hasDocumentStart) { reader.Expect<DocumentStart>(); } object result = DeserializeValue(reader, serializedType, internalContext); if (hasDocumentStart) { reader.Expect<DocumentEnd>(); } if (hasStreamStart) { reader.Expect<StreamEnd>(); } context = internalContext; return result; } private object DeserializeValue(EventReader reader, Type expectedType, DeserializationContext context) { if (reader.Accept<AnchorAlias>()) { return context.Anchors[reader.Expect<AnchorAlias>().Value]; } NodeEvent nodeEvent = (NodeEvent)reader.Parser.Current; if (nodeEvent.Tag == "tag:yaml.org,2002:null") { reader.Expect<NodeEvent>(); AddAnchoredObject(nodeEvent, null, context.Anchors); return null; } object result = DeserializeValueNotNull(reader, context, nodeEvent, expectedType); return ObjectConverter.Convert(result, expectedType); } private object DeserializeValueNotNull(EventReader reader, DeserializationContext context, INodeEvent nodeEvent, Type expectedType) { Type type = GetType(nodeEvent.Tag, expectedType, context.Options.Mappings); if (typeof(IYamlSerializable).IsAssignableFrom(type)) { return DeserializeYamlSerializable(reader, type); } if (reader.Accept<MappingStart>()) { return DeserializeProperties(reader, type, context); } if (reader.Accept<SequenceStart>()) { return DeserializeList(reader, type, context); } if (reader.Accept<Scalar>()) { return DeserializeScalar(reader, type, context); } throw new InvalidOperationException("Expected scalar, mapping or sequence."); } private static object DeserializeScalar(EventReader reader, Type type, DeserializationContext context) { Scalar scalar = reader.Expect<Scalar>(); object result; type = GetType(scalar.Tag, type, context.Options.Mappings); if (type.IsEnum) { result = Enum.Parse(type, scalar.Value); } else { TypeCode typeCode = Type.GetTypeCode(type); switch (typeCode) { case TypeCode.Boolean: result = bool.Parse(scalar.Value); break; case TypeCode.Byte: result = Byte.Parse(scalar.Value, numberFormat); break; case TypeCode.Int16: result = Int16.Parse(scalar.Value, numberFormat); break; case TypeCode.Int32: result = Int32.Parse(scalar.Value, numberFormat); break; case TypeCode.Int64: result = Int64.Parse(scalar.Value, numberFormat); break; case TypeCode.SByte: result = SByte.Parse(scalar.Value, numberFormat); break; case TypeCode.UInt16: result = UInt16.Parse(scalar.Value, numberFormat); break; case TypeCode.UInt32: result = UInt32.Parse(scalar.Value, numberFormat); break; case TypeCode.UInt64: result = UInt64.Parse(scalar.Value, numberFormat); break; case TypeCode.Single: result = Single.Parse(scalar.Value, numberFormat); break; case TypeCode.Double: result = Double.Parse(scalar.Value, numberFormat); break; case TypeCode.Decimal: result = Decimal.Parse(scalar.Value, numberFormat); break; case TypeCode.String: result = scalar.Value; break; case TypeCode.Char: result = scalar.Value[0]; break; case TypeCode.DateTime: // TODO: This is probably incorrect. Use the correct regular expression. result = DateTime.Parse(scalar.Value, CultureInfo.InvariantCulture); break; default: if (type == typeof(object)) { // Default to string result = scalar.Value; } else { TypeConverter converter = TypeDescriptor.GetConverter(type); if(converter != null && converter.CanConvertFrom(typeof(string))) { result = converter.ConvertFromInvariantString(scalar.Value); } else { result = Convert.ChangeType(scalar.Value, type, CultureInfo.InvariantCulture); } } break; } } AddAnchoredObject(scalar, result, context.Anchors); return result; } private static void AddAnchoredObject(INodeEvent node, object value, ObjectAnchorCollection deserializedAnchors) { if (!string.IsNullOrEmpty(node.Anchor)) { deserializedAnchors.Add(node.Anchor, value); } } // Called through reflection // ReSharper disable UnusedPrivateMember private static void AddAdapter<T>(object list, object value) { ((ICollection<T>)list).Add((T)value); } // ReSharper restore UnusedPrivateMember private static readonly MethodInfo addAdapterGeneric = typeof(YamlSerializer).GetMethod("AddAdapter", BindingFlags.Static | BindingFlags.NonPublic); private object DeserializeList(EventReader reader, Type type, DeserializationContext context) { SequenceStart sequence = reader.Expect<SequenceStart>(); type = GetType(sequence.Tag, type, context.Options.Mappings); // Choose a default list type in case there was no specific type specified. if (type == typeof(object)) { type = typeof(ArrayList); } object result = Activator.CreateInstance(type); Type iCollection = GetImplementedGenericInterface(type, typeof(ICollection<>)); if (iCollection != null) { Type[] iCollectionArguments = iCollection.GetGenericArguments(); Debug.Assert(iCollectionArguments.Length == 1, "ICollection<> must have one generic argument."); MethodInfo addAdapter = addAdapterGeneric.MakeGenericMethod(iCollectionArguments); Action<object, object> addAdapterDelegate = (Action<object, object>)Delegate.CreateDelegate(typeof(Action<object, object>), addAdapter); DeserializeGenericListInternal(reader, iCollectionArguments[0], result, addAdapterDelegate, context); } else { IList list = result as IList; if (list != null) { while (!reader.Accept<SequenceEnd>()) { list.Add(DeserializeValue(reader, typeof(object), context)); } } reader.Expect<SequenceEnd>(); } AddAnchoredObject(sequence, result, context.Anchors); return result; } private void DeserializeGenericListInternal(EventReader reader, Type itemType, object list, Action<object, object> addAdapterDelegate, DeserializationContext context) { while (!reader.Accept<SequenceEnd>()) { addAdapterDelegate(list, DeserializeValue(reader, itemType, context)); } reader.Expect<SequenceEnd>(); } private static Type GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type interfacetype in GetImplementedInterfaces(type)) { if (interfacetype.IsGenericType && interfacetype.GetGenericTypeDefinition() == genericInterfaceType) { return interfacetype; } } return null; } private static IEnumerable<Type> GetImplementedInterfaces(Type type) { if (type.IsInterface) { yield return type; } foreach (var implementedInterface in type.GetInterfaces()) { yield return implementedInterface; } } private static Type GetItemType(Type type, Type genericInterfaceType) { var implementedInterface = GetImplementedGenericInterface(type, genericInterfaceType); return implementedInterface != null ? implementedInterface.GetGenericArguments()[0] : typeof(object); } private static Type GetObjectType(object value) { return value != null ? value.GetType() : typeof(object); } private static object DeserializeYamlSerializable(EventReader reader, Type type) { IYamlSerializable result = (IYamlSerializable)Activator.CreateInstance(type); result.ReadYaml(reader.Parser); return result; } private object DeserializeProperties(EventReader reader, Type type, DeserializationContext context) { MappingStart mapping = reader.Expect<MappingStart>(); type = GetType(mapping.Tag, type, context.Options.Mappings); object result = Activator.CreateInstance(type); IDictionary dictionary = result as IDictionary; if (dictionary != null) { Type keyType = typeof(object); Type valueType = typeof(object); foreach (var interfaceType in result.GetType().GetInterfaces()) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { Type[] genericArguments = interfaceType.GetGenericArguments(); Debug.Assert(genericArguments.Length == 2, "IDictionary<,> must contain two generic arguments."); keyType = genericArguments[0]; valueType = genericArguments[1]; break; } } while (!reader.Accept<MappingEnd>()) { object key = DeserializeValue(reader, keyType, context); object value = DeserializeValue(reader, valueType, context); dictionary.Add(key, value); } } else { while (!reader.Accept<MappingEnd>()) { Scalar key = reader.Expect<Scalar>(); bool isOverriden = false; if (context.Options != null) { var deserializer = context.Options.Overrides.GetOverride(type, key.Value); if (deserializer != null) { isOverriden = true; deserializer(result, reader); } } if (!isOverriden) { PropertyInfo property = type.GetProperty(key.Value, BindingFlags.Instance | BindingFlags.Public); if (property == null) { Console.WriteLine(key); throw new SerializationException( string.Format( CultureInfo.InvariantCulture, "Property '{0}' not found on type '{1}'", key.Value, type.FullName ) ); } property.SetValue(result, DeserializeValue(reader, property.PropertyType, context), null); } } } reader.Expect<MappingEnd>(); AddAnchoredObject(mapping, result, context.Anchors); return result; } private static readonly Dictionary<string, Type> predefinedTypes = new Dictionary<string, Type> { { "tag:yaml.org,2002:map", typeof(Dictionary<object, object>) }, { "tag:yaml.org,2002:bool", typeof(bool) }, { "tag:yaml.org,2002:float", typeof(double) }, { "tag:yaml.org,2002:int", typeof(int) }, { "tag:yaml.org,2002:str", typeof(string) }, { "tag:yaml.org,2002:timestamp", typeof(DateTime) }, }; private static readonly Dictionary<Type, Type> defaultInterfaceImplementations = new Dictionary<Type, Type> { { typeof(IEnumerable<>), typeof(List<>) }, { typeof(ICollection<>), typeof(List<>) }, { typeof(IList<>), typeof(List<>) }, { typeof(IDictionary<,>), typeof(Dictionary<,>) }, }; private static Type GetType(string tag, Type defaultType, TagMappings mappings) { Type actualType = GetTypeFromTag(tag, defaultType, mappings); if (actualType.IsInterface) { Type implementationType; if (defaultInterfaceImplementations.TryGetValue(actualType.GetGenericTypeDefinition(), out implementationType)) { return implementationType.MakeGenericType(actualType.GetGenericArguments()); } } return actualType; } private static Type GetTypeFromTag(string tag, Type defaultType, TagMappings mappings) { if (tag == null) { return defaultType; } Type predefinedType = mappings.GetMapping(tag); if (predefinedType != null || predefinedTypes.TryGetValue(tag, out predefinedType)) { return predefinedType; } return Type.GetType(tag.Substring(1), true); } #endregion } /// <summary> /// Extension of the <see cref="YamlSerializer"/> type that avoida the need for casting /// on the user's code. /// </summary> /// <typeparam name="TSerialized">The type of the serialized.</typeparam> public class YamlSerializer<TSerialized> : YamlSerializer { /// <summary> /// Initializes a new instance of the <see cref="YamlSerializer{TSerialized}"/> class. /// </summary> public YamlSerializer() : base(typeof(TSerialized)) { } /// <summary> /// Initializes a new instance of the <see cref="YamlSerializer{TSerialized}"/> class. /// </summary> /// <param name="mode">The options.</param> public YamlSerializer(YamlSerializerModes mode) : base(typeof(TSerialized), mode) { } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> public new TSerialized Deserialize(TextReader input) { return (TSerialized)base.Deserialize(input); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <param name="options">The options.</param> /// <returns></returns> public new TSerialized Deserialize(TextReader input, DeserializationOptions options) { return (TSerialized)base.Deserialize(input, options); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public new TSerialized Deserialize(TextReader input, out IDeserializationContext context) { return (TSerialized)base.Deserialize(input, out context); } /// <summary> /// Deserializes an object from the specified stream. /// </summary> /// <param name="input">The input.</param> /// <param name="options">The options.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public new TSerialized Deserialize(TextReader input, DeserializationOptions options, out IDeserializationContext context) { return (TSerialized)base.Deserialize(input, options, out context); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <returns></returns> public new TSerialized Deserialize(EventReader reader) { return (TSerialized)base.Deserialize(reader); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="options">The options.</param> /// <returns></returns> public new TSerialized Deserialize(EventReader reader, DeserializationOptions options) { return (TSerialized)base.Deserialize(reader, options); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public new TSerialized Deserialize(EventReader reader, out IDeserializationContext context) { return (TSerialized)base.Deserialize(reader, out context); } /// <summary> /// Deserializes the specified reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="options">The options.</param> /// <param name="context">Returns additional information about the deserialization process.</param> /// <returns></returns> public new TSerialized Deserialize(EventReader reader, DeserializationOptions options, out IDeserializationContext context) { return (TSerialized)base.Deserialize(reader, options, out context); } } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: ViewModel.tt using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Windows.Input; using WPAppStudio; using WPAppStudio.Controls; using WPAppStudio.Entities; using WPAppStudio.Entities.Base; using WPAppStudio.Localization; using WPAppStudio.Repositories; using WPAppStudio.Services; using WPAppStudio.Services.Interfaces; using WPAppStudio.Shared; using WPAppStudio.ViewModel.Base; using WPAppStudio.ViewModel.Interfaces; namespace WPAppStudio.ViewModel { /// <summary> /// Implementation of ThePlace_Info ViewModel. /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] [System.CodeDom.Compiler.GeneratedCode("Radarc", "4.0")] public partial class ThePlace_InfoViewModel : BindableBase, IThePlace_InfoViewModel { private readonly IDialogService _dialogService; private readonly INavigationService _navigationService; private readonly ILockScreenService _lockScreenService; private readonly IThePlaceDataSource _thePlaceDataSource; private readonly IphotosCollection _photosCollection; private readonly IdiaryCollection _diaryCollection; private readonly IfellowsCollection _fellowsCollection; private readonly ITheNextOneCollection _theNextOneCollection; /// <summary> /// Initializes a new instance of the <see cref="ThePlace_InfoViewModel" /> class. /// </summary> /// <param name="dialogService">The Dialog Service.</param> /// <param name="navigationService">The Navigation Service.</param> /// <param name="lockScreenService">The Lock Screen Service.</param> /// <param name="thePlaceDataSource">The The Place Data Source.</param> /// <param name="photosCollection">The Photos Collection.</param> /// <param name="diaryCollection">The Diary Collection.</param> /// <param name="fellowsCollection">The Fellows Collection.</param> /// <param name="theNextOneCollection">The The Next One Collection.</param> public ThePlace_InfoViewModel(IDialogService dialogService, INavigationService navigationService, ILockScreenService lockScreenService, IThePlaceDataSource thePlaceDataSource, IphotosCollection photosCollection, IdiaryCollection diaryCollection, IfellowsCollection fellowsCollection, ITheNextOneCollection theNextOneCollection) { _dialogService = dialogService; _navigationService = navigationService; _lockScreenService = lockScreenService; _thePlaceDataSource = thePlaceDataSource; _photosCollection = photosCollection; _diaryCollection = diaryCollection; _fellowsCollection = fellowsCollection; _theNextOneCollection = theNextOneCollection; } private string _currentThePlace_InfoHtmlControl; /// <summary> /// CurrentThePlace_InfoHtmlControl property. /// </summary> public string CurrentThePlace_InfoHtmlControl { get { if(_currentThePlace_InfoHtmlControl == null) _currentThePlace_InfoHtmlControl = _thePlaceDataSource.Get(); return _currentThePlace_InfoHtmlControl; } set { SetProperty(ref _currentThePlace_InfoHtmlControl, value); } } private ObservableCollection<photosCollectionSchema> _photos_AlbumListControlCollection; /// <summary> /// Photos_AlbumListControlCollection property. /// </summary> public ObservableCollection<photosCollectionSchema> Photos_AlbumListControlCollection { get { if(_photos_AlbumListControlCollection == null) _photos_AlbumListControlCollection = _photosCollection.GetData(); return _photos_AlbumListControlCollection; } set { SetProperty(ref _photos_AlbumListControlCollection, value); } } private photosCollectionSchema _selectedphotos_AlbumListControlCollection; /// <summary> /// Selectedphotos_AlbumListControlCollection property. /// </summary> public photosCollectionSchema Selectedphotos_AlbumListControlCollection { get { return _selectedphotos_AlbumListControlCollection; } set { _selectedphotos_AlbumListControlCollection = value; if (value != null) _navigationService.NavigateTo<Iphotos_DetailViewModel>(_selectedphotos_AlbumListControlCollection); } } private ObservableCollection<diarySchema> _diary_ListListControlCollection; /// <summary> /// Diary_ListListControlCollection property. /// </summary> public ObservableCollection<diarySchema> Diary_ListListControlCollection { get { if(_diary_ListListControlCollection == null) _diary_ListListControlCollection = _diaryCollection.GetData(); return _diary_ListListControlCollection; } set { SetProperty(ref _diary_ListListControlCollection, value); } } private diarySchema _selecteddiary_ListListControlCollection; /// <summary> /// Selecteddiary_ListListControlCollection property. /// </summary> public diarySchema Selecteddiary_ListListControlCollection { get { return _selecteddiary_ListListControlCollection; } set { _selecteddiary_ListListControlCollection = value; if (value != null) _navigationService.NavigateTo<Idiary_DetailViewModel>(_selecteddiary_ListListControlCollection); } } private ObservableCollection<fellowsSchema> _fellows_ListListControlCollection; /// <summary> /// Fellows_ListListControlCollection property. /// </summary> public ObservableCollection<fellowsSchema> Fellows_ListListControlCollection { get { if(_fellows_ListListControlCollection == null) _fellows_ListListControlCollection = _fellowsCollection.GetData(); return _fellows_ListListControlCollection; } set { SetProperty(ref _fellows_ListListControlCollection, value); } } private fellowsSchema _selectedfellows_ListListControlCollection; /// <summary> /// Selectedfellows_ListListControlCollection property. /// </summary> public fellowsSchema Selectedfellows_ListListControlCollection { get { return _selectedfellows_ListListControlCollection; } set { _selectedfellows_ListListControlCollection = value; if (value != null) _navigationService.NavigateTo<Ifellows_DetailViewModel>(_selectedfellows_ListListControlCollection); } } private ObservableCollection<TheNextOneSchema> _theNextOne_ListListControlCollection; /// <summary> /// TheNextOne_ListListControlCollection property. /// </summary> public ObservableCollection<TheNextOneSchema> TheNextOne_ListListControlCollection { get { if(_theNextOne_ListListControlCollection == null) RefreshTheNextOne_ListListControlCollectionDelegate(); return _theNextOne_ListListControlCollection; } set { SetProperty(ref _theNextOne_ListListControlCollection, value); } } private TheNextOneSchema _selectedTheNextOne_ListListControlCollection; /// <summary> /// SelectedTheNextOne_ListListControlCollection property. /// </summary> public TheNextOneSchema SelectedTheNextOne_ListListControlCollection { get { return _selectedTheNextOne_ListListControlCollection; } set { _selectedTheNextOne_ListListControlCollection = value; if (value != null) _navigationService.NavigateTo<ITheNextOne_DetailViewModel>(_selectedTheNextOne_ListListControlCollection); } } /// <summary> /// Delegate method for the RefreshTheNextOne_ListListControlCollection command. /// </summary> public async void RefreshTheNextOne_ListListControlCollectionDelegate(int pageNumber= 1) { try { LoadingTheNextOne_ListListControlCollection = true; TheNextOne_ListListControlCollection = await _theNextOneCollection.GetData(); } catch (Exception ex) { TheNextOne_ListListControlCollection = null; Debug.WriteLine(ex.ToString()); _dialogService.Show(AppResources.DynamicDataError + Environment.NewLine + AppResources.TryAgain); } finally { LoadingTheNextOne_ListListControlCollection = false; } } private bool _loadingTheNextOne_ListListControlCollection; public bool LoadingTheNextOne_ListListControlCollection { get { return _loadingTheNextOne_ListListControlCollection; } set { SetProperty(ref _loadingTheNextOne_ListListControlCollection, value); } } private ICommand _refreshTheNextOne_ListListControlCollection; /// <summary> /// Gets the RefreshTheNextOne_ListListControlCollection command. /// </summary> public ICommand RefreshTheNextOne_ListListControlCollection { get { return _refreshTheNextOne_ListListControlCollection = _refreshTheNextOne_ListListControlCollection ?? new DelegateCommand<int>(RefreshTheNextOne_ListListControlCollectionDelegate); } } /// <summary> /// Delegate method for the SetLockScreenCommand command. /// </summary> public void SetLockScreenCommandDelegate() { _lockScreenService.SetLockScreen("LockScreen-fe1d364f-e0e1-4f58-b1bb-0ce2fe67aefa.jpg"); } private ICommand _setLockScreenCommand; /// <summary> /// Gets the SetLockScreenCommand command. /// </summary> public ICommand SetLockScreenCommand { get { return _setLockScreenCommand = _setLockScreenCommand ?? new DelegateCommand(SetLockScreenCommandDelegate); } } } }
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Text; using Hazelcast.Net.Ext; namespace Hazelcast.IO.Serialization { internal class ByteArrayObjectDataOutput : IOutputStream, IBufferObjectDataOutput { private readonly int _initialSize; private readonly bool _isBigEndian; private readonly ISerializationService _service; internal ByteArrayObjectDataOutput(int size, ISerializationService service, ByteOrder byteOrder) { _initialSize = size; Buffer = new byte[size]; _service = service; _isBigEndian = byteOrder == ByteOrder.BigEndian; } internal byte[] Buffer { get; set; } internal int Pos { get; set; } public virtual void Write(int position, int b) { Buffer[position] = unchecked((byte) b); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteBoolean(bool v) { Write(v ? 1 : 0); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteBoolean(int position, bool v) { Write(position, v ? 1 : 0); } /// <exception cref="System.IO.IOException"></exception> public void WriteByte(int v) { Write(v); } public void WriteZeroBytes(int count) { for (var k = 0; k < count; k++) { Write(0); } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteByte(int position, int v) { Write(position, v); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteBytes(string s) { var len = s.Length; EnsureAvailable(len); for (var i = 0; i < len; i++) { Buffer[Pos++] = unchecked((byte) s[i]); } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteChar(int v) { EnsureAvailable(Bits.CharSizeInBytes); Bits.WriteChar(Buffer, Pos, (char) v, _isBigEndian); Pos += Bits.CharSizeInBytes; } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteChar(int position, int v) { Bits.WriteChar(Buffer, position, (char) v, _isBigEndian); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteChars(string s) { var len = s.Length; EnsureAvailable(len*Bits.CharSizeInBytes); for (var i = 0; i < len; i++) { int v = s[i]; WriteChar(Pos, v); Pos += Bits.CharSizeInBytes; } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteDouble(double v) { WriteLong(BitConverter.DoubleToInt64Bits(v)); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteDouble(int position, double v) { WriteLong(position, BitConverter.DoubleToInt64Bits(v)); } public void WriteDouble(double v, ByteOrder byteOrder) { WriteLong(BitConverter.DoubleToInt64Bits(v), byteOrder); } public void WriteDouble(int position, double v, ByteOrder byteOrder) { WriteLong(position, BitConverter.DoubleToInt64Bits(v), byteOrder); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteFloat(float v) { WriteInt(BitConverter.ToInt32(BitConverter.GetBytes(v), 0)); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteFloat(int position, float v) { WriteInt(position, BitConverter.ToInt32(BitConverter.GetBytes(v), 0)); } public void WriteFloat(float v, ByteOrder byteOrder) { WriteInt(BitConverter.ToInt32(BitConverter.GetBytes(v), 0), byteOrder); } public void WriteFloat(int position, float v, ByteOrder byteOrder) { WriteInt(position, BitConverter.ToInt32(BitConverter.GetBytes(v), 0), byteOrder); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteInt(int v) { EnsureAvailable(Bits.IntSizeInBytes); Bits.WriteInt(Buffer, Pos, v, _isBigEndian); Pos += Bits.IntSizeInBytes; } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteInt(int position, int v) { Bits.WriteInt(Buffer, position, v, _isBigEndian); } public void WriteInt(int v, ByteOrder byteOrder) { EnsureAvailable(Bits.IntSizeInBytes); Bits.WriteInt(Buffer, Pos, v, byteOrder == ByteOrder.BigEndian); Pos += Bits.IntSizeInBytes; } public void WriteInt(int position, int v, ByteOrder byteOrder) { Bits.WriteInt(Buffer, position, v, byteOrder == ByteOrder.BigEndian); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteLong(long v) { EnsureAvailable(Bits.LongSizeInBytes); Bits.WriteLong(Buffer, Pos, v, _isBigEndian); Pos += Bits.LongSizeInBytes; } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteLong(int position, long v) { Bits.WriteLong(Buffer, position, v, _isBigEndian); } public void WriteLong(long v, ByteOrder byteOrder) { EnsureAvailable(Bits.LongSizeInBytes); Bits.WriteLong(Buffer, Pos, v, byteOrder == ByteOrder.BigEndian); Pos += Bits.LongSizeInBytes; } public void WriteLong(int position, long v, ByteOrder byteOrder) { Bits.WriteLong(Buffer, position, v, byteOrder == ByteOrder.BigEndian); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteShort(int v) { EnsureAvailable(Bits.ShortSizeInBytes); Bits.WriteShort(Buffer, Pos, (short) v, _isBigEndian); Pos += Bits.ShortSizeInBytes; } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteShort(int position, int v) { Bits.WriteShort(Buffer, position, (short) v, _isBigEndian); } public void WriteShort(int v, ByteOrder byteOrder) { EnsureAvailable(Bits.ShortSizeInBytes); Bits.WriteShort(Buffer, Pos, (short) v, byteOrder == ByteOrder.BigEndian); Pos += Bits.ShortSizeInBytes; } public void WriteShort(int position, int v, ByteOrder byteOrder) { Bits.WriteShort(Buffer, position, (short) v, byteOrder == ByteOrder.BigEndian); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteUTF(string str) { var len = (str != null) ? str.Length : Bits.NullArray; WriteInt(len); if (len > 0) { EnsureAvailable(len*3); for (var i = 0; i < len; i++) { Pos += Bits.WriteUtf8Char(Buffer, Pos, str[i]); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteByteArray(byte[] bytes) { var len = (bytes != null) ? bytes.Length : Bits.NullArray; WriteInt(len); if (len > 0) { Write(bytes, 0, len); } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteBooleanArray(bool[] bools) { var len = (bools != null) ? bools.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var b in bools) { WriteBoolean(b); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteCharArray(char[] chars) { var len = (chars != null) ? chars.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var c in chars) { WriteChar(c); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteIntArray(int[] ints) { var len = (ints != null) ? ints.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var i in ints) { WriteInt(i); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteLongArray(long[] longs) { var len = (longs != null) ? longs.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var l in longs) { WriteLong(l); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteDoubleArray(double[] doubles) { var len = (doubles != null) ? doubles.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var d in doubles) { WriteDouble(d); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteFloatArray(float[] floats) { var len = (floats != null) ? floats.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var f in floats) { WriteFloat(f); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteShortArray(short[] shorts) { var len = (shorts != null) ? shorts.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var s in shorts) { WriteShort(s); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteUTFArray(string[] strings) { var len = (strings != null) ? strings.Length : Bits.NullArray; WriteInt(len); if (len > 0) { foreach (var s in strings) { WriteUTF(s); } } } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteObject(object @object) { _service.WriteObject(this, @object); } /// <exception cref="System.IO.IOException"></exception> public virtual void WriteData(IData data) { var payload = data != null ? data.ToByteArray() : null; WriteByteArray(payload); } /// <summary>Returns this buffer's position.</summary> public virtual int Position() { return Pos; } public virtual void Position(int newPos) { if ((newPos > Buffer.Length) || (newPos < 0)) { throw new ArgumentException(); } Pos = newPos; } public virtual byte[] ToByteArray() { if (Buffer == null || Pos == 0) { return new byte[0]; } var newBuffer = new byte[Pos]; Array.Copy(Buffer, 0, newBuffer, 0, Pos); return newBuffer; } public virtual void Clear() { Pos = 0; if (Buffer != null && Buffer.Length > _initialSize*8) { Buffer = new byte[_initialSize*8]; } } public void Dispose() { Close(); } public virtual ByteOrder GetByteOrder() { return _isBigEndian ? ByteOrder.BigEndian : ByteOrder.LittleEndian; } public void Write(int b) { EnsureAvailable(1); Buffer[Pos++] = unchecked((byte) (b)); } public void Write(byte[] b) { Write(b, 0, b.Length); } public virtual void Write(byte[] b, int off, int len) { if ((off < 0) || (off > b.Length) || (len < 0) || ((off + len) > b.Length) || ((off + len) < 0)) { throw new IndexOutOfRangeException(); } if (len == 0) { return; } EnsureAvailable(len); Array.Copy(b, off, Buffer, Pos, len); Pos += len; } public void Flush() { } public virtual void Close() { Pos = 0; Buffer = null; } public virtual int Available() { return Buffer != null ? Buffer.Length - Pos : 0; } public override string ToString() { var sb = new StringBuilder(); sb.Append("ByteArrayObjectDataOutput"); sb.Append("{size=").Append(Buffer != null ? Buffer.Length : 0); sb.Append(", pos=").Append(Pos); sb.Append('}'); return sb.ToString(); } internal void EnsureAvailable(int len) { if (Available() < len) { if (Buffer != null) { var newCap = Math.Max(Buffer.Length << 1, Buffer.Length + len); var newBuffer = new byte[newCap]; Array.Copy(Buffer, 0, newBuffer, 0, Pos); Buffer = newBuffer; } else { Buffer = new byte[len > _initialSize/2 ? len*2 : _initialSize]; } } } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.NetworkAnalyst; using ESRI.ArcGIS.ArcMapUI; using ESRI.ArcGIS.NetworkAnalystUI; using SubsetNetworkEvaluators; namespace SubsetNetworkEvaluatorsUI { /// <summary> /// This command toggles on and off the event based behavior to update the relevant subset parameter arrays /// automatically by listening to selection change events and graphic element change events. When the command /// is toggled off, the subset parameter arrays are cleared out and the results may not match the current selection /// or graphic element geometries in this case. /// </summary> [Guid("f213e01f-3a45-44c7-a350-397a794e9084")] [ClassInterface(ClassInterfaceType.None)] [ProgId("SubsetNetworkEvaluatorsUI.AutoUpdateNetworkElementArrayParametersCommand")] public sealed class AutoUpdateNetworkElementArrayParametersCommand : BaseCommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); MxCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); MxCommands.Unregister(regKey); } #endregion #endregion private IApplication m_application = null; private INetworkAnalystExtension m_nax = null; private INAWindow m_naWindowEventSource = null; private IMap m_mapEventSource = null; private IGraphicsContainer m_graphicsEventSource = null; private ESRI.ArcGIS.NetworkAnalystUI.INAWindowEvents_OnActiveAnalysisChangedEventHandler m_ActiveAnalysisChanged; private ESRI.ArcGIS.Carto.IActiveViewEvents_SelectionChangedEventHandler m_ActiveViewEventsSelectionChanged; private ESRI.ArcGIS.Carto.IGraphicsContainerEvents_AllElementsDeletedEventHandler m_AllGraphicsDeleted; private ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementAddedEventHandler m_GraphicAdded; private ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementDeletedEventHandler m_GraphicDeleted; private ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementsAddedEventHandler m_GraphicsAdded; private ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementUpdatedEventHandler m_GraphicUpdated; public AutoUpdateNetworkElementArrayParametersCommand() { base.m_category = "Network Analyst Samples"; //localizable text base.m_caption = "Auto Update Network Element Array Parameters"; //localizable text base.m_message = "Auto Update Network Element Array Parameters"; //localizable text base.m_toolTip = "Auto Update Network Element Array Parameters"; //localizable text base.m_name = "NASamples_AutoUpdateNetworkElementArrayParameters"; //unique id, non-localizable (e.g. "MyCategory_ArcMapCommand") try { // // TODO: change bitmap name if necessary // string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #region Overriden Class Methods /// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { if (hook == null) return; m_application = hook as IApplication; m_nax = null; m_naWindowEventSource = null; m_mapEventSource = null; m_graphicsEventSource = null; m_nax = SubsetHelperUI.GetNAXConfiguration(m_application) as INetworkAnalystExtension; } public override bool Enabled { get { bool naxEnabled = false; IExtensionConfig naxConfig = m_nax as IExtensionConfig; if (naxConfig != null) naxEnabled = naxConfig.State == esriExtensionState.esriESEnabled; INALayer naLayer = null; INetworkDataset nds = null; if (naxEnabled) { INAWindow naWindow = m_nax.NAWindow; naLayer = naWindow.ActiveAnalysis; INAContext naContext = null; if (naLayer != null) naContext = naLayer.Context; if (naContext != null) nds = naContext.NetworkDataset; } bool enable = naxEnabled && (naLayer != null) && (nds != null); if (!enable && m_naWindowEventSource != null) UnWireEvents(); base.m_enabled = enable; return base.Enabled; } } /// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { if (m_naWindowEventSource != null) UnWireEvents(); else WireEvents(); } public override bool Checked { get { return (m_naWindowEventSource != null); } } private void WireEvents() { try { if (m_naWindowEventSource != null) UnWireEvents(); m_naWindowEventSource = ((m_nax != null) ? m_nax.NAWindow : null) as INAWindow; if (m_naWindowEventSource == null) return; //Create an instance of the delegate, add it to OnActiveAnalysisChanged event m_ActiveAnalysisChanged = new ESRI.ArcGIS.NetworkAnalystUI.INAWindowEvents_OnActiveAnalysisChangedEventHandler(OnActiveAnalysisChanged); ((ESRI.ArcGIS.NetworkAnalystUI.INAWindowEvents_Event)(m_naWindowEventSource)).OnActiveAnalysisChanged += m_ActiveAnalysisChanged; WireSelectionEvent(); WireGraphicsEvents(); } catch (Exception ex) { string msg = SubsetHelperUI.GetFullExceptionMessage(ex); MessageBox.Show(msg, "Wire Events"); } } private void UnWireEvents() { try { if (m_naWindowEventSource == null) return; UnWireSelectionEvent(); UnWireGraphicsEvents(); ((ESRI.ArcGIS.NetworkAnalystUI.INAWindowEvents_Event)(m_naWindowEventSource)).OnActiveAnalysisChanged -= m_ActiveAnalysisChanged; m_naWindowEventSource = null; } catch (Exception ex) { string msg = SubsetHelperUI.GetFullExceptionMessage(ex); MessageBox.Show(msg, "UnWire Events"); } } private void WireSelectionEvent() { try { if (m_naWindowEventSource == null) return; if (m_mapEventSource != null) UnWireSelectionEvent(); m_mapEventSource = ActiveMap; if (m_mapEventSource == null) return; UpdateSelectionEIDArrayParameterValues(); //Create an instance of the delegate, add it to SelectionChanged event m_ActiveViewEventsSelectionChanged = new ESRI.ArcGIS.Carto.IActiveViewEvents_SelectionChangedEventHandler(OnActiveViewEventsSelectionChanged); ((ESRI.ArcGIS.Carto.IActiveViewEvents_Event)(m_mapEventSource)).SelectionChanged += m_ActiveViewEventsSelectionChanged; } catch (Exception ex) { string msg = SubsetHelperUI.GetFullExceptionMessage(ex); MessageBox.Show(msg, "Wire Selection Event"); } } private void UnWireSelectionEvent() { try { if (m_naWindowEventSource == null) return; if (m_mapEventSource == null) return; ((ESRI.ArcGIS.Carto.IActiveViewEvents_Event)(m_mapEventSource)).SelectionChanged -= m_ActiveViewEventsSelectionChanged; m_mapEventSource = null; SubsetHelperUI.ClearEIDArrayParameterValues(m_nax, SubsetHelperUI.SelectionEIDArrayBaseName); } catch (Exception ex) { string msg = SubsetHelperUI.GetFullExceptionMessage(ex); MessageBox.Show(msg, "UnWire Selection Event"); } } private void WireGraphicsEvents() { try { if (m_naWindowEventSource == null) return; if (m_graphicsEventSource != null) UnWireGraphicsEvents(); IMap activeMap = ActiveMap; IGraphicsLayer graphicsLayer = null; if (activeMap != null) graphicsLayer = activeMap.BasicGraphicsLayer; if (graphicsLayer != null) m_graphicsEventSource = (IGraphicsContainer)graphicsLayer; if (m_graphicsEventSource == null) return; UpdateGraphicsEIDArrayParameterValues(); //Create an instance of the delegate, add it to AllElementsDeleted event m_AllGraphicsDeleted = new ESRI.ArcGIS.Carto.IGraphicsContainerEvents_AllElementsDeletedEventHandler(OnAllGraphicsDeleted); ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).AllElementsDeleted += m_AllGraphicsDeleted; //Create an instance of the delegate, add it to ElementAdded event m_GraphicAdded = new ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementAddedEventHandler(OnGraphicAdded); ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementAdded += m_GraphicAdded; //Create an instance of the delegate, add it to ElementDeleted event m_GraphicDeleted = new ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementDeletedEventHandler(OnGraphicDeleted); ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementDeleted += m_GraphicDeleted; //Create an instance of the delegate, add it to ElementsAdded event m_GraphicsAdded = new ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementsAddedEventHandler(OnGraphicsAdded); ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementsAdded += m_GraphicsAdded; //Create an instance of the delegate, add it to ElementUpdated event m_GraphicUpdated = new ESRI.ArcGIS.Carto.IGraphicsContainerEvents_ElementUpdatedEventHandler(OnGraphicUpdated); ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementUpdated += m_GraphicUpdated; } catch (Exception ex) { string msg = SubsetHelperUI.GetFullExceptionMessage(ex); MessageBox.Show(msg, "Wire Graphics Events"); } } private void UnWireGraphicsEvents() { try { if (m_naWindowEventSource == null) return; if (m_graphicsEventSource == null) return; ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).AllElementsDeleted -= m_AllGraphicsDeleted; ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementAdded -= m_GraphicAdded; ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementDeleted -= m_GraphicDeleted; ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementsAdded -= m_GraphicsAdded; ((ESRI.ArcGIS.Carto.IGraphicsContainerEvents_Event)(m_graphicsEventSource)).ElementUpdated -= m_GraphicUpdated; m_graphicsEventSource = null; SubsetHelperUI.ClearEIDArrayParameterValues(m_nax, SubsetHelperUI.GraphicsEIDArrayBaseName); } catch (Exception ex) { string msg = SubsetHelperUI.GetFullExceptionMessage(ex); MessageBox.Show(msg, "UnWire Graphics Events"); } } #endregion private void UpdateSelectionEIDArrayParameterValues() { IMap map = ActiveMap; if (map == null) return; INAWindow naWindow = m_nax.NAWindow; INALayer naLayer = null; INAContext naContext = null; INetworkDataset nds = null; naLayer = naWindow.ActiveAnalysis; if (naLayer != null) naContext = naLayer.Context; if (naContext != null) nds = naContext.NetworkDataset; if (nds == null) return; string baseName = SubsetHelperUI.SelectionEIDArrayBaseName; VarType vt = SubsetHelperUI.GetEIDArrayParameterType(); List<string> sourceNames = SubsetHelperUI.FindParameterizedSourceNames(nds, baseName, vt); Dictionary<string, ILongArray> oidArraysBySourceName = SubsetHelperUI.GetOIDArraysBySourceNameFromMapSelection(map, sourceNames); SubsetHelperUI.UpdateEIDArrayParameterValuesFromOIDArrays(m_nax, oidArraysBySourceName, baseName); } private void UpdateGraphicsEIDArrayParameterValues() { IGraphicsContainer graphics = ActiveGraphics; if (graphics == null) return; INAWindow naWindow = m_nax.NAWindow; INALayer naLayer = null; INAContext naContext = null; INetworkDataset nds = null; naLayer = naWindow.ActiveAnalysis; if (naLayer != null) naContext = naLayer.Context; if (naContext != null) nds = naContext.NetworkDataset; if (nds == null) return; string baseName = SubsetHelperUI.GraphicsEIDArrayBaseName; VarType vt = SubsetHelperUI.GetEIDArrayParameterType(); List<string> sourceNames = SubsetHelperUI.FindParameterizedSourceNames(nds, baseName, vt); IGeometry searchGeometry = SubsetHelperUI.GetSearchGeometryFromGraphics(graphics); SubsetHelperUI.UpdateEIDArrayParameterValuesFromGeometry(m_nax, searchGeometry, baseName); } private IMap ActiveMap { get { IDocument doc = m_application.Document; IMxDocument mxdoc = doc as IMxDocument; return (IMap)mxdoc.FocusMap; } } private IGraphicsContainer ActiveGraphics { get { IMap activeMap = ActiveMap; IGraphicsContainer graphics = null; if (activeMap != null) graphics = activeMap.BasicGraphicsLayer as IGraphicsContainer; return graphics; } } #region Event Handlers #region NAWindow Event Handlers private void OnActiveAnalysisChanged() { if (m_mapEventSource != null) WireSelectionEvent(); if (m_graphicsEventSource != null) WireGraphicsEvents(); } #endregion #region Selection Event Handler private void OnActiveViewEventsSelectionChanged() { UpdateSelectionEIDArrayParameterValues(); } #endregion #region Graphics Event Handlers private void OnAllGraphicsDeleted() { UpdateGraphicsEIDArrayParameterValues(); } private void OnGraphicAdded(IElement element) { UpdateGraphicsEIDArrayParameterValues(); } private void OnGraphicDeleted(IElement element) { UpdateGraphicsEIDArrayParameterValues(); } private void OnGraphicsAdded(IElementCollection elements) { UpdateGraphicsEIDArrayParameterValues(); } private void OnGraphicUpdated(IElement element) { UpdateGraphicsEIDArrayParameterValues(); } #endregion #endregion } }
#if !UNITY_EDITOR_OSX || MAC_FORCE_TESTS using System; using NUnit.Framework; using UnityEngine; using UnityEngine.Experimental.VFX; using UnityEditor.Experimental.VFX; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEditor.VFX.UI; using System.IO; using UnityEngine.TestTools; using UnityEditor.VFX.Block.Test; namespace UnityEditor.VFX.Test { [TestFixture] public class VFXControllersTests { VFXViewController m_ViewController; const string testAssetName = "Assets/TmpTests/VFXGraph1.vfx"; private int m_StartUndoGroupId; [SetUp] public void CreateTestAsset() { var directoryPath = Path.GetDirectoryName(testAssetName); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } if (File.Exists(testAssetName)) { AssetDatabase.DeleteAsset(testAssetName); } VisualEffectAsset asset = VisualEffectAssetEditorUtility.CreateNewAsset(testAssetName); VisualEffectResource resource = asset.GetResource(); // force resource creation m_ViewController = VFXViewController.GetController(resource); m_ViewController.useCount++; m_StartUndoGroupId = Undo.GetCurrentGroup(); } [TearDown] public void DestroyTestAsset() { m_ViewController.useCount--; Undo.RevertAllDownToGroup(m_StartUndoGroupId); AssetDatabase.DeleteAsset(testAssetName); } #pragma warning disable 0414 static private bool[] usePosition = { true, false }; #pragma warning restore 0414 [Test] public void LinkPositionOrVectorAndDirection([ValueSource("usePosition")] bool usePosition) { var crossDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name.Contains("Cross")); var positionDesc = VFXLibrary.GetParameters().FirstOrDefault(o => o.name.Contains("Position")); var vectorDesc = VFXLibrary.GetParameters().FirstOrDefault(o => o.name == "Vector"); var directionDesc = VFXLibrary.GetParameters().FirstOrDefault(o => o.name.Contains("Direction")); var cross = m_ViewController.AddVFXOperator(new Vector2(1, 1), crossDesc); var position = m_ViewController.AddVFXParameter(new Vector2(2, 2), positionDesc); var vector = m_ViewController.AddVFXParameter(new Vector2(3, 3), vectorDesc); var direction = m_ViewController.AddVFXParameter(new Vector2(4, 4), directionDesc); (cross as IVFXOperatorUniform).SetOperandType(typeof(Vector3)); m_ViewController.ApplyChanges(); Func<IVFXSlotContainer, VFXNodeController> fnFindController = delegate(IVFXSlotContainer slotContainer) { var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.FirstOrDefault(o => o.slotContainer == slotContainer); }; var controllerCross = fnFindController(cross); var vA = new Vector3(2, 3, 4); position.outputSlots[0].value = new Position() { position = vA }; vector.outputSlots[0].value = new Vector() { vector = vA }; var vB = new Vector3(5, 6, 7); direction.outputSlots[0].value = new DirectionType() { direction = vB }; var edgeControllerAppend_A = new VFXDataEdgeController(controllerCross.inputPorts.Where(o => o.portType == typeof(Vector3)).First(), fnFindController(usePosition ? position : vector).outputPorts.First()); m_ViewController.AddElement(edgeControllerAppend_A); (cross as IVFXOperatorUniform).SetOperandType(typeof(Vector3)); m_ViewController.ApplyChanges(); var edgeControllerAppend_B = new VFXDataEdgeController(controllerCross.inputPorts.Where(o => o.portType == typeof(Vector3)).Last(), fnFindController(direction).outputPorts.First()); m_ViewController.AddElement(edgeControllerAppend_B); (cross as IVFXOperatorUniform).SetOperandType(typeof(Vector3)); m_ViewController.ApplyChanges(); m_ViewController.ForceReload(); Assert.AreEqual(1, cross.inputSlots[0].LinkedSlots.Count()); Assert.AreEqual(1, cross.inputSlots[1].LinkedSlots.Count()); var context = new VFXExpression.Context(VFXExpressionContextOption.CPUEvaluation | VFXExpressionContextOption.ConstantFolding); var currentA = context.Compile(cross.inputSlots[0].GetExpression()).Get<Vector3>(); var currentB = context.Compile(cross.inputSlots[1].GetExpression()).Get<Vector3>(); var result = context.Compile(cross.outputSlots[0].GetExpression()).Get<Vector3>(); Assert.AreEqual((double)vA.x, (double)currentA.x, 0.001f); Assert.AreEqual((double)vA.y, (double)currentA.y, 0.001f); Assert.AreEqual((double)vA.z, (double)currentA.z, 0.001f); Assert.AreEqual((double)vB.normalized.x, (double)currentB.x, 0.001f); Assert.AreEqual((double)vB.normalized.y, (double)currentB.y, 0.001f); Assert.AreEqual((double)vB.normalized.z, (double)currentB.z, 0.001f); var expectedResult = Vector3.Cross(vA, vB.normalized); Assert.AreEqual((double)expectedResult.x, (double)result.x, 0.001f); Assert.AreEqual((double)expectedResult.y, (double)result.y, 0.001f); Assert.AreEqual((double)expectedResult.z, (double)result.z, 0.001f); } [Test] public void LinkToDirection() { var directionDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.model is VFXInlineOperator && (o.model as VFXInlineOperator).type == typeof(DirectionType)); var vector3Desc = VFXLibrary.GetOperators().FirstOrDefault(o => o.model is VFXInlineOperator && (o.model as VFXInlineOperator).type == typeof(Vector3)); var direction = m_ViewController.AddVFXOperator(new Vector2(1, 1), directionDesc); var vector3 = m_ViewController.AddVFXOperator(new Vector2(2, 2), vector3Desc); m_ViewController.ApplyChanges(); Func<IVFXSlotContainer, VFXNodeController> fnFindController = delegate(IVFXSlotContainer slotContainer) { var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.FirstOrDefault(o => o.slotContainer == slotContainer); }; var vA = new Vector3(8, 9, 6); vector3.inputSlots[0].value = vA; var controllerDirection = fnFindController(direction); var controllerVector3 = fnFindController(vector3); var edgeControllerAppend_A = new VFXDataEdgeController(controllerDirection.inputPorts.First(), controllerVector3.outputPorts.First()); m_ViewController.AddElement(edgeControllerAppend_A); m_ViewController.ApplyChanges(); m_ViewController.ForceReload(); Assert.AreEqual(1, direction.inputSlots[0].LinkedSlots.Count()); var context = new VFXExpression.Context(VFXExpressionContextOption.CPUEvaluation | VFXExpressionContextOption.ConstantFolding); var result = context.Compile(direction.outputSlots[0].GetExpression()).Get<Vector3>(); Assert.AreEqual((double)vA.normalized.x, (double)result.x, 0.001f); Assert.AreEqual((double)vA.normalized.y, (double)result.y, 0.001f); Assert.AreEqual((double)vA.normalized.z, (double)result.z, 0.001f); } [Test] public void UndoRedoCollapseSlot() { Undo.IncrementCurrentGroup(); var crossDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name.Contains("Cross")); var cross = m_ViewController.AddVFXOperator(new Vector2(0, 0), crossDesc); foreach (var slot in cross.inputSlots.Concat(cross.outputSlots)) { Undo.IncrementCurrentGroup(); Assert.IsTrue(slot.collapsed); slot.collapsed = false; } m_ViewController.ApplyChanges(); var totalSlotCount = cross.inputSlots.Concat(cross.outputSlots).Count(); for (int step = 1; step < totalSlotCount; step++) { Undo.PerformUndo(); var vfxOperatorController = m_ViewController.allChildren.OfType<VFXOperatorController>().FirstOrDefault(); Assert.IsNotNull(vfxOperatorController); var slots = vfxOperatorController.model.inputSlots.Concat(vfxOperatorController.model.outputSlots).Reverse(); for (int i = 0; i < totalSlotCount; ++i) { var slot = slots.ElementAt(i); Assert.AreEqual(i < step, slot.collapsed); } } for (int step = 1; step < totalSlotCount; step++) { Undo.PerformRedo(); var vfxOperatorController = m_ViewController.allChildren.OfType<VFXOperatorController>().FirstOrDefault(); Assert.IsNotNull(vfxOperatorController); var slots = vfxOperatorController.model.inputSlots.Concat(vfxOperatorController.model.outputSlots); for (int i = 0; i < totalSlotCount; ++i) { var slot = slots.ElementAt(i); Assert.AreEqual(i > step, slot.collapsed); } } } [Test] public void UndoRedoMoveOperator() { Undo.IncrementCurrentGroup(); var absDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Absolute"); var abs = m_ViewController.AddVFXOperator(new Vector2(0, 0), absDesc); var positions = new[] { new Vector2(1, 1), new Vector2(2, 2), new Vector2(3, 3), new Vector2(4, 4) }; foreach (var position in positions) { Undo.IncrementCurrentGroup(); abs.position = position; } Func<Type, VFXNodeController> fnFindController = delegate(Type type) { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.FirstOrDefault(o => type.IsInstanceOfType(o.slotContainer)); }; for (int i = 0; i < positions.Length; ++i) { var currentAbs = fnFindController(typeof(Operator.Absolute)); Assert.IsNotNull(currentAbs); Assert.AreEqual(positions[positions.Length - i - 1].x, currentAbs.model.position.x); Assert.AreEqual(positions[positions.Length - i - 1].y, currentAbs.model.position.y); Undo.PerformUndo(); } for (int i = 0; i < positions.Length; ++i) { Undo.PerformRedo(); var currentAbs = fnFindController(typeof(Operator.Absolute)); Assert.IsNotNull(currentAbs); Assert.AreEqual(positions[i].x, currentAbs.model.position.x); Assert.AreEqual(positions[i].y, currentAbs.model.position.y); } } [Test] public void UndoRedoAddOperator() { Func<VFXNodeController[]> fnAllOperatorController = delegate() { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.OfType<VFXOperatorController>().ToArray(); }; Action fnTestShouldExist = delegate() { var allOperatorController = fnAllOperatorController(); Assert.AreEqual(1, allOperatorController.Length); Assert.IsInstanceOf(typeof(Operator.Absolute), allOperatorController[0].model); }; Action fnTestShouldNotExist = delegate() { var allOperatorController = fnAllOperatorController(); Assert.AreEqual(0, allOperatorController.Length); }; Undo.IncrementCurrentGroup(); var absDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Absolute"); m_ViewController.AddVFXOperator(new Vector2(0, 0), absDesc); fnTestShouldExist(); Undo.PerformUndo(); fnTestShouldNotExist(); Undo.PerformRedo(); fnTestShouldExist(); Undo.IncrementCurrentGroup(); m_ViewController.RemoveElement(fnAllOperatorController()[0]); fnTestShouldNotExist(); Undo.PerformUndo(); fnTestShouldExist(); Undo.PerformRedo(); fnTestShouldNotExist(); } [Test] public void UndoRedoSetSlotValue() { Func<VFXNodeController[]> fnAllOperatorController = delegate() { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.OfType<VFXOperatorController>().ToArray(); }; var absDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Absolute"); m_ViewController.AddVFXOperator(new Vector2(0, 0), absDesc); var absOperator = fnAllOperatorController()[0]; Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 0; Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 123; Undo.PerformUndo(); Assert.AreEqual(0, absOperator.inputPorts[0].value); Undo.PerformRedo(); Assert.AreEqual(123, absOperator.inputPorts[0].value); } [Test] public void UndoRedoChangeSpace() { var inlineOperatorDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.modelType == typeof(VFXInlineOperator)); var inlineOperator = m_ViewController.AddVFXOperator(new Vector2(0, 0), inlineOperatorDesc); m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>().ToArray(); var inlineOperatorController = allController.OfType<VFXOperatorController>().FirstOrDefault(); inlineOperator.SetSettingValue("m_Type", (SerializableType)typeof(Position)); Assert.AreEqual(inlineOperator.inputSlots[0].space, VFXCoordinateSpace.Local); Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].space, VFXCoordinateSpace.Local); Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].GetSpaceTransformationType(), SpaceableType.Position); Undo.IncrementCurrentGroup(); inlineOperator.inputSlots[0].space = VFXCoordinateSpace.World; Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].space, VFXCoordinateSpace.World); Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].GetSpaceTransformationType(), SpaceableType.Position); Undo.PerformUndo(); //Should go back to local Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].space, VFXCoordinateSpace.Local); Assert.AreEqual((inlineOperatorController.model as VFXInlineOperator).inputSlots[0].GetSpaceTransformationType(), SpaceableType.Position); } [Test] public void UndoRedoSetSlotValueThenGraphChange() { Func<VFXNodeController[]> fnAllOperatorController = delegate() { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.OfType<VFXOperatorController>().ToArray(); }; var absDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Absolute"); m_ViewController.AddVFXOperator(new Vector2(0, 0), absDesc); var absOperator = fnAllOperatorController()[0]; Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 0; absOperator.position = new Vector2(1, 2); Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 123; Undo.IncrementCurrentGroup(); absOperator.position = new Vector2(123, 456); Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 789; Undo.PerformUndo(); // this should undo value change only Assert.AreEqual(123, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(123, 456), absOperator.position); Undo.PerformUndo(); // this should undo position change only Assert.AreEqual(123, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(1, 2), absOperator.position); Undo.PerformUndo(); // this should undo value change only Assert.AreEqual(0, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(1, 2), absOperator.position); Undo.PerformRedo(); // this should redo value change only Assert.AreEqual(123, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(1, 2), absOperator.position); Undo.PerformRedo(); // this should redo position change only Assert.AreEqual(123, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(123, 456), absOperator.position); Undo.PerformRedo(); // this should redo value change only Assert.AreEqual(789, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(123, 456), absOperator.position); } [Test] public void UndoRedoSetSlotValueAndGraphChange() { Func<VFXNodeController[]> fnAllOperatorController = delegate() { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.OfType<VFXOperatorController>().ToArray(); }; var absDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Absolute"); m_ViewController.AddVFXOperator(new Vector2(0, 0), absDesc); var absOperator = fnAllOperatorController()[0]; Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 0; absOperator.position = new Vector2(1, 2); Undo.IncrementCurrentGroup(); absOperator.inputPorts[0].value = 123; absOperator.position = new Vector2(123, 456); Undo.PerformUndo(); Assert.AreEqual(123, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(1, 2), absOperator.position); Undo.PerformRedo(); Assert.AreEqual(123, absOperator.inputPorts[0].value); Assert.AreEqual(new Vector2(123, 456), absOperator.position); } [Test] public void UndoRedoOperatorLinkSimple() { Func<Type, VFXNodeController> fnFindController = delegate(Type type) { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.FirstOrDefault(o => type.IsInstanceOfType(o.slotContainer)); }; var cosDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Cosine"); var sinDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Sine"); Undo.IncrementCurrentGroup(); m_ViewController.AddVFXOperator(new Vector2(0, 0), cosDesc); Undo.IncrementCurrentGroup(); m_ViewController.AddVFXOperator(new Vector2(1, 1), sinDesc); var cosController = fnFindController(typeof(Operator.Cosine)); var sinController = fnFindController(typeof(Operator.Sine)); Func<int> fnCountEdge = delegate() { return m_ViewController.allChildren.OfType<VFXDataEdgeController>().Count(); }; Undo.IncrementCurrentGroup(); Assert.AreEqual(0, fnCountEdge()); var edgeControllerSin = new VFXDataEdgeController(sinController.inputPorts[0], cosController.outputPorts[0]); m_ViewController.AddElement(edgeControllerSin); Assert.AreEqual(1, fnCountEdge()); Undo.PerformUndo(); m_ViewController.ApplyChanges(); Assert.AreEqual(0, fnCountEdge()); Assert.NotNull(fnFindController(typeof(Operator.Cosine))); Assert.NotNull(fnFindController(typeof(Operator.Sine))); } [Test] public void UndoRedoOperatorLinkToBlock() { Func<VFXContextController> fnFirstContextController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXContextController>().FirstOrDefault(); }; Func<Type, VFXNodeController> fnFindController = delegate(Type type) { m_ViewController.ApplyChanges(); var allController = m_ViewController.allChildren.OfType<VFXNodeController>(); return allController.FirstOrDefault(o => type.IsInstanceOfType(o.slotContainer)); }; Func<VFXBlockController> fnFirstBlockController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXContextController>().SelectMany(t => t.blockControllers).FirstOrDefault(); }; Func<VFXDataEdgeController> fnFirstEdgeController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXDataEdgeController>().FirstOrDefault(); }; Undo.IncrementCurrentGroup(); var cosDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Cosine"); var contextUpdateDesc = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Update")); var blockAttributeDesc = VFXLibrary.GetBlocks().FirstOrDefault(o => o.modelType == typeof(Block.SetAttribute)); m_ViewController.AddVFXOperator(new Vector2(0, 0), cosDesc); m_ViewController.AddVFXContext(new Vector2(2, 2), contextUpdateDesc); var blockAttribute = blockAttributeDesc.CreateInstance(); blockAttribute.SetSettingValue("attribute", "color"); blockAttribute.SetSettingValue("Source", Block.SetAttribute.ValueSource.Slot); fnFirstContextController().AddBlock(0, blockAttribute); var firstBlockController = fnFirstBlockController(); var cosController = fnFindController(typeof(Operator.Cosine)); var blockInputPorts = firstBlockController.inputPorts.ToArray(); var cosOutputPorts = cosController.outputPorts.ToArray(); var edgeController = new VFXDataEdgeController(blockInputPorts[0], cosOutputPorts[0]); m_ViewController.AddElement(edgeController); Undo.IncrementCurrentGroup(); m_ViewController.RemoveElement(fnFirstEdgeController()); Assert.IsNull(fnFirstEdgeController()); Undo.IncrementCurrentGroup(); Undo.PerformUndo(); Assert.IsNotNull(fnFirstEdgeController()); Undo.PerformRedo(); Assert.IsNull(fnFirstEdgeController()); } [Test] public void UndoRedoOperatorSettings() { Func<VFXOperatorController> fnFirstOperatorController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXOperatorController>().FirstOrDefault(); }; var swizzleDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name == "Swizzle"); m_ViewController.AddVFXOperator(new Vector2(0, 0), swizzleDesc); var maskList = new string[] { "xy", "yww", "xw", "z" }; for (int i = 0; i < maskList.Length; ++i) { var componentMaskController = fnFirstOperatorController(); Undo.IncrementCurrentGroup(); (componentMaskController.model as Operator.Swizzle).SetSettingValue("mask", maskList[i]); Assert.AreEqual(maskList[i], (componentMaskController.model as Operator.Swizzle).mask); } for (int i = maskList.Length - 1; i > 0; --i) { Undo.PerformUndo(); var componentMaskController = fnFirstOperatorController(); Assert.AreEqual(maskList[i - 1], (componentMaskController.model as Operator.Swizzle).mask); } for (int i = 0; i < maskList.Length - 1; ++i) { Undo.PerformRedo(); var componentMaskController = fnFirstOperatorController(); Assert.AreEqual(maskList[i + 1], (componentMaskController.model as Operator.Swizzle).mask); } } [Test] public void UndoRedoAddBlockContext() { var contextUpdateDesc = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Update")); var blockDesc = new VFXModelDescriptor<VFXBlock>(ScriptableObject.CreateInstance<AllType>()); m_ViewController.AddVFXContext(Vector2.one, contextUpdateDesc); Func<VFXContextController> fnContextController = delegate() { m_ViewController.ApplyChanges(); var allContextController = m_ViewController.allChildren.OfType<VFXContextController>().ToArray(); return allContextController.FirstOrDefault() as VFXContextController; }; Assert.IsNotNull(fnContextController()); //Creation Undo.IncrementCurrentGroup(); fnContextController().AddBlock(0, blockDesc.CreateInstance()); Assert.AreEqual(1, fnContextController().model.children.Count()); Undo.PerformUndo(); Assert.AreEqual(0, fnContextController().model.children.Count()); //Deletion var block = blockDesc.CreateInstance(); fnContextController().AddBlock(0, block); Assert.AreEqual(1, fnContextController().model.children.Count()); Undo.IncrementCurrentGroup(); fnContextController().RemoveBlock(block); Assert.AreEqual(0, fnContextController().model.children.Count()); Undo.PerformUndo(); m_ViewController.ApplyChanges(); Assert.IsNotNull(fnContextController()); Assert.AreEqual(1, fnContextController().model.children.Count()); Assert.IsInstanceOf(typeof(AllType), fnContextController().model.children.First()); } [Test] public void UndoRedoContext() { Func<VFXContextController> fnFirstContextController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXContextController>().FirstOrDefault() as VFXContextController; }; var contextDesc = VFXLibrary.GetContexts().FirstOrDefault(); Undo.IncrementCurrentGroup(); m_ViewController.AddVFXContext(Vector2.zero, contextDesc); Assert.NotNull(fnFirstContextController()); Undo.PerformUndo(); Assert.Null(fnFirstContextController(), "Fail Undo Create"); Undo.IncrementCurrentGroup(); m_ViewController.AddVFXContext(Vector2.zero, contextDesc); Assert.NotNull(fnFirstContextController()); Undo.IncrementCurrentGroup(); m_ViewController.RemoveElement(fnFirstContextController()); Assert.Null(fnFirstContextController()); Undo.PerformUndo(); Assert.NotNull(fnFirstContextController(), "Fail Undo Delete"); } [Test] public void UndoRedoContextLinkMultiSlot() { Func<VFXContextController[]> fnContextController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXContextController>().Cast<VFXContextController>().ToArray(); }; Func<VFXContextController> fnSpawner = delegate() { var controller = fnContextController(); return controller.FirstOrDefault(o => o.model.name.Contains("Spawn")); }; Func<string, VFXContextController> fnEvent = delegate(string name) { var controller = fnContextController(); var allEvent = controller.Where(o => o.model.name.Contains("Event")); return allEvent.FirstOrDefault(o => (o.model as VFXBasicEvent).eventName == name) as VFXContextController; }; Func<VFXContextController> fnStart = delegate() { return fnEvent("Start"); }; Func<VFXContextController> fnStop = delegate() { return fnEvent("Stop"); }; Func<int> fnFlowEdgeCount = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXFlowEdgeController>().Count(); }; var contextSpawner = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Spawn")); var contextEvent = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Event")); m_ViewController.AddVFXContext(new Vector2(1, 1), contextSpawner); var eventStartController = m_ViewController.AddVFXContext(new Vector2(2, 2), contextEvent) as VFXBasicEvent; var eventStopController = m_ViewController.AddVFXContext(new Vector2(3, 3), contextEvent) as VFXBasicEvent; eventStartController.SetSettingValue("eventName", "Start"); eventStopController.SetSettingValue("eventName", "Stop"); //Creation var flowEdge = new VFXFlowEdgeController(fnSpawner().flowInputAnchors.ElementAt(0), fnStart().flowOutputAnchors.FirstOrDefault()); Undo.IncrementCurrentGroup(); m_ViewController.AddElement(flowEdge); Assert.AreEqual(1, fnFlowEdgeCount()); flowEdge = new VFXFlowEdgeController(fnSpawner().flowInputAnchors.ElementAt(1), fnStop().flowOutputAnchors.FirstOrDefault()); Undo.IncrementCurrentGroup(); m_ViewController.AddElement(flowEdge); Assert.AreEqual(2, fnFlowEdgeCount()); //Test a single deletion var allFlowEdge = m_ViewController.allChildren.OfType<VFXFlowEdgeController>().ToArray(); // Integrity test... var inputSlotIndex = allFlowEdge.Select(o => (o.input as VFXFlowAnchorController).slotIndex).OrderBy(o => o).ToArray(); var outputSlotIndex = allFlowEdge.Select(o => (o.output as VFXFlowAnchorController).slotIndex).OrderBy(o => o).ToArray(); Assert.AreEqual(inputSlotIndex[0], 0); Assert.AreEqual(inputSlotIndex[1], 1); Assert.AreEqual(outputSlotIndex[0], 0); Assert.AreEqual(outputSlotIndex[1], 0); var edge = allFlowEdge.First(o => o.input == fnSpawner().flowInputAnchors.ElementAt(1) && o.output == fnStop().flowOutputAnchors.FirstOrDefault()); Undo.IncrementCurrentGroup(); m_ViewController.RemoveElement(edge); Assert.AreEqual(1, fnFlowEdgeCount()); Undo.PerformUndo(); Assert.AreEqual(2, fnFlowEdgeCount()); Undo.PerformRedo(); Assert.AreEqual(1, fnFlowEdgeCount()); Undo.PerformUndo(); Assert.AreEqual(2, fnFlowEdgeCount()); //Global Deletion Undo.PerformUndo(); Assert.AreEqual(1, fnFlowEdgeCount()); Undo.PerformUndo(); Assert.AreEqual(0, fnFlowEdgeCount()); } [Test] public void UndoRedoContextLink() { Func<VFXContextController[]> fnContextController = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXContextController>().Cast<VFXContextController>().ToArray(); }; Func<VFXContextController> fnInitializeController = delegate() { var controller = fnContextController(); return controller.FirstOrDefault(o => o.model.name.Contains("Init")); }; Func<VFXContextController> fnUpdateController = delegate() { var controller = fnContextController(); return controller.FirstOrDefault(o => o.model.name.Contains("Update")); }; Func<int> fnFlowEdgeCount = delegate() { m_ViewController.ApplyChanges(); return m_ViewController.allChildren.OfType<VFXFlowEdgeController>().Count(); }; var contextInitializeDesc = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Init")); var contextUpdateDesc = VFXLibrary.GetContexts().FirstOrDefault(o => o.name.Contains("Update")); m_ViewController.AddVFXContext(new Vector2(1, 1), contextInitializeDesc); m_ViewController.AddVFXContext(new Vector2(2, 2), contextUpdateDesc); //Creation var flowEdge = new VFXFlowEdgeController(fnUpdateController().flowInputAnchors.FirstOrDefault(), fnInitializeController().flowOutputAnchors.FirstOrDefault()); Undo.IncrementCurrentGroup(); m_ViewController.AddElement(flowEdge); Assert.AreEqual(1, fnFlowEdgeCount()); Undo.PerformUndo(); Assert.AreEqual(0, fnFlowEdgeCount(), "Fail undo Create"); //Deletion flowEdge = new VFXFlowEdgeController(fnUpdateController().flowInputAnchors.FirstOrDefault(), fnInitializeController().flowOutputAnchors.FirstOrDefault()); m_ViewController.AddElement(flowEdge); Assert.AreEqual(1, fnFlowEdgeCount()); Undo.IncrementCurrentGroup(); m_ViewController.RemoveElement(m_ViewController.allChildren.OfType<VFXFlowEdgeController>().FirstOrDefault()); Assert.AreEqual(0, fnFlowEdgeCount()); Undo.PerformUndo(); Assert.AreEqual(1, fnFlowEdgeCount(), "Fail undo Delete"); } [Test] public void DeleteSubSlotWithLink() { var crossProductDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name.Contains("Cross")); var sinDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name.Contains("Sin")); var cosDesc = VFXLibrary.GetOperators().FirstOrDefault(o => o.name.Contains("Cos")); var crossProduct = m_ViewController.AddVFXOperator(new Vector2(0, 0), crossProductDesc); var sin = m_ViewController.AddVFXOperator(new Vector2(8, 8), sinDesc); var cos = m_ViewController.AddVFXOperator(new Vector2(-8, 8), cosDesc); m_ViewController.ApplyChanges(); crossProduct.outputSlots[0].children.ElementAt(1).Link(sin.inputSlots[0]); crossProduct.outputSlots[0].children.ElementAt(1).Link(cos.inputSlots[0]); var crossController = m_ViewController.allChildren.OfType<VFXOperatorController>().First(o => o.model.name.Contains("Cross")); m_ViewController.RemoveElement(crossController); Assert.IsFalse(cos.inputSlots[0].HasLink(true)); Assert.IsFalse(sin.inputSlots[0].HasLink(true)); } [Test] public void ConvertParameterToInline() { VFXParameter newParameter = m_ViewController.AddVFXParameter(Vector2.zero, VFXLibrary.GetParameters().First(t => t.model.type == typeof(AABox))); m_ViewController.LightApplyChanges(); VFXParameterController parameterController = m_ViewController.GetParameterController(newParameter); parameterController.model.AddNode(new Vector2(123, 456)); AABox value = new AABox { center = new Vector3(1, 2, 3), size = new Vector3(4, 5, 6) }; parameterController.value = value; m_ViewController.LightApplyChanges(); VFXParameterNodeController parameterNode = parameterController.nodes.First(); parameterNode.ConvertToInline(); VFXInlineOperator op = m_ViewController.graph.children.OfType<VFXInlineOperator>().First(); Assert.AreEqual(new Vector2(123, 456), op.position); Assert.AreEqual(typeof(AABox), op.type); Assert.AreEqual(value, op.inputSlots[0].value); } [Test] public void ConvertInlineToParameter() { var op = ScriptableObject.CreateInstance<VFXInlineOperator>(); m_ViewController.graph.AddChild(op); op.SetSettingValue("m_Type", (SerializableType)typeof(AABox)); op.position = new Vector2(123, 456); AABox value = new AABox { center = new Vector3(1, 2, 3), size = new Vector3(4, 5, 6) }; op.inputSlots[0].value = value; m_ViewController.LightApplyChanges(); var nodeController = m_ViewController.GetNodeController(op, 0) as VFXOperatorController; nodeController.ConvertToParameter(); VFXParameter param = m_ViewController.graph.children.OfType<VFXParameter>().First(); Assert.AreEqual(new Vector2(123, 456), param.nodes[0].position); Assert.AreEqual(typeof(AABox), param.type); Assert.AreEqual(value, param.value); } } } #endif
using PcapDotNet.Packets.IpV4; namespace PcapDotNet.Packets.IpV6 { /// <summary> /// RFCs 3963, 4140, 5213, 5380, 5555, 5845, 6275, 6602. /// <pre> /// +-----+---+---+---+---+---+---+---+---+---+---+-----------------+ /// | Bit | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10-15 | /// +-----+---+---+---+---+---+---+---+---+---+---+-----------------+ /// | 0 | Next Header | Header Extension Length | /// +-----+-------------------------------+-------------------------+ /// | 16 | MH Type | Reserved | /// +-----+-------------------------------+-------------------------+ /// | 32 | Checksum | /// +-----+---------------------------------------------------------+ /// | 48 | Sequence # | /// +-----+---+---+---+---+---+---+---+---+---+---+-----------------+ /// | 64 | A | H | L | K | M | R | P | F | T | B | Reserved | /// +-----+---+---+---+---+---+---+---+---+---+---+-----------------+ /// | 80 | Lifetime | /// +-----+---------------------------------------------------------+ /// | 96 | Mobility Options | /// | ... | | /// +-----+---------------------------------------------------------+ /// </pre> /// </summary> public sealed class IpV6ExtensionHeaderMobilityBindingUpdate : IpV6ExtensionHeaderMobilityBindingUpdateBase { private static class MessageDataOffset { public const int MapRegistration = sizeof(ushort); public const int MobileRouter = MapRegistration; public const int ProxyRegistration = MobileRouter; public const int ForcingUdpEncapsulation = ProxyRegistration; public const int TlvHeaderFormat = ForcingUdpEncapsulation + sizeof(byte); public const int BulkBindingUpdate = TlvHeaderFormat; } private static class MessageDataMask { public const byte MapRegistration = 0x08; public const byte MobileRouter = 0x04; public const byte ProxyRegistration = 0x02; public const byte ForcingUdpEncapsulation = 0x01; public const byte TlvHeaderFormat = 0x80; public const byte BulkBindingUpdate = 0x40; } /// <summary> /// Creates an instance from next header, checksum, sequence number, acknowledge, home registration, link local address compatibility, /// key management mobiltiy capability, map registration, mobile router, proxy registration flag, forcing UDP encapsulation, TLV header format, /// bulk binding update, lifetime and options. /// </summary> /// <param name="nextHeader">Identifies the type of header immediately following this extension header.</param> /// <param name="checksum"> /// Contains the checksum of the Mobility Header. /// The checksum is calculated from the octet string consisting of a "pseudo-header" /// followed by the entire Mobility Header starting with the Payload Proto field. /// The checksum is the 16-bit one's complement of the one's complement sum of this string. /// </param> /// <param name="sequenceNumber"> /// Used by the receiving node to sequence Binding Updates and by the sending node to match a returned Binding Acknowledgement with this Binding Update. /// </param> /// <param name="acknowledge"> /// Set by the sending mobile node to request a Binding Acknowledgement be returned upon receipt of the Binding Update. /// For Fast Binding Update this must be set to one to request that PAR send a Fast Binding Acknowledgement message. /// </param> /// <param name="homeRegistration"> /// Set by the sending mobile node to request that the receiving node should act as this node's home agent. /// The destination of the packet carrying this message must be that of a router sharing the same subnet prefix as the home address /// of the mobile node in the binding. /// For Fast Binding Update this must be set to one. /// </param> /// <param name="linkLocalAddressCompatibility"> /// Set when the home address reported by the mobile node has the same interface identifier as the mobile node's link-local address. /// </param> /// <param name="keyManagementMobilityCapability"> /// If this is cleared, the protocol used for establishing the IPsec security associations between the mobile node and the home agent /// does not survive movements. /// It may then have to be rerun. (Note that the IPsec security associations themselves are expected to survive movements.) /// If manual IPsec configuration is used, the bit must be cleared. /// </param> /// <param name="mapRegistration"> /// Indicates MAP registration. /// When a mobile node registers with the MAP, the MapRegistration and Acknowledge must be set to distinguish this registration /// from a Binding Update being sent to the Home Agent or a correspondent node. /// </param> /// <param name="mobileRouter"> /// Indicates to the Home Agent that the Binding Update is from a Mobile Router. /// If false, the Home Agent assumes that the Mobile Router is behaving as a Mobile Node, /// and it must not forward packets destined for the Mobile Network to the Mobile Router. /// </param> /// <param name="proxyRegistration"> /// Indicates to the local mobility anchor that the Binding Update message is a proxy registration. /// Must be true for proxy registrations and must be false direct registrations sent by a mobile node. /// </param> /// <param name="forcingUdpEncapsulation"> /// Indicates a request for forcing UDP encapsulation regardless of whether a NAT is present on the path between the mobile node and the home agent. /// May be set by the mobile node if it is required to use UDP encapsulation regardless of the presence of a NAT. /// </param> /// <param name="typeLengthValueHeaderFormat"> /// Indicates that the mobile access gateway requests the use of the TLV header for encapsulating IPv6 or IPv4 packets in IPv4. /// </param> /// <param name="bulkBindingUpdate"> /// If true, it informs the local mobility anchor to enable bulk binding update support for the mobility session associated with this message. /// If false, the local mobility anchor must exclude the mobility session associated with this message from any bulk-binding-related operations /// and any binding update, or binding revocation operations with bulk-specific scope will not be relevant to that mobility session. /// This flag is relevant only for Proxy Mobile IPv6 and therefore must be set to false when the ProxyRegistration is false. /// </param> /// <param name="lifetime"> /// The number of time units remaining before the binding must be considered expired. /// A value of zero indicates that the Binding Cache entry for the mobile node must be deleted. /// One time unit is 4 seconds for Binding Update and 1 second for Fast Binding Update. /// </param> /// <param name="options">Zero or more TLV-encoded mobility options.</param> public IpV6ExtensionHeaderMobilityBindingUpdate(IpV4Protocol? nextHeader, ushort checksum, ushort sequenceNumber, bool acknowledge, bool homeRegistration, bool linkLocalAddressCompatibility, bool keyManagementMobilityCapability, bool mapRegistration, bool mobileRouter, bool proxyRegistration, bool forcingUdpEncapsulation, bool typeLengthValueHeaderFormat, bool bulkBindingUpdate, ushort lifetime, IpV6MobilityOptions options) : base(nextHeader, checksum, sequenceNumber, acknowledge, homeRegistration, linkLocalAddressCompatibility, keyManagementMobilityCapability, lifetime, options) { MapRegistration = mapRegistration; MobileRouter = mobileRouter; ProxyRegistration = proxyRegistration; ForcingUdpEncapsulation = forcingUdpEncapsulation; TypeLengthValueHeaderFormat = typeLengthValueHeaderFormat; BulkBindingUpdate = bulkBindingUpdate; } /// <summary> /// Identifies the particular mobility message in question. /// An unrecognized MH Type field causes an error indication to be sent. /// </summary> public override IpV6MobilityHeaderType MobilityHeaderType { get { return IpV6MobilityHeaderType.BindingUpdate; } } /// <summary> /// Indicates MAP registration. /// When a mobile node registers with the MAP, the MapRegistration and Acknowledge must be set to distinguish this registration /// from a Binding Update being sent to the Home Agent or a correspondent node. /// </summary> public bool MapRegistration { get; private set; } /// <summary> /// Indicates to the Home Agent that the Binding Update is from a Mobile Router. /// If false, the Home Agent assumes that the Mobile Router is behaving as a Mobile Node, /// and it must not forward packets destined for the Mobile Network to the Mobile Router. /// </summary> public bool MobileRouter { get; private set; } /// <summary> /// Indicates to the local mobility anchor that the Binding Update message is a proxy registration. /// Must be true for proxy registrations and must be false direct registrations sent by a mobile node. /// </summary> public bool ProxyRegistration { get; private set; } /// <summary> /// Indicates a request for forcing UDP encapsulation regardless of whether a NAT is present on the path between the mobile node and the home agent. /// May be set by the mobile node if it is required to use UDP encapsulation regardless of the presence of a NAT. /// </summary> public bool ForcingUdpEncapsulation { get; private set; } /// <summary> /// Indicates that the mobile access gateway requests the use of the TLV header for encapsulating IPv6 or IPv4 packets in IPv4. /// </summary> public bool TypeLengthValueHeaderFormat { get; private set; } /// <summary> /// If true, it informs the local mobility anchor to enable bulk binding update support for the mobility session associated with this message. /// If false, the local mobility anchor must exclude the mobility session associated with this message from any bulk-binding-related operations /// and any binding update, or binding revocation operations with bulk-specific scope will not be relevant to that mobility session. /// This flag is relevant only for Proxy Mobile IPv6 and therefore must be set to false when the ProxyRegistration is false. /// </summary> public bool BulkBindingUpdate { get; private set; } internal static IpV6ExtensionHeaderMobilityBindingUpdate ParseMessageData(IpV4Protocol nextHeader, ushort checksum, DataSegment messageData) { ushort sequenceNumber; bool acknowledge; bool homeRegistration; bool linkLocalAddressCompatibility; bool keyManagementMobilityCapability; ushort lifetime; IpV6MobilityOptions options; if (!ParseMessageDataToFields(messageData, out sequenceNumber, out acknowledge, out homeRegistration, out linkLocalAddressCompatibility, out keyManagementMobilityCapability, out lifetime, out options)) { return null; } bool mapRegistration = messageData.ReadBool(MessageDataOffset.MapRegistration, MessageDataMask.MapRegistration); bool mobileRouter = messageData.ReadBool(MessageDataOffset.MobileRouter, MessageDataMask.MobileRouter); bool proxyRegistration = messageData.ReadBool(MessageDataOffset.ProxyRegistration, MessageDataMask.ProxyRegistration); bool forcingUdpEncapsulation = messageData.ReadBool(MessageDataOffset.ForcingUdpEncapsulation, MessageDataMask.ForcingUdpEncapsulation); bool tlvHeaderFormat = messageData.ReadBool(MessageDataOffset.TlvHeaderFormat, MessageDataMask.TlvHeaderFormat); bool bulkBindingUpdate = messageData.ReadBool(MessageDataOffset.BulkBindingUpdate, MessageDataMask.BulkBindingUpdate); return new IpV6ExtensionHeaderMobilityBindingUpdate(nextHeader, checksum, sequenceNumber, acknowledge, homeRegistration, linkLocalAddressCompatibility, keyManagementMobilityCapability, mapRegistration, mobileRouter, proxyRegistration, forcingUdpEncapsulation, tlvHeaderFormat, bulkBindingUpdate, lifetime, options); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Multiverse.ToolBox; namespace Multiverse.Tools.WorldEditor { public partial class AddMobDialog : Form, IDisposable { private bool showRadius; public AddMobDialog(string title, bool enableRadius) { InitializeComponent(); this.showRadius = enableRadius; if (enableRadius) { spawnRadiusLabel.Visible = true; spawnRadiusTextbox.Visible = true; } else { spawnRadiusLabel.Visible = false; spawnRadiusTextbox.Visible = false; } } public string TemplateNameTextBoxText { get { return templateNameTextbox.Text; } set { templateNameTextbox.Text = value; } } public string RespawnTimeTextboxText { get { return respawnTimeTextbox.Text; } set { respawnTimeTextbox.Text = value; } } public string NumberOfSpawnsTextboxText { get { return numberOfSpawnsTextbox.Text; } set { numberOfSpawnsTextbox.Text = value; } } public string SpawnRadiusTextboxText { get { if (showRadius) { return spawnRadiusTextbox.Text; } else { return ""; } } set { if (showRadius) { spawnRadiusTextbox.Text = value; } else { spawnRadiusTextbox.Text = ""; } } } public float SpawnRadius { get { if (showRadius) { return float.Parse(spawnRadiusTextbox.Text); } return 0; } set { if (showRadius) { spawnRadiusTextbox.Text = value.ToString(); } else { spawnRadiusTextbox.Text = "0"; } } } public int RespawnTime { get { return int.Parse(respawnTimeTextbox.Text); } set { respawnTimeTextbox.Text = value.ToString(); } } public uint NumberOfSpawns { get { return uint.Parse(numberOfSpawnsTextbox.Text); } set { numberOfSpawnsTextbox.Text = value.ToString(); } } private void floatVerifyevent(object sender, CancelEventArgs e) { TextBox textbox = (TextBox)sender; if (!ValidityHelperClass.isFloat(textbox.Text)) { Color textColor = Color.Red; textbox.ForeColor = textColor; } else { Color textColor = Color.Black; textbox.ForeColor = textColor; } } private void intVerifyevent(object sender, CancelEventArgs e) { TextBox textbox = (TextBox)sender; if (!ValidityHelperClass.isInt(textbox.Text)) { Color textColor = Color.Red; textbox.ForeColor = textColor; } else { Color textColor = Color.Black; textbox.ForeColor = textColor; } } private void uintVerifyevent(object sender, CancelEventArgs e) { TextBox textbox = (TextBox)sender; if (!ValidityHelperClass.isUint(textbox.Text)) { Color textColor = Color.Red; textbox.ForeColor = textColor; } else { Color textColor = Color.Black; textbox.ForeColor = textColor; } } public bool okButton_validating() { if (!ValidityHelperClass.isInt(respawnTimeTextbox.Text)) { MessageBox.Show("Respawn time can not be parsed to a integer number", "Incorrect respawn time", MessageBoxButtons.OK); return false; } else { if (!ValidityHelperClass.isUint(numberOfSpawnsTextbox.Text)) { MessageBox.Show("Number of spanws can not be parsed to a unsigned integer number", "Incorrect number of spawns", MessageBoxButtons.OK); return false; } else { if ((!ValidityHelperClass.isInt(spawnRadiusTextbox.Text)) && (showRadius)) { MessageBox.Show("Spawn radius can not be parsed to a integer number", "Incorrect spawn radius", MessageBoxButtons.OK); return false; } } } return true; } private void helpButton_clicked(object sender, EventArgs e) { Button but = sender as Button; WorldEditor.LaunchDoc(but.Tag as string); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System.Collections.Generic; namespace NPOI.HPSF { using System; using System.IO; using NPOI.HPSF.Wellknown; using NPOI.POIFS.FileSystem; using NPOI.Util; /// <summary> /// Abstract superclass for the convenience classes {@link /// SummaryInformation} and {@link DocumentSummaryInformation}. /// The motivation behind this class is quite nasty if you look /// behind the scenes, but it serves the application programmer well by /// providing him with the easy-to-use {@link SummaryInformation} and /// {@link DocumentSummaryInformation} classes. When parsing the data a /// property Set stream consists of (possibly coming from an {@link /// java.io.Stream}) we want To Read and process each byte only /// once. Since we don't know in advance which kind of property Set we /// have, we can expect only the most general {@link /// PropertySet}. Creating a special subclass should be as easy as /// calling the special subclass' constructor and pass the general /// {@link PropertySet} in. To make things easy internally, the special /// class just holds a reference To the general {@link PropertySet} and /// delegates all method calls To it. /// A cleaner implementation would have been like this: The {@link /// PropertySetFactory} parses the stream data into some internal /// object first. Then it Finds out whether the stream is a {@link /// SummaryInformation}, a {@link DocumentSummaryInformation} or a /// general {@link PropertySet}. However, the current implementation /// went the other way round historically: the convenience classes came /// only late To my mind. /// @author Rainer Klute /// klute@rainer-klute.de /// @since 2002-02-09 /// </summary> [Serializable] public abstract class SpecialPropertySet : MutablePropertySet { /** * The id to name mapping of the properties * in this set. */ public abstract PropertyIDMap PropertySetIDMap{get;} /** * The "real" property Set <c>SpecialPropertySet</c> * delegates To. */ private MutablePropertySet delegate1; /// <summary> /// Initializes a new instance of the <see cref="SpecialPropertySet"/> class. /// </summary> /// <param name="ps">The property Set To be encapsulated by the <c>SpecialPropertySet</c></param> public SpecialPropertySet(PropertySet ps) { delegate1 = new MutablePropertySet(ps); } /// <summary> /// Initializes a new instance of the <see cref="SpecialPropertySet"/> class. /// </summary> /// <param name="ps">The mutable property Set To be encapsulated by the <c>SpecialPropertySet</c></param> public SpecialPropertySet(MutablePropertySet ps) { delegate1 = ps; } /// <summary> /// gets or sets the "byteOrder" property. /// </summary> /// <value>the byteOrder value To Set</value> public override int ByteOrder { get { return delegate1.ByteOrder; } set { delegate1.ByteOrder = value; } } /// <summary> /// gets or sets the "format" property /// </summary> /// <value>the format value To Set</value> public override int Format { get { return delegate1.Format; } set { delegate1.Format = value; } } /// <summary> /// gets or sets the property Set stream's low-level "class ID" /// field. /// </summary> /// <value>The property Set stream's low-level "class ID" field</value> public override ClassID ClassID { get { return delegate1.ClassID; } set { delegate1.ClassID = value; } } /// <summary> /// Returns the number of {@link Section}s in the property /// Set. /// </summary> /// <value>The number of {@link Section}s in the property Set.</value> public override int SectionCount { get { return delegate1.SectionCount; } } public override List<Section> Sections { get { return delegate1.Sections; } } /// <summary> /// Checks whether this {@link PropertySet} represents a Summary /// Information. /// </summary> /// <value> /// <c>true</c> Checks whether this {@link PropertySet} represents a Summary /// Information; otherwise, <c>false</c>. /// </value> public override bool IsSummaryInformation { get{return delegate1.IsSummaryInformation;} } public override Stream ToStream() { return delegate1.ToStream(); } /// <summary> /// Gets a value indicating whether this instance is document summary information. /// </summary> /// <value> /// <c>true</c> if this instance is document summary information; otherwise, <c>false</c>. /// </value> /// Checks whether this {@link PropertySet} is a Document /// Summary Information. /// @return /// <c>true</c> /// if this {@link PropertySet} /// represents a Document Summary Information, else /// <c>false</c> public override bool IsDocumentSummaryInformation { get{return delegate1.IsDocumentSummaryInformation;} } /// <summary> /// Gets the PropertySet's first section. /// </summary> /// <value>The {@link PropertySet}'s first section.</value> public override Section FirstSection { get { return delegate1.FirstSection; } } /// <summary> /// Adds a section To this property set. /// </summary> /// <param name="section">The {@link Section} To Add. It will be Appended /// after any sections that are alReady present in the property Set /// and thus become the last section.</param> public override void AddSection(Section section) { delegate1.AddSection(section); } /// <summary> /// Removes all sections from this property Set. /// </summary> public override void ClearSections() { delegate1.ClearSections(); } /// <summary> /// gets or sets the "osVersion" property /// </summary> /// <value> the osVersion value To Set</value> public override int OSVersion { set { delegate1.OSVersion=value; } get { return delegate1.OSVersion; } } /// <summary> /// Returns the contents of this property Set stream as an input stream. /// The latter can be used for example To Write the property Set into a POIFS /// document. The input stream represents a snapshot of the property Set. /// If the latter is modified while the input stream is still being /// Read, the modifications will not be reflected in the input stream but in /// the {@link MutablePropertySet} only. /// </summary> /// <returns>the contents of this PropertySet stream</returns> public override Stream GetStream() { return delegate1.GetStream(); } /// <summary> /// Writes a property Set To a document in a POI filesystem directory. /// </summary> /// <param name="dir">The directory in the POI filesystem To Write the document To</param> /// <param name="name">The document's name. If there is alReady a document with the /// same name in the directory the latter will be overwritten.</param> public override void Write(DirectoryEntry dir, String name) { delegate1.Write(dir, name); } /// <summary> /// Writes the property Set To an output stream. /// </summary> /// <param name="out1">the output stream To Write the section To</param> public override void Write(Stream out1) { delegate1.Write(out1); } /// <summary> /// Returns <c>true</c> if the <c>PropertySet</c> is equal /// To the specified parameter, else <c>false</c>. /// </summary> /// <param name="o">the object To Compare this /// <c>PropertySet</c> /// with</param> /// <returns> /// <c>true</c> /// if the objects are equal, /// <c>false</c> /// if not /// </returns> public override bool Equals(Object o) { return delegate1.Equals(o); } /// <summary> /// Convenience method returning the {@link Property} array /// contained in this property Set. It is a shortcut for Getting /// the {@link PropertySet}'s {@link Section}s list and then /// Getting the {@link Property} array from the first {@link /// Section}. /// </summary> /// <value> /// The properties of the only {@link Section} of this /// {@link PropertySet}. /// </value> public override Property[] Properties { get { return delegate1.Properties; } } /// <summary> /// Convenience method returning the value of the property with /// the specified ID. If the property is not available, /// <c>null</c> is returned and a subsequent call To {@link /// #WasNull} will return <c>true</c> . /// </summary> /// <param name="id">The property ID</param> /// <returns>The property value</returns> public override Object GetProperty(int id) { return delegate1.GetProperty(id); } /// <summary> /// Convenience method returning the value of a bool property /// with the specified ID. If the property is not available, /// <c>false</c> is returned. A subsequent call To {@link /// #WasNull} will return <c>true</c> To let the caller /// distinguish that case from a real property value of /// <c>false</c>. /// </summary> /// <param name="id">The property ID</param> /// <returns>The property value</returns> public override bool GetPropertyBooleanValue(int id) { return delegate1.GetPropertyBooleanValue(id); } /// <summary> /// Convenience method returning the value of the numeric /// property with the specified ID. If the property is not /// available, 0 is returned. A subsequent call To {@link #WasNull} /// will return <c>true</c> To let the caller distinguish /// that case from a real property value of 0. /// </summary> /// <param name="id">The property ID</param> /// <returns>The propertyIntValue value</returns> public override int GetPropertyIntValue(int id) { return delegate1.GetPropertyIntValue(id); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return delegate1.GetHashCode(); } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { return delegate1.ToString(); } /// <summary> /// Checks whether the property which the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access /// Was available or not. This information might be important for /// callers of {@link #GetPropertyIntValue} since the latter /// returns 0 if the property does not exist. Using {@link /// #WasNull}, the caller can distiguish this case from a /// property's real value of 0. /// </summary> /// <value> /// <c>true</c> if the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access a /// property that Was not available; otherwise, <c>false</c>. /// </value> public override bool WasNull { get { return delegate1.WasNull; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; namespace DD.CloudControl.Powershell.Utilities { /// <summary> /// A synchronisation context that runs all calls scheduled on it (via <see cref="SynchronizationContext.Post"/>) on a single thread. /// </summary> /// <remarks> /// With thanks to Stephen Toub. /// </remarks> public sealed class ThreadAffinitiveSynchronizationContext : SynchronizationContext, IDisposable { /// <summary> /// A blocking collection (effectively a queue) of work items to execute, consisting of callback delegates and their callback state (if any). /// </summary> BlockingCollection<KeyValuePair<SendOrPostCallback, object>> _workItemQueue = new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>(); /// <summary> /// Create a new thread-affinitive synchronisation context. /// </summary> ThreadAffinitiveSynchronizationContext() { } /// <summary> /// Dispose of resources being used by the synchronisation context. /// </summary> void IDisposable.Dispose() { if (_workItemQueue != null) { _workItemQueue.Dispose(); _workItemQueue = null; } } /// <summary> /// Check if the synchronisation context has been disposed. /// </summary> void CheckDisposed() { if (_workItemQueue == null) throw new ObjectDisposedException(GetType().Name); } /// <summary> /// Run the message pump for the callback queue on the current thread. /// </summary> void RunMessagePump() { CheckDisposed(); KeyValuePair<SendOrPostCallback, object> workItem; while (_workItemQueue.TryTake(out workItem, Timeout.InfiniteTimeSpan)) { workItem.Key(workItem.Value); // Has the synchronisation context been disposed? if (_workItemQueue == null) break; } } /// <summary> /// Terminate the message pump once all callbacks have completed. /// </summary> void TerminateMessagePump() { CheckDisposed(); _workItemQueue.CompleteAdding(); } /// <summary> /// Dispatch an asynchronous message to the synchronization context. /// </summary> /// <param name="callback"> /// The <see cref="SendOrPostCallback"/> delegate to call in the synchronisation context. /// </param> /// <param name="callbackState"> /// Optional state data passed to the callback. /// </param> /// <exception cref="InvalidOperationException"> /// The message pump has already been started, and then terminated by calling <see cref="TerminateMessagePump"/>. /// </exception> public override void Post(SendOrPostCallback callback, object callbackState) { if (callback == null) throw new ArgumentNullException(nameof(callback)); CheckDisposed(); try { _workItemQueue.Add( new KeyValuePair<SendOrPostCallback, object>( key: callback, value: callbackState ) ); } catch (InvalidOperationException eMessagePumpAlreadyTerminated) { throw new InvalidOperationException( "Cannot enqueue the specified callback because the synchronisation context's message pump has already been terminated.", eMessagePumpAlreadyTerminated ); } } /// <summary> /// Run an asynchronous operation using the current thread as its synchronisation context. /// </summary> /// <param name="asyncOperation"> /// A <see cref="Func{TResult}"/> delegate representing the asynchronous operation to run. /// </param> public static void RunSynchronized(Func<Task> asyncOperation) { if (asyncOperation == null) throw new ArgumentNullException(nameof(asyncOperation)); SynchronizationContext savedContext = Current; try { using (ThreadAffinitiveSynchronizationContext synchronizationContext = new ThreadAffinitiveSynchronizationContext()) { SetSynchronizationContext(synchronizationContext); Task rootOperationTask = asyncOperation(); if (rootOperationTask == null) throw new InvalidOperationException("The asynchronous operation delegate cannot return null."); rootOperationTask.ContinueWith( operationTask => synchronizationContext.TerminateMessagePump(), scheduler: TaskScheduler.Default ); synchronizationContext.RunMessagePump(); try { rootOperationTask .GetAwaiter() .GetResult(); } catch (AggregateException eWaitForTask) // The TPL will almost always wrap an AggregateException around any exception thrown by the async operation. { // Is this just a wrapped exception? AggregateException flattenedAggregate = eWaitForTask.Flatten(); if (flattenedAggregate.InnerExceptions.Count != 1) throw; // Nope, genuine aggregate. // Yep, so rethrow (preserving original stack-trace). ExceptionDispatchInfo .Capture( flattenedAggregate .InnerExceptions[0] ) .Throw(); } } } finally { SetSynchronizationContext(savedContext); } } /// <summary> /// Run an asynchronous operation using the current thread as its synchronisation context. /// </summary> /// <typeparam name="TResult"> /// The operation result type. /// </typeparam> /// <param name="asyncOperation"> /// A <see cref="Func{TResult}"/> delegate representing the asynchronous operation to run. /// </param> /// <returns> /// The operation result. /// </returns> public static TResult RunSynchronized<TResult>(Func<Task<TResult>> asyncOperation) { if (asyncOperation == null) throw new ArgumentNullException(nameof(asyncOperation)); SynchronizationContext savedContext = Current; try { using (ThreadAffinitiveSynchronizationContext synchronizationContext = new ThreadAffinitiveSynchronizationContext()) { SetSynchronizationContext(synchronizationContext); Task<TResult> rootOperationTask = asyncOperation(); if (rootOperationTask == null) throw new InvalidOperationException("The asynchronous operation delegate cannot return null."); rootOperationTask.ContinueWith( operationTask => synchronizationContext.TerminateMessagePump(), scheduler: TaskScheduler.Default ); synchronizationContext.RunMessagePump(); try { return rootOperationTask .GetAwaiter() .GetResult(); } catch (AggregateException eWaitForTask) // The TPL will almost always wrap an AggregateException around any exception thrown by the async operation. { // Is this just a wrapped exception? AggregateException flattenedAggregate = eWaitForTask.Flatten(); if (flattenedAggregate.InnerExceptions.Count != 1) throw; // Nope, genuine aggregate. // Yep, so rethrow (preserving original stack-trace). ExceptionDispatchInfo .Capture( flattenedAggregate .InnerExceptions[0] ) .Throw(); throw; // Never reached. } } } finally { SetSynchronizationContext(savedContext); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Addins; using Mono.Addins.Setup; using Mono.Addins.Description; using OpenSim.Framework; namespace OpenSim.Framework { /// <summary> /// Manager for registries and plugins /// </summary> public class PluginManager : SetupService { public AddinRegistry PluginRegistry; public PluginManager(AddinRegistry registry): base (registry) { PluginRegistry = registry; } /// <summary> /// Installs the plugin. /// </summary> /// <returns> /// The plugin. /// </returns> /// <param name='args'> /// Arguments. /// </param> public bool InstallPlugin(int ndx, out Dictionary<string, object> result) { Dictionary<string, object> res = new Dictionary<string, object>(); PackageCollection pack = new PackageCollection(); PackageCollection toUninstall; DependencyCollection unresolved; IProgressStatus ps = new ConsoleProgressStatus(false); AddinRepositoryEntry[] available = GetSortedAvailbleAddins(); if (ndx > (available.Length - 1)) { MainConsole.Instance.Output("Selection out of range"); result = res; return false; } AddinRepositoryEntry aentry = available[ndx]; Package p = Package.FromRepository(aentry); pack.Add(p); ResolveDependencies(ps, pack, out toUninstall, out unresolved); // Attempt to install the plugin disabled if (Install(ps, pack) == true) { MainConsole.Instance.Output("Ignore the following error..."); PluginRegistry.Update(ps); Addin addin = PluginRegistry.GetAddin(aentry.Addin.Id); PluginRegistry.DisableAddin(addin.Id); addin.Enabled = false; MainConsole.Instance.Output("Installation Success"); ListInstalledAddins(out res); result = res; return true; } else { MainConsole.Instance.Output("Installation Failed"); result = res; return false; } } // Remove plugin /// <summary> /// Uns the install. /// </summary> /// <param name='args'> /// Arguments. /// </param> public void UnInstall(int ndx) { Addin[] addins = GetSortedAddinList("RobustPlugin"); if (ndx > (addins.Length -1)) { MainConsole.Instance.Output("Selection out of range"); return; } Addin addin = addins[ndx]; MainConsole.Instance.OutputFormat("Uninstalling plugin {0}", addin.Id); AddinManager.Registry.DisableAddin(addin.Id); addin.Enabled = false; IProgressStatus ps = new ConsoleProgressStatus(false); Uninstall(ps, addin.Id); MainConsole.Instance.Output("Uninstall Success - restart to complete operation"); return; } /// <summary> /// Checks the installed. /// </summary> /// <returns> /// The installed. /// </returns> public string CheckInstalled() { return "CheckInstall"; } /// <summary> /// Lists the installed addins. /// </summary> /// <param name='result'> /// Result. /// </param> public void ListInstalledAddins(out Dictionary<string, object> result) { Dictionary<string, object> res = new Dictionary<string, object>(); Addin[] addins = GetSortedAddinList("RobustPlugin"); if(addins.Count() < 1) { MainConsole.Instance.Output("Error!"); } int count = 0; foreach (Addin addin in addins) { Dictionary<string, object> r = new Dictionary<string, object>(); r["enabled"] = addin.Enabled == true ? true : false; r["name"] = addin.LocalId; r["version"] = addin.Version; res.Add(count.ToString(), r); count++; } result = res; return; } // List compatible plugins in registered repositories /// <summary> /// Lists the available. /// </summary> /// <param name='result'> /// Result. /// </param> public void ListAvailable(out Dictionary<string, object> result) { Dictionary<string, object> res = new Dictionary<string, object>(); AddinRepositoryEntry[] addins = GetSortedAvailbleAddins(); int count = 0; foreach (AddinRepositoryEntry addin in addins) { Dictionary<string, object> r = new Dictionary<string, object>(); r["name"] = addin.Addin.Name; r["version"] = addin.Addin.Version; r["repository"] = addin.RepositoryName; res.Add(count.ToString(), r); count++; } result = res; return; } // List available updates ** 1 /// <summary> /// Lists the updates. /// </summary> public void ListUpdates() { IProgressStatus ps = new ConsoleProgressStatus(true); Console.WriteLine ("Looking for updates..."); Repositories.UpdateAllRepositories (ps); Console.WriteLine ("Available add-in updates:"); AddinRepositoryEntry[] entries = Repositories.GetAvailableUpdates(); foreach (AddinRepositoryEntry entry in entries) { Console.WriteLine(String.Format("{0}",entry.Addin.Id)); } } // Sync to repositories /// <summary> /// Update this instance. /// </summary> public string Update() { IProgressStatus ps = new ConsoleProgressStatus(true); Repositories.UpdateAllRepositories(ps); return "Update"; } // Register a repository /// <summary> /// Register a repository with our server. /// </summary> /// <returns> /// result of the action /// </returns> /// <param name='repo'> /// The URL of the repository we want to add /// </param> public bool AddRepository(string repo) { Repositories.RegisterRepository(null, repo, true); PluginRegistry.Rebuild(null); return true; } /// <summary> /// Gets the repository. /// </summary> public void GetRepository() { Repositories.UpdateAllRepositories(new ConsoleProgressStatus(false)); } // Remove a repository from the list /// <summary> /// Removes the repository. /// </summary> /// <param name='args'> /// Arguments. /// </param> public void RemoveRepository(string[] args) { AddinRepository[] reps = Repositories.GetRepositories(); Array.Sort(reps, (r1,r2) => r1.Title.CompareTo(r2.Title)); if (reps.Length == 0) { MainConsole.Instance.Output("No repositories have been registered."); return; } int n = Convert.ToInt16(args[2]); if (n > (reps.Length -1)) { MainConsole.Instance.Output("Selection out of range"); return; } AddinRepository rep = reps[n]; Repositories.RemoveRepository(rep.Url); return; } // Enable repository /// <summary> /// Enables the repository. /// </summary> /// <param name='args'> /// Arguments. /// </param> public void EnableRepository(string[] args) { AddinRepository[] reps = Repositories.GetRepositories(); Array.Sort(reps, (r1,r2) => r1.Title.CompareTo(r2.Title)); if (reps.Length == 0) { MainConsole.Instance.Output("No repositories have been registered."); return; } int n = Convert.ToInt16(args[2]); if (n > (reps.Length -1)) { MainConsole.Instance.Output("Selection out of range"); return; } AddinRepository rep = reps[n]; Repositories.SetRepositoryEnabled(rep.Url, true); return; } // Disable a repository /// <summary> /// Disables the repository. /// </summary> /// <param name='args'> /// Arguments. /// </param> public void DisableRepository(string[] args) { AddinRepository[] reps = Repositories.GetRepositories(); Array.Sort(reps, (r1,r2) => r1.Title.CompareTo(r2.Title)); if (reps.Length == 0) { MainConsole.Instance.Output("No repositories have been registered."); return; } int n = Convert.ToInt16(args[2]); if (n > (reps.Length -1)) { MainConsole.Instance.Output("Selection out of range"); return; } AddinRepository rep = reps[n]; Repositories.SetRepositoryEnabled(rep.Url, false); return; } // List registered repositories /// <summary> /// Lists the repositories. /// </summary> /// <param name='result'> /// Result. /// </param> public void ListRepositories(out Dictionary<string, object> result) { Dictionary<string, object> res = new Dictionary<string, object>(); result = res; AddinRepository[] reps = GetSortedAddinRepo(); if (reps.Length == 0) { MainConsole.Instance.Output("No repositories have been registered."); return; } int count = 0; foreach (AddinRepository rep in reps) { Dictionary<string, object> r = new Dictionary<string, object>(); r["enabled"] = rep.Enabled == true ? true : false; r["name"] = rep.Name; r["url"] = rep.Url; res.Add(count.ToString(), r); count++; } return; } /// <summary> /// Updates the registry. /// </summary> public void UpdateRegistry() { PluginRegistry.Update(); } // Show plugin info /// <summary> /// Addins the info. /// </summary> /// <returns> /// The info. /// </returns> /// <param name='args'> /// Arguments. /// </param> public bool AddinInfo(int ndx, out Dictionary<string, object> result) { Dictionary<string, object> res = new Dictionary<string, object>(); result = res; Addin[] addins = GetSortedAddinList("RobustPlugin"); if (ndx > (addins.Length - 1)) { MainConsole.Instance.Output("Selection out of range"); return false; } // author category description Addin addin = addins[ndx]; res["author"] = addin.Description.Author; res["category"] = addin.Description.Category; res["description"] = addin.Description.Description; res["name"] = addin.Name; res["url"] = addin.Description.Url; res["file_name"] = addin.Description.FileName; result = res; return true; } // Disable a plugin /// <summary> /// Disables the plugin. /// </summary> /// <param name='args'> /// Arguments. /// </param> public void DisablePlugin(string[] args) { Addin[] addins = GetSortedAddinList("RobustPlugin"); int n = Convert.ToInt16(args[2]); if (n > (addins.Length -1)) { MainConsole.Instance.Output("Selection out of range"); return; } Addin addin = addins[n]; AddinManager.Registry.DisableAddin(addin.Id); addin.Enabled = false; return; } // Enable plugin /// <summary> /// Enables the plugin. /// </summary> /// <param name='args'> /// Arguments. /// </param> public void EnablePlugin(string[] args) { Addin[] addins = GetSortedAddinList("RobustPlugin"); int n = Convert.ToInt16(args[2]); if (n > (addins.Length -1)) { MainConsole.Instance.Output("Selection out of range"); return; } Addin addin = addins[n]; addin.Enabled = true; AddinManager.Registry.EnableAddin(addin.Id); // AddinManager.Registry.Update(); if(PluginRegistry.IsAddinEnabled(addin.Id)) { ConsoleProgressStatus ps = new ConsoleProgressStatus(false); if (!AddinManager.AddinEngine.IsAddinLoaded(addin.Id)) { MainConsole.Instance.Output("Ignore the following error..."); AddinManager.Registry.Rebuild(ps); AddinManager.AddinEngine.LoadAddin(ps, addin.Id); } } else { MainConsole.Instance.OutputFormat("Not Enabled in this domain {0}", addin.Name); } return; } #region Util private void Testing() { Addin[] list = Registry.GetAddins(); var addins = list.Where( a => a.Description.Category == "RobustPlugin"); foreach (Addin addin in addins) { MainConsole.Instance.OutputFormat("Addin {0}", addin.Name); } } // These will let us deal with numbered lists instead // of needing to type in the full ids private AddinRepositoryEntry[] GetSortedAvailbleAddins() { ArrayList list = new ArrayList(); list.AddRange(Repositories.GetAvailableAddins()); AddinRepositoryEntry[] addins = list.ToArray(typeof(AddinRepositoryEntry)) as AddinRepositoryEntry[]; Array.Sort(addins,(r1,r2) => r1.Addin.Id.CompareTo(r2.Addin.Id)); return addins; } private AddinRepository[] GetSortedAddinRepo() { ArrayList list = new ArrayList(); list.AddRange(Repositories.GetRepositories()); AddinRepository[] repos = list.ToArray(typeof(AddinRepository)) as AddinRepository[]; Array.Sort (repos,(r1,r2) => r1.Name.CompareTo(r2.Name)); return repos; } private Addin[] GetSortedAddinList(string category) { ArrayList xlist = new ArrayList(); ArrayList list = new ArrayList(); try { list.AddRange(PluginRegistry.GetAddins()); } catch (Exception) { Addin[] x = xlist.ToArray(typeof(Addin)) as Addin[]; return x; } foreach (Addin addin in list) { if (addin.Description.Category == category) xlist.Add(addin); } Addin[] addins = xlist.ToArray(typeof(Addin)) as Addin[]; Array.Sort(addins,(r1,r2) => r1.Id.CompareTo(r2.Id)); return addins; } #endregion Util } }
// 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.Runtime.InteropServices; using System.Threading; using Xunit; public partial class ThreadPoolBoundHandleTests { [Fact] public unsafe void SingleOperationOverSingleHandle() { const int DATA_SIZE = 2; SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"SingleOverlappedOverSingleHandle.tmp"); ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle); OverlappedContext result = new OverlappedContext(); byte[] data = new byte[DATA_SIZE]; data[0] = (byte)'A'; data[1] = (byte)'B'; NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result, data); fixed (byte* p = data) { int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operation to complete result.Event.WaitOne(); } boundHandle.FreeNativeOverlapped(overlapped); boundHandle.Dispose(); handle.Dispose(); Assert.Equal(0, result.ErrorCode); Assert.Equal(DATA_SIZE, result.BytesWritten); } [Fact] public unsafe void MultipleOperationsOverSingleHandle() { const int DATA_SIZE = 2; SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverSingleHandle.tmp"); ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle); OverlappedContext result1 = new OverlappedContext(); OverlappedContext result2 = new OverlappedContext(); byte[] data1 = new byte[DATA_SIZE]; data1[0] = (byte)'A'; data1[1] = (byte)'B'; byte[] data2 = new byte[DATA_SIZE]; data2[0] = (byte)'C'; data2[1] = (byte)'D'; NativeOverlapped* overlapped1 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result1, data1); NativeOverlapped* overlapped2 = boundHandle.AllocateNativeOverlapped(OnOverlappedOperationCompleted, result2, data2); fixed (byte* p1 = data1, p2 = data2) { int retval = DllImport.WriteFile(boundHandle.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Start the offset after the above write, so that it doesn't overwrite the previous write overlapped2->OffsetLow = DATA_SIZE; retval = DllImport.WriteFile(boundHandle.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operations to complete WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event }); } boundHandle.FreeNativeOverlapped(overlapped1); boundHandle.FreeNativeOverlapped(overlapped2); boundHandle.Dispose(); handle.Dispose(); Assert.Equal(0, result1.ErrorCode); Assert.Equal(0, result2.ErrorCode); Assert.Equal(DATA_SIZE, result1.BytesWritten); Assert.Equal(DATA_SIZE, result2.BytesWritten); } [Fact] public unsafe void MultipleOperationsOverMultipleHandles() { const int DATA_SIZE = 2; SafeHandle handle1 = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverMultipleHandle1.tmp"); SafeHandle handle2 = HandleFactory.CreateAsyncFileHandleForWrite(@"MultipleOperationsOverMultipleHandle2.tmp"); ThreadPoolBoundHandle boundHandle1 = ThreadPoolBoundHandle.BindHandle(handle1); ThreadPoolBoundHandle boundHandle2 = ThreadPoolBoundHandle.BindHandle(handle2); OverlappedContext result1 = new OverlappedContext(); OverlappedContext result2 = new OverlappedContext(); byte[] data1 = new byte[DATA_SIZE]; data1[0] = (byte)'A'; data1[1] = (byte)'B'; byte[] data2 = new byte[DATA_SIZE]; data2[0] = (byte)'C'; data2[1] = (byte)'D'; PreAllocatedOverlapped preAlloc1 = new PreAllocatedOverlapped(OnOverlappedOperationCompleted, result1, data1); PreAllocatedOverlapped preAlloc2 = new PreAllocatedOverlapped(OnOverlappedOperationCompleted, result2, data2); for (int i = 0; i < 10; i++) { NativeOverlapped* overlapped1 = boundHandle1.AllocateNativeOverlapped(preAlloc1); NativeOverlapped* overlapped2 = boundHandle2.AllocateNativeOverlapped(preAlloc2); fixed (byte* p1 = data1, p2 = data2) { int retval = DllImport.WriteFile(boundHandle1.Handle, p1, DATA_SIZE, IntPtr.Zero, overlapped1); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } retval = DllImport.WriteFile(boundHandle2.Handle, p2, DATA_SIZE, IntPtr.Zero, overlapped2); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operations to complete WaitHandle.WaitAll(new WaitHandle[] { result1.Event, result2.Event }); } boundHandle1.FreeNativeOverlapped(overlapped1); boundHandle2.FreeNativeOverlapped(overlapped2); result1.Event.Reset(); result2.Event.Reset(); Assert.Equal(0, result1.ErrorCode); Assert.Equal(0, result2.ErrorCode); Assert.Equal(DATA_SIZE, result1.BytesWritten); Assert.Equal(DATA_SIZE, result2.BytesWritten); } boundHandle1.Dispose(); boundHandle2.Dispose(); preAlloc1.Dispose(); preAlloc2.Dispose(); handle1.Dispose(); handle2.Dispose(); } [Fact] public unsafe void FlowsAsyncLocalsToCallback() { // Makes sure that we flow async locals to callback const int DATA_SIZE = 2; SafeHandle handle = HandleFactory.CreateAsyncFileHandleForWrite(@"AsyncLocal.tmp"); ThreadPoolBoundHandle boundHandle = ThreadPoolBoundHandle.BindHandle(handle); OverlappedContext context = new OverlappedContext(); byte[] data = new byte[DATA_SIZE]; AsyncLocal<int> asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 10; int? result = null; IOCompletionCallback callback = (_, __, ___) => { result = asyncLocal.Value; OnOverlappedOperationCompleted(_, __, ___); }; NativeOverlapped* overlapped = boundHandle.AllocateNativeOverlapped(callback, context, data); fixed (byte* p = data) { int retval = DllImport.WriteFile(boundHandle.Handle, p, DATA_SIZE, IntPtr.Zero, overlapped); if (retval == 0) { Assert.Equal(DllImport.ERROR_IO_PENDING, Marshal.GetLastWin32Error()); } // Wait for overlapped operation to complete context.Event.WaitOne(); } boundHandle.FreeNativeOverlapped(overlapped); boundHandle.Dispose(); handle.Dispose(); Assert.Equal(10, result); } private static unsafe void OnOverlappedOperationCompleted(uint errorCode, uint numBytes, NativeOverlapped* overlapped) { OverlappedContext result = (OverlappedContext)ThreadPoolBoundHandle.GetNativeOverlappedState(overlapped); result.ErrorCode = (int)errorCode; result.BytesWritten = (int)numBytes; // Signal original thread to indicate overlapped completed result.Event.Set(); } private class OverlappedContext { public readonly ManualResetEvent Event = new ManualResetEvent(false); public int ErrorCode; public int BytesWritten; } }
//------------------------------------------------------------------------------ // <copyright file="HttpResponseWrapper.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web { using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Caching; using System.Web.Routing; [TypeForwardedFrom("System.Web.Abstractions, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public class HttpResponseWrapper : HttpResponseBase { private HttpResponse _httpResponse; public HttpResponseWrapper(HttpResponse httpResponse) { if (httpResponse == null) { throw new ArgumentNullException("httpResponse"); } _httpResponse = httpResponse; } public override bool Buffer { get { return _httpResponse.Buffer; } set { _httpResponse.Buffer = value; } } public override bool BufferOutput { get { return _httpResponse.BufferOutput; } set { _httpResponse.BufferOutput = value; } } public override HttpCachePolicyBase Cache { get { return new HttpCachePolicyWrapper(_httpResponse.Cache); } } public override string CacheControl { get { return _httpResponse.CacheControl; } set { _httpResponse.CacheControl = value; } } public override string Charset { get { return _httpResponse.Charset; } set { _httpResponse.Charset = value; } } public override CancellationToken ClientDisconnectedToken { get { return _httpResponse.ClientDisconnectedToken; } } public override Encoding ContentEncoding { get { return _httpResponse.ContentEncoding; } set { _httpResponse.ContentEncoding = value; } } public override string ContentType { get { return _httpResponse.ContentType; } set { _httpResponse.ContentType = value; } } public override HttpCookieCollection Cookies { get { return _httpResponse.Cookies; } } public override int Expires { get { return _httpResponse.Expires; } set { _httpResponse.Expires = value; } } public override DateTime ExpiresAbsolute { get { return _httpResponse.ExpiresAbsolute; } set { _httpResponse.ExpiresAbsolute = value; } } public override Stream Filter { get { return _httpResponse.Filter; } set { _httpResponse.Filter = value; } } public override NameValueCollection Headers { get { return _httpResponse.Headers; } } public override bool HeadersWritten { get { return _httpResponse.HeadersWritten; } } public override Encoding HeaderEncoding { get { return _httpResponse.HeaderEncoding; } set { _httpResponse.HeaderEncoding = value; } } public override bool IsClientConnected { get { return _httpResponse.IsClientConnected; } } public override bool IsRequestBeingRedirected { get { return _httpResponse.IsRequestBeingRedirected; } } public override TextWriter Output { get { return _httpResponse.Output; } set { _httpResponse.Output = value; } } public override Stream OutputStream { get { return _httpResponse.OutputStream; } } public override string RedirectLocation { get { return _httpResponse.RedirectLocation; } set { _httpResponse.RedirectLocation = value; } } public override string Status { get { return _httpResponse.Status; } set { _httpResponse.Status = value; } } public override int StatusCode { get { return _httpResponse.StatusCode; } set { _httpResponse.StatusCode = value; } } public override string StatusDescription { get { return _httpResponse.StatusDescription; } set { _httpResponse.StatusDescription = value; } } public override int SubStatusCode { get { return _httpResponse.SubStatusCode; } set { _httpResponse.SubStatusCode = value; } } public override bool SupportsAsyncFlush { get { return _httpResponse.SupportsAsyncFlush; } } public override bool SuppressContent { get { return _httpResponse.SuppressContent; } set { _httpResponse.SuppressContent = value; } } public override bool SuppressDefaultCacheControlHeader { get { return _httpResponse.SuppressDefaultCacheControlHeader; } set { _httpResponse.SuppressDefaultCacheControlHeader = value; } } public override bool SuppressFormsAuthenticationRedirect { get { return _httpResponse.SuppressFormsAuthenticationRedirect; } set { _httpResponse.SuppressFormsAuthenticationRedirect = value; } } public override bool TrySkipIisCustomErrors { get { return _httpResponse.TrySkipIisCustomErrors; } set { _httpResponse.TrySkipIisCustomErrors = value; } } public override void AddCacheItemDependency(string cacheKey) { _httpResponse.AddCacheItemDependency(cacheKey); } public override void AddCacheItemDependencies(ArrayList cacheKeys) { _httpResponse.AddCacheItemDependencies(cacheKeys); } public override void AddCacheItemDependencies(string[] cacheKeys) { _httpResponse.AddCacheItemDependencies(cacheKeys); } public override void AddCacheDependency(params CacheDependency[] dependencies) { _httpResponse.AddCacheDependency(dependencies); } public override void AddFileDependency(string filename) { _httpResponse.AddFileDependency(filename); } public override ISubscriptionToken AddOnSendingHeaders(Action<HttpContextBase> callback) { return _httpResponse.AddOnSendingHeaders(HttpContextWrapper.WrapCallback(callback)); } public override void AddFileDependencies(ArrayList filenames) { _httpResponse.AddFileDependencies(filenames); } public override void AddFileDependencies(string[] filenames) { _httpResponse.AddFileDependencies(filenames); } public override void AddHeader(string name, string value) { _httpResponse.AddHeader(name, value); } public override void AppendCookie(HttpCookie cookie) { _httpResponse.AppendCookie(cookie); } public override void AppendHeader(string name, string value) { _httpResponse.AppendHeader(name, value); } public override void AppendToLog(string param) { _httpResponse.AppendToLog(param); } public override string ApplyAppPathModifier(string virtualPath) { return _httpResponse.ApplyAppPathModifier(virtualPath); } public override IAsyncResult BeginFlush(AsyncCallback callback, Object state) { return _httpResponse.BeginFlush(callback, state); } public override void BinaryWrite(byte[] buffer) { _httpResponse.BinaryWrite(buffer); } public override void Clear() { _httpResponse.Clear(); } public override void ClearContent() { _httpResponse.ClearContent(); } public override void ClearHeaders() { _httpResponse.ClearHeaders(); } public override void Close() { _httpResponse.Close(); } public override void DisableKernelCache() { _httpResponse.DisableKernelCache(); } public override void DisableUserCache() { _httpResponse.DisableUserCache(); } public override void End() { _httpResponse.End(); } public override void EndFlush(IAsyncResult asyncResult) { _httpResponse.EndFlush(asyncResult); } public override void Flush() { _httpResponse.Flush(); } public override Task FlushAsync() { return _httpResponse.FlushAsync(); } public override void Pics(string value) { _httpResponse.Pics(value); } public override void Redirect(string url) { _httpResponse.Redirect(url); } public override void Redirect(string url, bool endResponse) { _httpResponse.Redirect(url, endResponse); } public override void RedirectPermanent(String url) { _httpResponse.RedirectPermanent(url); } public override void RedirectPermanent(String url, bool endResponse) { _httpResponse.RedirectPermanent(url, endResponse); } public override void RedirectToRoute(object routeValues) { _httpResponse.RedirectToRoute(routeValues); } public override void RedirectToRoute(string routeName) { _httpResponse.RedirectToRoute(routeName); } public override void RedirectToRoute(RouteValueDictionary routeValues) { _httpResponse.RedirectToRoute(routeValues); } public override void RedirectToRoute(string routeName, object routeValues) { _httpResponse.RedirectToRoute(routeName, routeValues); } public override void RedirectToRoute(string routeName, RouteValueDictionary routeValues) { _httpResponse.RedirectToRoute(routeName, routeValues); } public override void RedirectToRoutePermanent(object routeValues) { _httpResponse.RedirectToRoutePermanent(routeValues); } public override void RedirectToRoutePermanent(string routeName) { _httpResponse.RedirectToRoutePermanent(routeName); } public override void RedirectToRoutePermanent(RouteValueDictionary routeValues) { _httpResponse.RedirectToRoutePermanent(routeValues); } public override void RedirectToRoutePermanent(string routeName, object routeValues) { _httpResponse.RedirectToRoutePermanent(routeName, routeValues); } public override void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues) { _httpResponse.RedirectToRoutePermanent(routeName, routeValues); } public override void RemoveOutputCacheItem(string path) { HttpResponse.RemoveOutputCacheItem(path); } public override void RemoveOutputCacheItem(string path, string providerName) { HttpResponse.RemoveOutputCacheItem(path, providerName); } public override void SetCookie(HttpCookie cookie) { _httpResponse.SetCookie(cookie); } public override void TransmitFile(string filename) { _httpResponse.TransmitFile(filename); } public override void TransmitFile(string filename, long offset, long length) { _httpResponse.TransmitFile(filename, offset, length); } public override void Write(string s) { _httpResponse.Write(s); } public override void Write(char ch) { _httpResponse.Write(ch); } public override void Write(char[] buffer, int index, int count) { _httpResponse.Write(buffer, index, count); } public override void Write(object obj) { _httpResponse.Write(obj); } public override void WriteFile(string filename) { _httpResponse.WriteFile(filename); } public override void WriteFile(string filename, bool readIntoMemory) { _httpResponse.WriteFile(filename, readIntoMemory); } public override void WriteFile(string filename, long offset, long size) { _httpResponse.WriteFile(filename, offset, size); } public override void WriteFile(IntPtr fileHandle, long offset, long size) { _httpResponse.WriteFile(fileHandle, offset, size); } public override void WriteSubstitution(HttpResponseSubstitutionCallback callback) { _httpResponse.WriteSubstitution(callback); } public override void PushPromise(string path) { _httpResponse.PushPromise(path); } public override void PushPromise(string path, string method, NameValueCollection headers) { _httpResponse.PushPromise(path, method, headers); } } }
// 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.IO; using System.Linq; using System.Xml.Serialization; namespace Microsoft.NodejsTools.Profiling { [Serializable] public sealed class ProfilingTarget { internal static XmlSerializer Serializer = new XmlSerializer(typeof(ProfilingTarget)); [XmlElement("ProjectTarget")] public ProjectTarget ProjectTarget { get; set; } [XmlElement("StandaloneTarget")] public StandaloneTarget StandaloneTarget { get; set; } [XmlElement("Reports")] public Reports Reports { get; set; } internal string GetProfilingName(out bool save) { string baseName = null; if (ProjectTarget != null) { if (!String.IsNullOrEmpty(ProjectTarget.FriendlyName)) { baseName = ProjectTarget.FriendlyName; } } else if (StandaloneTarget != null) { if (!String.IsNullOrEmpty(StandaloneTarget.Script)) { baseName = Path.GetFileNameWithoutExtension(StandaloneTarget.Script); } } if (baseName == null) { baseName = "Performance"; } baseName = baseName + NodejsProfilingPackage.PerfFileType; var dte = (EnvDTE.DTE)NodejsProfilingPackage.GetGlobalService(typeof(EnvDTE.DTE)); if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) { save = true; return Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), baseName); } save = false; return baseName; } internal ProfilingTarget Clone() { var res = new ProfilingTarget(); if (ProjectTarget != null) { res.ProjectTarget = ProjectTarget.Clone(); } if (StandaloneTarget != null) { res.StandaloneTarget = StandaloneTarget.Clone(); } if (Reports != null) { res.Reports = Reports.Clone(); } return res; } internal static bool IsSame(ProfilingTarget self, ProfilingTarget other) { if (self == null) { return other == null; } else if (other != null) { return ProjectTarget.IsSame(self.ProjectTarget, other.ProjectTarget) && StandaloneTarget.IsSame(self.StandaloneTarget, other.StandaloneTarget); } return false; } } [Serializable] public sealed class ProjectTarget { [XmlElement("TargetProject")] public Guid TargetProject { get; set; } [XmlElement("FriendlyName")] public string FriendlyName { get; set; } internal ProjectTarget Clone() { var res = new ProjectTarget(); res.TargetProject = TargetProject; res.FriendlyName = FriendlyName; return res; } internal static bool IsSame(ProjectTarget self, ProjectTarget other) { if (self == null) { return other == null; } else if (other != null) { return self.TargetProject == other.TargetProject; } return false; } } [Serializable] public sealed class StandaloneTarget { [XmlElement(ElementName = "InterpreterPath")] public string InterpreterPath { get; set; } [XmlElement("WorkingDirectory")] public string WorkingDirectory { get; set; } [XmlElement("Script")] public string Script { get; set; } [XmlElement("Arguments")] public string Arguments { get; set; } internal StandaloneTarget Clone() { var res = new StandaloneTarget(); res.InterpreterPath = InterpreterPath; res.WorkingDirectory = WorkingDirectory; res.Script = Script; res.Arguments = Arguments; return res; } internal static bool IsSame(StandaloneTarget self, StandaloneTarget other) { if (self == null) { return other == null; } else if (other != null) { return self.InterpreterPath == other.InterpreterPath && self.WorkingDirectory == other.WorkingDirectory && self.Script == other.Script && self.Arguments == other.Arguments; } return false; } } public sealed class Reports { public Reports() { } public Reports(Profiling.Report[] reports) { Report = reports; } [XmlElement("Report")] public Report[] Report { get { return AllReports.Values.ToArray(); } set { AllReports = new SortedDictionary<int, Report>(); for (int i = 0; i < value.Length; i++) { AllReports[i + SessionNode.StartingReportId] = value[i]; } } } internal SortedDictionary<int, Report> AllReports { get; set; } internal Reports Clone() { var res = new Reports(); if (Report != null) { res.Report = new Report[Report.Length]; for (int i = 0; i < res.Report.Length; i++) { res.Report[i] = Report[i].Clone(); } } return res; } } public sealed class Report { public Report() { } public Report(string filename) { Filename = filename; } [XmlElement("Filename")] public string Filename { get; set; } internal Report Clone() { var res = new Report(); res.Filename = Filename; return res; } } }
using System; using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class MemberServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Can_Create_Role() { ServiceContext.MemberService.AddRole("MyTestRole"); var found = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); } [Test] public void Can_Create_Duplicate_Role() { ServiceContext.MemberService.AddRole("MyTestRole"); ServiceContext.MemberService.AddRole("MyTestRole"); var found = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); } [Test] public void Can_Get_All_Roles() { ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AddRole("MyTestRole2"); ServiceContext.MemberService.AddRole("MyTestRole3"); var found = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(3, found.Count()); } [Test] public void Can_Get_All_Roles_By_Member_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AddRole("MyTestRole2"); ServiceContext.MemberService.AddRole("MyTestRole3"); ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); var memberRoles = ServiceContext.MemberService.GetAllRoles(member.Id); Assert.AreEqual(2, memberRoles.Count()); } [Test] public void Can_Get_All_Roles_By_Member_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); //need to test with '@' symbol in the lookup IMember member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AddRole("MyTestRole2"); ServiceContext.MemberService.AddRole("MyTestRole3"); ServiceContext.MemberService.AssignRoles(new[] { member.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); var memberRoles = ServiceContext.MemberService.GetAllRoles("test"); Assert.AreEqual(2, memberRoles.Count()); var memberRoles2 = ServiceContext.MemberService.GetAllRoles("test2@test.com"); Assert.AreEqual(2, memberRoles2.Count()); } [Test] public void Can_Delete_Role() { ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.DeleteRole("MyTestRole1", false); var memberRoles = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(0, memberRoles.Count()); } [Test] public void Throws_When_Deleting_Assigned_Role() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); Assert.Throws<InvalidOperationException>(() => ServiceContext.MemberService.DeleteRole("MyTestRole1", true)); } [Test] public void Can_Get_Members_In_Role() { ServiceContext.MemberService.AddRole("MyTestRole1"); var roleId = DatabaseContext.Database.ExecuteScalar<int>("SELECT id from umbracoNode where [text] = 'MyTestRole1'"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); DatabaseContext.Database.Insert(new Member2MemberGroupDto {MemberGroup = roleId, Member = member1.Id}); DatabaseContext.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member2.Id }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [TestCase("MyTestRole1", "test1", StringPropertyMatchType.StartsWith, 1)] [TestCase("MyTestRole1", "test", StringPropertyMatchType.StartsWith, 3)] [TestCase("MyTestRole1", "test1", StringPropertyMatchType.Exact, 1)] [TestCase("MyTestRole1", "test", StringPropertyMatchType.Exact, 0)] [TestCase("MyTestRole1", "st2", StringPropertyMatchType.EndsWith, 1)] [TestCase("MyTestRole1", "test%", StringPropertyMatchType.Wildcard, 3)] public void Find_Members_In_Role(string roleName1, string usernameToMatch, StringPropertyMatchType matchType, int resultCount) { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); var member3 = MockedMember.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3"); ServiceContext.MemberService.Save(member3); ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id, member3.Id }, new[] { roleName1 }); var result = ServiceContext.MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType); Assert.AreEqual(resultCount, result.Count()); } [Test] public void Associate_Members_To_Roles_With_Member_Id() { ServiceContext.MemberService.AddRole("MyTestRole1"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Associate_Members_To_Roles_With_Member_Username() { ServiceContext.MemberService.AddRole("MyTestRole1"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Associate_Members_To_Roles_With_Member_Username_Containing_At_Symbols() { ServiceContext.MemberService.AddRole("MyTestRole1"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Associate_Members_To_Roles_With_New_Role() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); //implicitly create the role ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Remove_Members_From_Roles_With_Member_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); ServiceContext.MemberService.DissociateRoles(new[] {member1.Id }, new[] {"MyTestRole1"}); ServiceContext.MemberService.DissociateRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole2" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); } [Test] public void Remove_Members_From_Roles_With_Member_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1", "MyTestRole2" }); ServiceContext.MemberService.DissociateRoles(new[] { member1.Username }, new[] { "MyTestRole1" }); ServiceContext.MemberService.DissociateRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole2" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); } [Test] public void Can_Delete_member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); ServiceContext.MemberService.Delete(member); var deleted = ServiceContext.MemberService.GetById(member.Id); // Assert Assert.That(deleted, Is.Null); } [Test] public void ContentXml_Created_When_Saved() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = member.Id }); Assert.IsNotNull(xml); } [Test] public void Exists_By_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); IMember member2 = MockedMember.CreateSimpleMember(memberType, "test", "test2@test.com", "pass", "test2@test.com"); ServiceContext.MemberService.Save(member2); Assert.IsTrue(ServiceContext.MemberService.Exists("test")); Assert.IsFalse(ServiceContext.MemberService.Exists("notFound")); Assert.IsTrue(ServiceContext.MemberService.Exists("test2@test.com")); } [Test] public void Exists_By_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsTrue(ServiceContext.MemberService.Exists(member.Id)); Assert.IsFalse(ServiceContext.MemberService.Exists(9876)); } [Test] public void Tracks_Dirty_Changes() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); var resolved = ServiceContext.MemberService.GetByEmail(member.Email); //NOTE: This will not trigger a property isDirty because this is not based on a 'Property', it is // just a c# property of the Member object resolved.Email = "changed@test.com"; //NOTE: this WILL trigger a property isDirty because setting this c# property actually sets a value of // the underlying 'Property' resolved.FailedPasswordAttempts = 1234; var dirtyMember = (ICanBeDirty)resolved; var dirtyProperties = resolved.Properties.Where(x => x.IsDirty()).ToList(); Assert.IsTrue(dirtyMember.IsDirty()); Assert.AreEqual(1, dirtyProperties.Count()); } [Test] public void Get_By_Email() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsNotNull(ServiceContext.MemberService.GetByEmail(member.Email)); Assert.IsNull(ServiceContext.MemberService.GetByEmail("do@not.find")); } [Test] public void Get_Member_Name() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "Test Real Name", "test@test.com", "pass", "testUsername"); ServiceContext.MemberService.Save(member); Assert.AreEqual("Test Real Name", member.Name); } [Test] public void Get_Member_Name_In_Created_Event() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); TypedEventHandler<IMemberService, NewEventArgs<IMember>> callback = (sender, args) => { Assert.AreEqual("Test Real Name", args.Entity.Name); }; MemberService.Created += callback; var member = ServiceContext.MemberService.CreateMember("testUsername", "test@test.com", "Test Real Name", memberType); MemberService.Created -= callback; } [Test] public void Get_By_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsNotNull(ServiceContext.MemberService.GetByUsername(member.Username)); Assert.IsNull(ServiceContext.MemberService.GetByUsername("notFound")); } [Test] public void Get_By_Object_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsNotNull(ServiceContext.MemberService.GetById(member.Id)); Assert.IsNull(ServiceContext.MemberService.GetById(9876)); } [Test] public void Get_All_Paged_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); int totalRecs; var found = ServiceContext.MemberService.GetAll(0, 2, out totalRecs); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); Assert.AreEqual("test0", found.First().Username); Assert.AreEqual("test1", found.Last().Username); } [Test] public void Find_By_Name_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "Bob", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindMembersByDisplayName("B", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(1, found.Count()); } [Test] public void Find_By_Email_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //don't find this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello","hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Find_By_Email_Ends_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("test.com", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Email_Contains() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Email_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("hello@test.com", 0, 100, out totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Find_By_Login_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //don't find this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Find_By_Login_Ends_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("llo", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); } [Test] public void Find_By_Login_Contains() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Login_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("hello", 0, 100, out totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Get_By_Property_String_Value_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", "hello member", StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Get_By_Property_String_Value_Contains() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", " member", StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Get_By_Property_String_Value_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", "Member No", StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Get_By_Property_String_Value_Ends_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("title", "title of mine"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", "mine", StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); } [Test] public void Get_By_Property_Int_Value_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "number", Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 2); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 2, ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); } [Test] public void Get_By_Property_Int_Value_Greater_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "number", Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); } [Test] public void Get_By_Property_Int_Value_Greater_Than_Equal_To() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "number", Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); } [Test] public void Get_By_Property_Int_Value_Less_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.DateAlias, DataTypeDatabaseType.Date) { Alias = "number", Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); } [Test] public void Get_By_Property_Int_Value_Less_Than_Or_Equal() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "number", Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); } [Test] public void Get_By_Property_Date_Value_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "date", Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 2, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 2, 0), ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); } [Test] public void Get_By_Property_Date_Value_Greater_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "date", Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); } [Test] public void Get_By_Property_Date_Value_Greater_Than_Equal_To() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "date", Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); } [Test] public void Get_By_Property_Date_Value_Less_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "date", Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); } [Test] public void Get_By_Property_Date_Value_Less_Than_Or_Equal() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer) { Alias = "date", Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); } [Test] public void Count_All_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.All); Assert.AreEqual(11, found); } [Test] public void Count_All_Online_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.LastLoginDate, DateTime.Now); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.Online); Assert.AreEqual(9, found); } [Test] public void Count_All_Locked_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsLockedOut, true); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } [Test] public void Count_All_Approved_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsApproved, false); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.Approved); Assert.AreEqual(5, found); } [Test] public void Setting_Property_On_Built_In_Member_Property_When_Property_Doesnt_Exist_On_Type_Is_Ok() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); memberType.RemovePropertyType(Constants.Conventions.Member.Comments); ServiceContext.MemberTypeService.Save(memberType); Assert.IsFalse(memberType.PropertyTypes.Any(x => x.Alias == Constants.Conventions.Member.Comments)); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); //this should not throw an exception customMember.Comments = "hello world"; ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetById(customMember.Id); Assert.IsTrue(found.Comments.IsNullOrWhiteSpace()); } /// <summary> /// Because we are forcing some of the built-ins to be Labels which have an underlying db type as nvarchar but we need /// to ensure that the dates/int get saved to the correct column anyways. /// </summary> [Test] public void Setting_DateTime_Property_On_Built_In_Member_Property_Saves_To_Correct_Column() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test"); var date = DateTime.Now; member.LastLoginDate = DateTime.Now; ServiceContext.MemberService.Save(member); var result = ServiceContext.MemberService.GetById(member.Id); Assert.AreEqual( date.TruncateTo(DateTimeExtensions.DateTruncate.Second), result.LastLoginDate.TruncateTo(DateTimeExtensions.DateTruncate.Second)); //now ensure the col is correct var sql = new Sql().Select("cmsPropertyData.*") .From<PropertyDataDto>() .InnerJoin<PropertyTypeDto>() .On<PropertyDataDto, PropertyTypeDto>(dto => dto.PropertyTypeId, dto => dto.Id) .Where<PropertyDataDto>(dto => dto.NodeId == member.Id) .Where<PropertyTypeDto>(dto => dto.Alias == Constants.Conventions.Member.LastLoginDate); var colResult = DatabaseContext.Database.Fetch<PropertyDataDto>(sql); Assert.AreEqual(1, colResult.Count); Assert.IsTrue(colResult.First().Date.HasValue); Assert.IsFalse(colResult.First().Integer.HasValue); Assert.IsNull(colResult.First().Text); Assert.IsNull(colResult.First().VarChar); } [Test] public void New_Member_Approved_By_Default() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetById(customMember.Id); Assert.IsTrue(found.IsApproved); } [Test] public void Ensure_Content_Xml_Created() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var provider = new PetaPocoUnitOfWorkProvider(); var uow = provider.GetUnitOfWork(); using (RepositoryResolver.Current.ResolveByType<IMemberRepository>(uow)) { Assert.IsTrue(uow.Database.Exists<ContentXmlDto>(customMember.Id)); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Logging.V2.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedMetricsServiceV2ClientSnippets { /// <summary>Snippet for ListLogMetrics</summary> public void ListLogMetricsRequestObject() { // Snippet: ListLogMetrics(ListLogMetricsRequest, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) ListLogMetricsRequest request = new ListLogMetricsRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetrics(request); // Iterate over all response items, lazily performing RPCs as required foreach (LogMetric item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogMetricsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogMetric> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogMetric item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogMetricsAsync</summary> public async Task ListLogMetricsRequestObjectAsync() { // Snippet: ListLogMetricsAsync(ListLogMetricsRequest, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) ListLogMetricsRequest request = new ListLogMetricsRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogMetric item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogMetricsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogMetric> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogMetric item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogMetrics</summary> public void ListLogMetrics() { // Snippet: ListLogMetrics(string, string, int?, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetrics(parent); // Iterate over all response items, lazily performing RPCs as required foreach (LogMetric item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogMetricsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogMetric> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogMetric item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogMetricsAsync</summary> public async Task ListLogMetricsAsync() { // Snippet: ListLogMetricsAsync(string, string, int?, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogMetric item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogMetricsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogMetric> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogMetric item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogMetrics</summary> public void ListLogMetricsResourceNames() { // Snippet: ListLogMetrics(ProjectName, string, int?, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetrics(parent); // Iterate over all response items, lazily performing RPCs as required foreach (LogMetric item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListLogMetricsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogMetric> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogMetric item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListLogMetricsAsync</summary> public async Task ListLogMetricsResourceNamesAsync() { // Snippet: ListLogMetricsAsync(ProjectName, string, int?, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListLogMetricsResponse, LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogMetric item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListLogMetricsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<LogMetric> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (LogMetric item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetLogMetric</summary> public void GetLogMetricRequestObject() { // Snippet: GetLogMetric(GetLogMetricRequest, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) GetLogMetricRequest request = new GetLogMetricRequest { MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"), }; // Make the request LogMetric response = metricsServiceV2Client.GetLogMetric(request); // End snippet } /// <summary>Snippet for GetLogMetricAsync</summary> public async Task GetLogMetricRequestObjectAsync() { // Snippet: GetLogMetricAsync(GetLogMetricRequest, CallSettings) // Additional: GetLogMetricAsync(GetLogMetricRequest, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) GetLogMetricRequest request = new GetLogMetricRequest { MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"), }; // Make the request LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(request); // End snippet } /// <summary>Snippet for GetLogMetric</summary> public void GetLogMetric() { // Snippet: GetLogMetric(string, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string metricName = "projects/[PROJECT]/metrics/[METRIC]"; // Make the request LogMetric response = metricsServiceV2Client.GetLogMetric(metricName); // End snippet } /// <summary>Snippet for GetLogMetricAsync</summary> public async Task GetLogMetricAsync() { // Snippet: GetLogMetricAsync(string, CallSettings) // Additional: GetLogMetricAsync(string, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) string metricName = "projects/[PROJECT]/metrics/[METRIC]"; // Make the request LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(metricName); // End snippet } /// <summary>Snippet for GetLogMetric</summary> public void GetLogMetricResourceNames() { // Snippet: GetLogMetric(LogMetricName, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"); // Make the request LogMetric response = metricsServiceV2Client.GetLogMetric(metricName); // End snippet } /// <summary>Snippet for GetLogMetricAsync</summary> public async Task GetLogMetricResourceNamesAsync() { // Snippet: GetLogMetricAsync(LogMetricName, CallSettings) // Additional: GetLogMetricAsync(LogMetricName, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"); // Make the request LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(metricName); // End snippet } /// <summary>Snippet for CreateLogMetric</summary> public void CreateLogMetricRequestObject() { // Snippet: CreateLogMetric(CreateLogMetricRequest, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) CreateLogMetricRequest request = new CreateLogMetricRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Metric = new LogMetric(), }; // Make the request LogMetric response = metricsServiceV2Client.CreateLogMetric(request); // End snippet } /// <summary>Snippet for CreateLogMetricAsync</summary> public async Task CreateLogMetricRequestObjectAsync() { // Snippet: CreateLogMetricAsync(CreateLogMetricRequest, CallSettings) // Additional: CreateLogMetricAsync(CreateLogMetricRequest, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) CreateLogMetricRequest request = new CreateLogMetricRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), Metric = new LogMetric(), }; // Make the request LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(request); // End snippet } /// <summary>Snippet for CreateLogMetric</summary> public void CreateLogMetric() { // Snippet: CreateLogMetric(string, LogMetric, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; LogMetric metric = new LogMetric(); // Make the request LogMetric response = metricsServiceV2Client.CreateLogMetric(parent, metric); // End snippet } /// <summary>Snippet for CreateLogMetricAsync</summary> public async Task CreateLogMetricAsync() { // Snippet: CreateLogMetricAsync(string, LogMetric, CallSettings) // Additional: CreateLogMetricAsync(string, LogMetric, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; LogMetric metric = new LogMetric(); // Make the request LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(parent, metric); // End snippet } /// <summary>Snippet for CreateLogMetric</summary> public void CreateLogMetricResourceNames() { // Snippet: CreateLogMetric(ProjectName, LogMetric, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = metricsServiceV2Client.CreateLogMetric(parent, metric); // End snippet } /// <summary>Snippet for CreateLogMetricAsync</summary> public async Task CreateLogMetricResourceNamesAsync() { // Snippet: CreateLogMetricAsync(ProjectName, LogMetric, CallSettings) // Additional: CreateLogMetricAsync(ProjectName, LogMetric, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(parent, metric); // End snippet } /// <summary>Snippet for UpdateLogMetric</summary> public void UpdateLogMetricRequestObject() { // Snippet: UpdateLogMetric(UpdateLogMetricRequest, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) UpdateLogMetricRequest request = new UpdateLogMetricRequest { MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"), Metric = new LogMetric(), }; // Make the request LogMetric response = metricsServiceV2Client.UpdateLogMetric(request); // End snippet } /// <summary>Snippet for UpdateLogMetricAsync</summary> public async Task UpdateLogMetricRequestObjectAsync() { // Snippet: UpdateLogMetricAsync(UpdateLogMetricRequest, CallSettings) // Additional: UpdateLogMetricAsync(UpdateLogMetricRequest, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) UpdateLogMetricRequest request = new UpdateLogMetricRequest { MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"), Metric = new LogMetric(), }; // Make the request LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(request); // End snippet } /// <summary>Snippet for UpdateLogMetric</summary> public void UpdateLogMetric() { // Snippet: UpdateLogMetric(string, LogMetric, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string metricName = "projects/[PROJECT]/metrics/[METRIC]"; LogMetric metric = new LogMetric(); // Make the request LogMetric response = metricsServiceV2Client.UpdateLogMetric(metricName, metric); // End snippet } /// <summary>Snippet for UpdateLogMetricAsync</summary> public async Task UpdateLogMetricAsync() { // Snippet: UpdateLogMetricAsync(string, LogMetric, CallSettings) // Additional: UpdateLogMetricAsync(string, LogMetric, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) string metricName = "projects/[PROJECT]/metrics/[METRIC]"; LogMetric metric = new LogMetric(); // Make the request LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(metricName, metric); // End snippet } /// <summary>Snippet for UpdateLogMetric</summary> public void UpdateLogMetricResourceNames() { // Snippet: UpdateLogMetric(LogMetricName, LogMetric, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = metricsServiceV2Client.UpdateLogMetric(metricName, metric); // End snippet } /// <summary>Snippet for UpdateLogMetricAsync</summary> public async Task UpdateLogMetricResourceNamesAsync() { // Snippet: UpdateLogMetricAsync(LogMetricName, LogMetric, CallSettings) // Additional: UpdateLogMetricAsync(LogMetricName, LogMetric, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(metricName, metric); // End snippet } /// <summary>Snippet for DeleteLogMetric</summary> public void DeleteLogMetricRequestObject() { // Snippet: DeleteLogMetric(DeleteLogMetricRequest, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) DeleteLogMetricRequest request = new DeleteLogMetricRequest { MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"), }; // Make the request metricsServiceV2Client.DeleteLogMetric(request); // End snippet } /// <summary>Snippet for DeleteLogMetricAsync</summary> public async Task DeleteLogMetricRequestObjectAsync() { // Snippet: DeleteLogMetricAsync(DeleteLogMetricRequest, CallSettings) // Additional: DeleteLogMetricAsync(DeleteLogMetricRequest, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) DeleteLogMetricRequest request = new DeleteLogMetricRequest { MetricNameAsLogMetricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"), }; // Make the request await metricsServiceV2Client.DeleteLogMetricAsync(request); // End snippet } /// <summary>Snippet for DeleteLogMetric</summary> public void DeleteLogMetric() { // Snippet: DeleteLogMetric(string, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string metricName = "projects/[PROJECT]/metrics/[METRIC]"; // Make the request metricsServiceV2Client.DeleteLogMetric(metricName); // End snippet } /// <summary>Snippet for DeleteLogMetricAsync</summary> public async Task DeleteLogMetricAsync() { // Snippet: DeleteLogMetricAsync(string, CallSettings) // Additional: DeleteLogMetricAsync(string, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) string metricName = "projects/[PROJECT]/metrics/[METRIC]"; // Make the request await metricsServiceV2Client.DeleteLogMetricAsync(metricName); // End snippet } /// <summary>Snippet for DeleteLogMetric</summary> public void DeleteLogMetricResourceNames() { // Snippet: DeleteLogMetric(LogMetricName, CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"); // Make the request metricsServiceV2Client.DeleteLogMetric(metricName); // End snippet } /// <summary>Snippet for DeleteLogMetricAsync</summary> public async Task DeleteLogMetricResourceNamesAsync() { // Snippet: DeleteLogMetricAsync(LogMetricName, CallSettings) // Additional: DeleteLogMetricAsync(LogMetricName, CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = await MetricsServiceV2Client.CreateAsync(); // Initialize request argument(s) LogMetricName metricName = LogMetricName.FromProjectMetric("[PROJECT]", "[METRIC]"); // Make the request await metricsServiceV2Client.DeleteLogMetricAsync(metricName); // End snippet } } }