context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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.ComponentModel.Design; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Versions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets; using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Setup { [Guid(Guids.RoslynPackageIdString)] [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", version: 10)] internal class RoslynPackage : Package { private LibraryManager _libraryManager; private uint _libraryManagerCookie; private VisualStudioWorkspace _workspace; private WorkspaceFailureOutputPane _outputPane; private IComponentModel _componentModel; private RuleSetEventHandler _ruleSetEventHandler; private IDisposable _solutionEventMonitor; protected override void Initialize() { base.Initialize(); ForegroundThreadAffinitizedObject.Initialize(); FatalError.Handler = FailFast.OnFatalException; FatalError.NonFatalHandler = WatsonReporter.Report; // We also must set the FailFast handler for the compiler layer as well var compilerAssembly = typeof(Compilation).Assembly; var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true); var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public); var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true); var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic); property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method)); InitializePortableShim(compilerAssembly); RegisterFindResultsLibraryManager(); var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel)); _workspace = componentModel.GetService<VisualStudioWorkspace>(); var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>(); foreach (var telemetrySetup in telemetrySetupExtensions) { telemetrySetup.Initialize(this); } // set workspace output pane _outputPane = new WorkspaceFailureOutputPane(this, _workspace); InitializeColors(); // load some services that have to be loaded in UI thread LoadComponentsInUIContext(); _solutionEventMonitor = new SolutionEventMonitor(_workspace); } private static void InitializePortableShim(Assembly compilerAssembly) { // We eagerly force all of the types to be loaded within the PortableShim because there are scenarios // in which loading types can trigger the current AppDomain's AssemblyResolve or TypeResolve events. // If handlers of those events do anything that would cause PortableShim to be accessed recursively, // bad things can happen. In particular, this fixes the scenario described in TFS bug #1185842. // // Note that the fix below is written to be as defensive as possible to do no harm if it impacts other // scenarios. // Initialize the PortableShim linked into the Workspaces layer. Roslyn.Utilities.PortableShim.Initialize(); // Initialize the PortableShim linked into the Compilers layer via reflection. var compilerPortableShim = compilerAssembly.GetType("Roslyn.Utilities.PortableShim", throwOnError: false); var initializeMethod = compilerPortableShim?.GetMethod(nameof(Roslyn.Utilities.PortableShim.Initialize), BindingFlags.Static | BindingFlags.NonPublic); initializeMethod?.Invoke(null, null); } private void InitializeColors() { // Use VS color keys in order to support theming. CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey; CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey; CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey; CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey; CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey; CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey; } private void LoadComponentsInUIContext() { if (KnownUIContexts.SolutionExistsAndFullyLoadedContext.IsActive) { // if we are already in the right UI context, load it right away LoadComponents(); } else { // load them when it is a right context. KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged += OnSolutionExistsAndFullyLoadedContext; } } private void OnSolutionExistsAndFullyLoadedContext(object sender, UIContextChangedEventArgs e) { if (e.Activated) { // unsubscribe from it KnownUIContexts.SolutionExistsAndFullyLoadedContext.UIContextChanged -= OnSolutionExistsAndFullyLoadedContext; // load components LoadComponents(); } } private void LoadComponents() { // we need to load it as early as possible since we can have errors from // package from each language very early this.ComponentModel.GetService<VisualStudioDiagnosticListTable>(); this.ComponentModel.GetService<VisualStudioTodoListTable>(); this.ComponentModel.GetService<VisualStudioTodoTaskList>(); this.ComponentModel.GetService<HACK_ThemeColorFixer>(); this.ComponentModel.GetExtensions<IReferencedSymbolsPresenter>(); this.ComponentModel.GetExtensions<INavigableItemsPresenter>(); this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>(); this.ComponentModel.GetService<VirtualMemoryNotificationListener>(); LoadAnalyzerNodeComponents(); Task.Run(() => LoadComponentsBackground()); } private void LoadComponentsBackground() { // Perf: Initialize the command handlers. var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>(); commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType); this.ComponentModel.GetService<MiscellaneousTodoListTable>(); this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>(); } internal IComponentModel ComponentModel { get { if (_componentModel == null) { _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } return _componentModel; } } protected override void Dispose(bool disposing) { UnregisterFindResultsLibraryManager(); DisposeVisualStudioDocumentTrackingService(); UnregisterAnalyzerTracker(); UnregisterRuleSetEventHandler(); ReportSessionWideTelemetry(); if (_solutionEventMonitor != null) { _solutionEventMonitor.Dispose(); _solutionEventMonitor = null; } base.Dispose(disposing); } private void ReportSessionWideTelemetry() { PersistedVersionStampLogger.LogSummary(); } private void RegisterFindResultsLibraryManager() { var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2; if (objectManager != null) { _libraryManager = new LibraryManager(this); if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie))) { _libraryManagerCookie = 0; } ((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true); } } private void UnregisterFindResultsLibraryManager() { if (_libraryManagerCookie != 0) { var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2; if (objectManager != null) { objectManager.UnregisterLibrary(_libraryManagerCookie); _libraryManagerCookie = 0; } ((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true); _libraryManager = null; } } private void DisposeVisualStudioDocumentTrackingService() { if (_workspace != null) { var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService; documentTrackingService.Dispose(); } } private void LoadAnalyzerNodeComponents() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this); _ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>(); if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Register(); } } private void UnregisterAnalyzerTracker() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister(); } private void UnregisterRuleSetEventHandler() { if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Unregister(); _ruleSetEventHandler = null; } } } }
// // Xkb.cs // // Author: // Stefanos Apostolopoulos <stapostol@gmail.com> // // Copyright (c) 2006-2014 // // 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.Diagnostics; using System.Runtime.InteropServices; #pragma warning disable 0169 namespace OpenTK.Platform.X11 { using Atom = IntPtr; using KeyCode = Byte; using XkbControlsPtr = IntPtr; using XkbServerMapPtr = IntPtr; using XkbClientMapPtr = IntPtr; using XkbIndicatorPtr = IntPtr; using XkbCompatMapPtr = IntPtr; using XkbGeometryPtr = IntPtr; internal class Xkb { private const string lib = "libX11"; internal const int KeyNameLength = 4; internal const int NumModifiers = 8; internal const int NumVirtualMods = 16; internal const int NumIndicators = 32; internal const int NumKbdGroups = 4; internal const int UseCoreKeyboard = 0x0100; [DllImport(lib, EntryPoint = "XkbFreeKeyboard")] unsafe internal extern static void FreeKeyboard(XkbDesc* descr, int which, bool free); [DllImport(lib, EntryPoint = "XkbAllocKeyboard")] unsafe internal extern static XkbDesc* AllocKeyboard(IntPtr display); [DllImport(lib, EntryPoint = "XkbGetKeyboard")] internal extern static IntPtr GetKeyboard(IntPtr display, XkbKeyboardMask which, int device_id); [DllImport(lib, EntryPoint = "XkbGetMap")] internal extern static IntPtr GetMap(IntPtr display, XkbKeyboardMask which, int device_spec); [DllImport(lib, EntryPoint = "XkbGetNames")] unsafe internal extern static IntPtr GetNames(IntPtr display, XkbNamesMask which, XkbDesc* xkb); [DllImport(lib, EntryPoint = "XkbKeycodeToKeysym")] internal extern static XKey KeycodeToKeysym(IntPtr display, int keycode, int group, int level); [DllImport(lib, EntryPoint = "XkbQueryExtension")] internal extern static bool QueryExtension(IntPtr display, out int opcode_rtrn, out int event_rtrn, out int error_rtrn, ref int major_in_out, ref int minor_in_out); [DllImport(lib, EntryPoint = "XkbSetDetectableAutoRepeat")] internal extern static bool SetDetectableAutoRepeat(IntPtr display, bool detectable, out bool supported); internal static bool IsSupported(IntPtr display) { // The XkbQueryExtension manpage says that we cannot // use XQueryExtension with XKB. int opcode, error, ev; int major = 1; int minor = 0; bool supported = QueryExtension(display, out opcode, out ev, out error, ref major, ref minor); Debug.Print("XKB extension is {0}.", supported ? "supported" : "not supported"); if (supported) { Debug.Print("XKB version is {0}.{1}", major, minor); } return supported; } } [Flags] internal enum XkbKeyboardMask { Controls = 1 << 0, ServerMap = 1 << 1, IClientMap = 1 << 2, IndicatorMap = 1 << 3, Names = 1 << 4, CompatibilityMap = 1 << 5, Geometry = 1 << 6, AllComponents = 1 << 7, } [Flags] internal enum XkbNamesMask { Keycodes = 1 << 0, Geometry = 1 << 1, Symbols = 1 << 2, PhysSymbols = 1 << 3, Types = 1 << 4, Compat = 1 << 5, KeyType = 1 << 6, KTLevel = 1 << 7, Indicator = 1 << 8, Key = 1 << 9, KeyAliasesMask = 1 << 10, VirtualMod = 1 << 11, Group = 1 << 12, RG = 1 << 13, Component = 0x3f, All = 0x3fff } [StructLayout(LayoutKind.Sequential)] internal unsafe struct XkbDesc { internal IntPtr dpy; internal ushort flags; internal ushort device_spec; internal KeyCode min_key_code; internal KeyCode max_key_code; internal XkbControlsPtr ctrls; internal XkbServerMapPtr server; internal XkbClientMapPtr map; internal XkbIndicatorPtr indicators; internal XkbNames* names; internal XkbCompatMapPtr compat; internal XkbGeometryPtr geom; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct XkbKeyAlias { internal fixed byte real[Xkb.KeyNameLength]; internal fixed byte alias[Xkb.KeyNameLength]; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct XkbKeyName { internal fixed byte name[Xkb.KeyNameLength]; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct XkbNames { [StructLayout(LayoutKind.Sequential)] internal struct Groups { private Atom groups0; private Atom groups1; private Atom groups2; private Atom groups3; internal Atom this[int i] { get { if (i < 0 || i > 3) { throw new IndexOutOfRangeException(); } unsafe { fixed (Atom* ptr = &groups0) { return *(ptr + i); } } } } } [StructLayout(LayoutKind.Sequential)] internal struct Indicators { private Atom indicators0; private Atom indicators1; private Atom indicators2; private Atom indicators3; private Atom indicators4; private Atom indicators5; private Atom indicators6; private Atom indicators7; private Atom indicators8; private Atom indicators9; private Atom indicators10; private Atom indicators11; private Atom indicators12; private Atom indicators13; private Atom indicators14; private Atom indicators15; private Atom indicators16; private Atom indicators17; private Atom indicators18; private Atom indicators19; private Atom indicators20; private Atom indicators21; private Atom indicators22; private Atom indicators23; private Atom indicators24; private Atom indicators25; private Atom indicators26; private Atom indicators27; private Atom indicators28; private Atom indicators29; private Atom indicators30; private Atom indicators31; internal Atom this[int i] { get { if (i < 0 || i > 31) { throw new IndexOutOfRangeException(); } unsafe { fixed (Atom* ptr = &indicators0) { return *(ptr + i); } } } } } [StructLayout(LayoutKind.Sequential)] internal struct VMods { private Atom vmods0; private Atom vmods1; private Atom vmods2; private Atom vmods3; private Atom vmods4; private Atom vmods5; private Atom vmods6; private Atom vmods7; private Atom vmods8; private Atom vmods9; private Atom vmods10; private Atom vmods11; private Atom vmods12; private Atom vmods13; private Atom vmods14; private Atom vmods15; internal Atom this[int i] { get { if (i < 0 || i > 15) { throw new IndexOutOfRangeException(); } unsafe { fixed (Atom* ptr = &vmods0) { return *(ptr + i); } } } } } internal Atom keycodes; internal Atom geometry; internal Atom symbols; internal Atom types; internal Atom compat; internal VMods vmods; internal Indicators indicators; internal Groups groups; internal XkbKeyName* keys; internal XkbKeyAlias* key_aliases; internal Atom *radio_groups; internal Atom phys_symbols; internal byte num_keys; internal byte num_key_aliases; internal byte num_rg; } }
using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; using TDTK; namespace TDTK { [CustomEditor(typeof(BuildManager))] public class BuildManagerEditor : Editor { private static BuildManager instance; private static List<UnitTower> towerList=new List<UnitTower>(); private static bool showTowerList=true; private static string[] cursorIndModeLabel=new string[0]; private static string[] cursorIndModeTooltip=new string[0]; void Awake(){ instance = (BuildManager)target; GetTower(); int enumLength = Enum.GetValues(typeof(BuildManager._CursorIndicatorMode)).Length; cursorIndModeLabel=new string[enumLength]; cursorIndModeTooltip=new string[enumLength]; for(int i=0; i<enumLength; i++){ cursorIndModeLabel[i]=((BuildManager._CursorIndicatorMode)i).ToString(); if((BuildManager._CursorIndicatorMode)i==BuildManager._CursorIndicatorMode.All) cursorIndModeTooltip[i]="Always show the tile currently being hovered over by the cursor"; if((BuildManager._CursorIndicatorMode)i==BuildManager._CursorIndicatorMode.ValidOnly) cursorIndModeTooltip[i]="Only show the tile currently being hovered over by the cursor if it's available to be built on"; if((BuildManager._CursorIndicatorMode)i==BuildManager._CursorIndicatorMode.None) cursorIndModeTooltip[i]="Never show the tile currently being hovered over by the cursor"; } EditorUtility.SetDirty(instance); } private static void GetTower(){ EditorDBManager.Init(); towerList=EditorDBManager.GetTowerList(); if(Application.isPlaying) return; //instance.fullTowerList=towerList; List<int> towerIDList=EditorDBManager.GetTowerIDList(); for(int i=0; i<instance.unavailableTowerIDList.Count; i++){ if(!towerIDList.Contains(instance.unavailableTowerIDList[i])){ instance.unavailableTowerIDList.RemoveAt(i); i-=1; } } } //private Vector2 scrollPosition; private static bool showDefaultFlag=false; private GUIContent cont; private GUIContent[] contList; private static bool showPlatforms=false; public override void OnInspectorGUI(){ GUI.changed = false; EditorGUILayout.Space(); cont=new GUIContent("Grid Size:", "The grid size of the grid on the platform"); instance.gridSize=EditorGUILayout.FloatField(cont, instance.gridSize); cont=new GUIContent("AutoSearchForPlatform:", "Check to let the BuildManager automatically serach of all the build platform in game\nThis will override the BuildPlatform list"); instance.autoSearchForPlatform=EditorGUILayout.Toggle(cont, instance.autoSearchForPlatform); cont=new GUIContent("AutoAdjustTextureToGrid:", "Check to let the BuildManager reformat the texture tiling of the platform to fix the gridsize"); instance.AutoAdjustTextureToGrid=EditorGUILayout.Toggle(cont, instance.AutoAdjustTextureToGrid); EditorGUILayout.Space(); if(GUILayout.Button("Enable All Towers On All Platforms") && !Application.isPlaying){ EnableAllToweronAllPlatform(); } cont=new GUIContent("Build Platforms", "Build Platform in this level\nOnly applicable when AutoSearchForPlatform is unchecked"); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("", GUILayout.MaxWidth(10)); showPlatforms = EditorGUILayout.Foldout(showPlatforms, cont); EditorGUILayout.EndHorizontal(); if(showPlatforms){ cont=new GUIContent("Build Platforms:", "The grid size of the grid on the platform"); float listSize=instance.buildPlatforms.Count; listSize=EditorGUILayout.FloatField(" Size:", listSize); //if(!EditorGUIUtility.editingTextField && listSize!=instance.buildPlatforms.Count){ if(listSize!=instance.buildPlatforms.Count){ while(instance.buildPlatforms.Count<listSize) instance.buildPlatforms.Add(null); while(instance.buildPlatforms.Count>listSize) instance.buildPlatforms.RemoveAt(instance.buildPlatforms.Count-1); } for(int i=0; i<instance.buildPlatforms.Count; i++){ instance.buildPlatforms[i]=(PlatformTD)EditorGUILayout.ObjectField(" Element "+i, instance.buildPlatforms[i], typeof(PlatformTD), true); } } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("", GUILayout.MaxWidth(10)); showTowerList=EditorGUILayout.Foldout(showTowerList, "Show Tower List"); EditorGUILayout.EndHorizontal(); if(showTowerList){ EditorGUILayout.BeginHorizontal(); if(GUILayout.Button("EnableAll") && !Application.isPlaying){ instance.unavailableTowerIDList=new List<int>(); } if(GUILayout.Button("DisableAll") && !Application.isPlaying){ instance.unavailableTowerIDList=new List<int>(); for(int i=0; i<towerList.Count; i++) instance.unavailableTowerIDList.Add(towerList[i].prefabID); } EditorGUILayout.EndHorizontal (); //scrollPosition = GUILayout.BeginScrollView (scrollPosition); for(int i=0; i<towerList.Count; i++){ UnitTower tower=towerList[i]; if(tower.disableInBuildManager) continue; GUILayout.BeginHorizontal(); GUILayout.Box("", GUILayout.Width(40), GUILayout.Height(40)); Rect rect=GUILayoutUtility.GetLastRect(); EditorUtilities.DrawSprite(rect, tower.iconSprite, false); GUILayout.BeginVertical(); EditorGUILayout.Space(); GUILayout.Label(tower.unitName, GUILayout.ExpandWidth(false)); bool flag=!instance.unavailableTowerIDList.Contains(tower.prefabID) ? true : false; if(Application.isPlaying) flag=!flag; //switch it around in runtime flag=EditorGUILayout.Toggle(new GUIContent(" - enabled: ", "check to enable the tower in this level"), flag); if(!Application.isPlaying){ if(flag) instance.unavailableTowerIDList.Remove(tower.prefabID); else{ if(!instance.unavailableTowerIDList.Contains(tower.prefabID)) instance.unavailableTowerIDList.Add(tower.prefabID); } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } //GUILayout.EndScrollView (); } EditorGUILayout.Space(); int cursorMode=(int)instance.cursorIndicatorMode; cont=new GUIContent("Tile Cursor Mode:", "The way to indicate a tile on a grid when it's currently being hovered on by the cursor"); contList=new GUIContent[cursorIndModeLabel.Length]; for(int i=0; i<contList.Length; i++) contList[i]=new GUIContent(cursorIndModeLabel[i], cursorIndModeTooltip[i]); cursorMode = EditorGUILayout.Popup(cont, cursorMode, contList); instance.cursorIndicatorMode=(BuildManager._CursorIndicatorMode)cursorMode; EditorGUILayout.Space(); if(GUILayout.Button("Open TowerEditor")){ UnitTowerEditorWindow.Init(); } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("", GUILayout.MaxWidth(10)); showDefaultFlag=EditorGUILayout.Foldout(showDefaultFlag, "Show default editor"); EditorGUILayout.EndHorizontal(); if(showDefaultFlag) DrawDefaultInspector(); if(GUI.changed) EditorUtility.SetDirty(instance); } void EnableAllToweronAllPlatform(){ PlatformTD[] platList = FindObjectsOfType(typeof(PlatformTD)) as PlatformTD[]; for(int i=0; i<platList.Length; i++) platList[i].availableTowerIDList=new List<int>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Threading; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile { /// <summary> /// Used by the 2 Create factory method groups. A null fileHandle specifies that the /// memory mapped file should not be associated with an existing file on disk (i.e. start /// out empty). /// </summary> private static SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); SafeMemoryMappedFileHandle handle = fileHandle != null ? Interop.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName) : Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return handle; } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen) { return OpenCore(mapName, inheritability, GetFileMapAccess(access), createOrOpen); } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen) { return OpenCore(mapName, inheritability, GetFileMapAccess(rights), createOrOpen); } /// <summary> /// Used by the CreateOrOpen factory method groups. /// </summary> private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { /// Try to open the file if it exists -- this requires a bit more work. Loop until we can /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail /// if the file exists and we have non-null security attributes, in which case we need to /// use OpenFileMapping. But, there exists a race condition because the memory mapped file /// may have closed between the two calls -- hence the loop. /// /// The retry/timeout logic increases the wait time each pass through the loop and times /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened, /// throw an InvalidOperationException. Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we get valid handle while (waitRetries > 0) { // try to create handle = Interop.CreateFileMapping(new IntPtr(-1), ref secAttrs, GetPageAccess(access) | (int)options, capacity, mapName); if (!handle.IsInvalid) { break; } else { handle.Dispose(); int createErrorCode = Marshal.GetLastWin32Error(); if (createErrorCode != Interop.Errors.ERROR_ACCESS_DENIED) { throw Win32Marshal.GetExceptionForWin32Error(createErrorCode); } } // try to open handle = Interop.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { handle.Dispose(); int openErrorCode = Marshal.GetLastWin32Error(); if (openErrorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { throw Win32Marshal.GetExceptionForWin32Error(openErrorCode); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { Thread.Sleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping); } return handle; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// This converts a MemoryMappedFileRights to its corresponding native FILE_MAP_XXX value to be used when /// creating new views. /// </summary> private static int GetFileMapAccess(MemoryMappedFileRights rights) { return (int)rights; } /// <summary> /// This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when /// creating new views. /// </summary> internal static int GetFileMapAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: return Interop.Kernel32.FileMapOptions.FILE_MAP_READ; case MemoryMappedFileAccess.Write: return Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE; case MemoryMappedFileAccess.ReadWrite: return Interop.Kernel32.FileMapOptions.FILE_MAP_READ | Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE; case MemoryMappedFileAccess.CopyOnWrite: return Interop.Kernel32.FileMapOptions.FILE_MAP_COPY; case MemoryMappedFileAccess.ReadExecute: return Interop.Kernel32.FileMapOptions.FILE_MAP_EXECUTE | Interop.Kernel32.FileMapOptions.FILE_MAP_READ; default: Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute); return Interop.Kernel32.FileMapOptions.FILE_MAP_EXECUTE | Interop.Kernel32.FileMapOptions.FILE_MAP_READ | Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE; } } /// <summary> /// This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the /// factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not /// valid here since there is no corresponding PAGE_XXX value. /// </summary> internal static int GetPageAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: return Interop.Kernel32.PageOptions.PAGE_READONLY; case MemoryMappedFileAccess.ReadWrite: return Interop.Kernel32.PageOptions.PAGE_READWRITE; case MemoryMappedFileAccess.CopyOnWrite: return Interop.Kernel32.PageOptions.PAGE_WRITECOPY; case MemoryMappedFileAccess.ReadExecute: return Interop.Kernel32.PageOptions.PAGE_EXECUTE_READ; default: Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute); return Interop.Kernel32.PageOptions.PAGE_EXECUTE_READWRITE; } } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, int desiredAccessRights, bool createOrOpen) { SafeMemoryMappedFileHandle handle = Interop.OpenFileMapping( desiredAccessRights, (inheritability & HandleInheritability.Inheritable) != 0, mapName); int lastError = Marshal.GetLastWin32Error(); if (handle.IsInvalid) { handle.Dispose(); if (createOrOpen && (lastError == Interop.Errors.ERROR_FILE_NOT_FOUND)) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } else { throw Win32Marshal.GetExceptionForWin32Error(lastError); } } return handle; } /// <summary> /// Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity /// type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned. /// </summary> private static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES(); secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES); secAttrs.bInheritHandle = Interop.BOOL.TRUE; } return secAttrs; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// UI logic. Manages all UI, raycasting, touch/mouse events passing and uiItem event notifications. /// For any tk2dUIItem to work there needs to be a tk2dUIManager in the scene /// </summary> [AddComponentMenu("2D Toolkit/UI/Core/tk2dUIManager")] public class tk2dUIManager : MonoBehaviour { public static double version = 1.0; public static int releaseId = 0; // < -10000 = alpha, other negative = beta release, 0 = final, positive = final patch /// <summary> /// Used to reference tk2dUIManager without a direct reference via singleton structure (will not auto-create and only one can exist at a time) /// </summary> private static tk2dUIManager instance; public static tk2dUIManager Instance { get { if (instance == null) { instance = FindObjectOfType(typeof(tk2dUIManager)) as tk2dUIManager; if (instance == null) { GameObject go = new GameObject("tk2dUIManager"); instance = go.AddComponent<tk2dUIManager>(); } } return instance; } } public static tk2dUIManager Instance__NoCreate { get { return instance; } } /// <summary> /// UICamera which raycasts for mouse/touch inputs are cast from /// </summary> [SerializeField] #pragma warning disable 649 private Camera uiCamera; #pragma warning restore 649 public Camera UICamera { get { return uiCamera; } set { uiCamera = value; } } public Camera GetUICameraForControl( GameObject go ) { int layer = 1 << go.layer; int cameraCount = allCameras.Count; for (int i = 0; i < cameraCount; ++i) { tk2dUICamera camera = allCameras[i]; if ((camera.FilteredMask & layer) != 0) { return camera.HostCamera; } } Debug.LogError("Unable to find UI camera for " + go.name); return null; } static List<tk2dUICamera> allCameras = new List<tk2dUICamera>(); List<tk2dUICamera> sortedCameras = new List<tk2dUICamera>(); public static void RegisterCamera(tk2dUICamera cam) { allCameras.Add(cam); } public static void UnregisterCamera(tk2dUICamera cam) { allCameras.Remove(cam); } /// <summary> /// Which layer the raycast will be done using. Will ignore others /// </summary> public LayerMask raycastLayerMask = -1; private bool inputEnabled = true; /// <summary> /// Used to disable user input /// </summary> public bool InputEnabled { get { return inputEnabled; } set { if (inputEnabled && !value) //disable current presses/hovers { SortCameras(); inputEnabled = value; if (useMultiTouch) { CheckMultiTouchInputs(); } else { CheckInputs(); } } else { inputEnabled = value; } } } /// <summary> /// If hover events are to be tracked. If you don't not need hover events disable for increased performance (less raycasting). /// Only works when using mouse and multi-touch is disabled (tk2dUIManager.useMultiTouch) /// </summary> public bool areHoverEventsTracked = true; //if disable no hover events will be tracked (less overhead), only effects if using mouse private tk2dUIItem pressedUIItem = null; /// <summary> /// Most recent pressedUIItem (if one is pressed). If multi-touch gets the most recent /// </summary> public tk2dUIItem PressedUIItem { get { //if multi-touch return the last item (most recent touch) if (useMultiTouch) { if (pressedUIItems.Length > 0) { return pressedUIItems[pressedUIItems.Length-1]; } else { return null; } } else { return pressedUIItem; } } } /// <summary> /// All currently pressed down UIItems if using multi-touch /// </summary> public tk2dUIItem[] PressedUIItems { get { return pressedUIItems; } } private tk2dUIItem overUIItem = null; //current hover over uiItem private tk2dUITouch firstPressedUIItemTouch; //used to determine deltas private bool checkForHovers = true; //if internal we are checking for hovers /// <summary> /// Use multi-touch. Only enable if you need multi-touch support. When multi-touch is enabled, hover events are disabled. /// Multi-touch disable will provide better performance and accuracy. /// </summary> [SerializeField] private bool useMultiTouch = false; public bool UseMultiTouch { get { return useMultiTouch; } set { if (useMultiTouch != value && inputEnabled) //changed { InputEnabled = false; //clears existing useMultiTouch = value; InputEnabled = true; } else { useMultiTouch = value; } } } //multi-touch specifics private const int MAX_MULTI_TOUCH_COUNT = 5; //number of touches at the same time private tk2dUITouch[] allTouches = new tk2dUITouch[MAX_MULTI_TOUCH_COUNT]; //all multi-touches private List<tk2dUIItem> prevPressedUIItemList = new List<tk2dUIItem>(); //previous pressed and still pressed UIItems private tk2dUIItem[] pressedUIItems = new tk2dUIItem[MAX_MULTI_TOUCH_COUNT]; //pressed UIItem on the this frame private int touchCounter = 0; //touchs counter private Vector2 mouseDownFirstPos = Vector2.zero; //used to determine mouse position deltas while in multi-touch //end multi-touch specifics private const string MOUSE_WHEEL_AXES_NAME = "Mouse ScrollWheel"; //Input name of mouse scroll wheel //for update loop private tk2dUITouch primaryTouch = new tk2dUITouch(); //main touch (generally began, or actively press) private tk2dUITouch secondaryTouch = new tk2dUITouch(); //secondary touches (generally other fingers) private tk2dUITouch resultTouch = new tk2dUITouch(); //which touch is selected between primary and secondary private tk2dUIItem hitUIItem; //current uiItem hit private RaycastHit hit; private Ray ray; //for update loop (multi-touch) private tk2dUITouch currTouch; private tk2dUIItem currPressedItem; private tk2dUIItem prevPressedItem; /// <summary> /// Only any touch began or mouse click /// </summary> public event System.Action OnAnyPress; /// <summary> /// Fired at the end of every update /// </summary> public event System.Action OnInputUpdate; /// <summary> /// On mouse scroll wheel change (return direction of mouse scroll wheel change) /// </summary> public event System.Action<float> OnScrollWheelChange; void SortCameras() { sortedCameras.Clear(); int cameraCount = allCameras.Count; for (int i = 0; i < cameraCount; ++i) { tk2dUICamera camera = allCameras[i]; if (camera != null) { sortedCameras.Add( camera ); } } // Largest depth gets priority sortedCameras.Sort( (a, b) => b.GetComponent<Camera>().depth.CompareTo( a.GetComponent<Camera>().depth ) ); } void Awake() { if (instance == null) { instance = this; if (instance.transform.childCount != 0) { Debug.LogError("You should not attach anything to the tk2dUIManager object. " + "The tk2dUIManager will not get destroyed between scene switches and any children will persist as well."); } if (Application.isPlaying) { DontDestroyOnLoad( gameObject ); } } else { //can only be one tk2dUIManager at one-time, if another one is found Destroy it if (instance != this) { Debug.Log("Discarding unnecessary tk2dUIManager instance."); if (uiCamera != null) { HookUpLegacyCamera(uiCamera); uiCamera = null; } Destroy(this); return; } } tk2dUITime.Init(); Setup(); } void HookUpLegacyCamera(Camera cam) { if (cam.GetComponent<tk2dUICamera>() == null) { // Handle registration properly tk2dUICamera newUICam = cam.gameObject.AddComponent<tk2dUICamera>(); newUICam.AssignRaycastLayerMask( raycastLayerMask ); } } void Start() { if (uiCamera != null) { Debug.Log("It is no longer necessary to hook up a camera to the tk2dUIManager. You can simply attach a tk2dUICamera script to the cameras that interact with UI."); HookUpLegacyCamera(uiCamera); uiCamera = null; } if (allCameras.Count == 0) { Debug.LogError("Unable to find any tk2dUICameras, and no cameras are connected to the tk2dUIManager. You will not be able to interact with the UI."); } } private void Setup() { if (!areHoverEventsTracked) { checkForHovers = false; } } void Update() { tk2dUITime.Update(); if (inputEnabled) { SortCameras(); if (useMultiTouch) { CheckMultiTouchInputs(); } else { CheckInputs(); } if (OnInputUpdate != null) { OnInputUpdate(); } if (OnScrollWheelChange != null) { float mouseWheel = Input.GetAxis(MOUSE_WHEEL_AXES_NAME); if (mouseWheel != 0) { OnScrollWheelChange(mouseWheel); } } } } //checks for inputs (non-multi-touch) private void CheckInputs() { bool isPrimaryTouchFound = false; bool isSecondaryTouchFound = false; bool isAnyPressBeganRecorded = false; primaryTouch = new tk2dUITouch(); secondaryTouch = new tk2dUITouch(); resultTouch = new tk2dUITouch(); hitUIItem = null; if (inputEnabled) { int touchCount = Input.touchCount; if (Input.touchCount > 0) { for (int touchIndex = 0; touchIndex < touchCount; ++touchIndex) { Touch touch = Input.GetTouch(touchIndex); if (touch.phase == TouchPhase.Began) { primaryTouch = new tk2dUITouch(touch); isPrimaryTouchFound = true; isAnyPressBeganRecorded = true; } else if (pressedUIItem != null && touch.fingerId == firstPressedUIItemTouch.fingerId) { secondaryTouch = new tk2dUITouch(touch); isSecondaryTouchFound = true; } } checkForHovers = false; } else { if (Input.GetMouseButtonDown(0)) { primaryTouch = new tk2dUITouch(TouchPhase.Began, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, Vector2.zero, 0); isPrimaryTouchFound = true; isAnyPressBeganRecorded = true; } else if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0)) { Vector2 deltaPosition = Vector2.zero; TouchPhase mousePhase = TouchPhase.Moved; if (pressedUIItem != null) { deltaPosition = firstPressedUIItemTouch.position - new Vector2(Input.mousePosition.x, Input.mousePosition.y); } if (Input.GetMouseButtonUp(0)) { mousePhase = TouchPhase.Ended; } else if (deltaPosition == Vector2.zero) { mousePhase = TouchPhase.Stationary; } secondaryTouch = new tk2dUITouch(mousePhase, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, deltaPosition, tk2dUITime.deltaTime); isSecondaryTouchFound = true; } } } if (isPrimaryTouchFound) { resultTouch = primaryTouch; } else if (isSecondaryTouchFound) { resultTouch = secondaryTouch; } if (isPrimaryTouchFound || isSecondaryTouchFound) //focus touch found { hitUIItem = RaycastForUIItem(resultTouch.position); if (resultTouch.phase == TouchPhase.Began) { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(hitUIItem); if (pressedUIItem != hitUIItem) { pressedUIItem.Release(); pressedUIItem = null; } else { firstPressedUIItemTouch = resultTouch; //just incase touch changed } } if (hitUIItem != null) { hitUIItem.Press(resultTouch); } pressedUIItem = hitUIItem; firstPressedUIItemTouch = resultTouch; } else if (resultTouch.phase == TouchPhase.Ended) { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(hitUIItem); pressedUIItem.UpdateTouch(resultTouch); pressedUIItem.Release(); pressedUIItem = null; } } else { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(hitUIItem); pressedUIItem.UpdateTouch(resultTouch); } } } else //no touches found { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(null); pressedUIItem.Release(); pressedUIItem = null; } } //only if hover events are enabled and only if no touch events have ever been recorded if (checkForHovers) { if (inputEnabled) //if input enabled and mouse button is not currently down { if (!isPrimaryTouchFound && !isSecondaryTouchFound && hitUIItem == null && !Input.GetMouseButton(0)) //if raycast for a button has not yet been done { hitUIItem = RaycastForUIItem( Input.mousePosition ); } else if (Input.GetMouseButton(0)) //if mouse button is down clear it { hitUIItem = null; } } if (hitUIItem != null) { if (hitUIItem.isHoverEnabled) { bool wasPrevOverFound = hitUIItem.HoverOver(overUIItem); if (!wasPrevOverFound && overUIItem != null) { overUIItem.HoverOut(hitUIItem); } overUIItem = hitUIItem; } else { if (overUIItem != null) { overUIItem.HoverOut(null); } } } else { if (overUIItem != null) { overUIItem.HoverOut(null); } } } if (isAnyPressBeganRecorded) { if (OnAnyPress != null) { OnAnyPress(); } } } //checks for inputs (multi-touch) private void CheckMultiTouchInputs() { bool isAnyPressBeganRecorded = false; int prevFingerID = -1; bool wasPrevTouchFound = false; bool isNewlyPressed = false; touchCounter = 0; if (inputEnabled) { if (Input.touchCount > 0) { foreach (Touch touch in Input.touches) { if (touchCounter < MAX_MULTI_TOUCH_COUNT) { allTouches[touchCounter] = new tk2dUITouch(touch); touchCounter++; } else { break; } } } else { if (Input.GetMouseButtonDown(0)) { allTouches[touchCounter] = new tk2dUITouch(TouchPhase.Began, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, Vector2.zero, 0); mouseDownFirstPos = Input.mousePosition; touchCounter++; } else if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0)) { Vector2 deltaPosition = mouseDownFirstPos - new Vector2(Input.mousePosition.x, Input.mousePosition.y); TouchPhase mousePhase = TouchPhase.Moved; if (Input.GetMouseButtonUp(0)) { mousePhase = TouchPhase.Ended; } else if (deltaPosition == Vector2.zero) { mousePhase = TouchPhase.Stationary; } allTouches[touchCounter] = new tk2dUITouch(mousePhase, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, deltaPosition, tk2dUITime.deltaTime); touchCounter++; } } } for (int p = 0; p < touchCounter; p++) { pressedUIItems[p] = RaycastForUIItem(allTouches[p].position); } //deals with all the previous presses for (int f=0; f<prevPressedUIItemList.Count; f++) { prevPressedItem = prevPressedUIItemList[f]; if (prevPressedItem != null) { prevFingerID = prevPressedItem.Touch.fingerId; wasPrevTouchFound=false; for (int t = 0; t < touchCounter; t++) { currTouch = allTouches[t]; if (currTouch.fingerId == prevFingerID) { wasPrevTouchFound=true; currPressedItem = pressedUIItems[t]; if (currTouch.phase == TouchPhase.Began) { prevPressedItem.CurrentOverUIItem(currPressedItem); if (prevPressedItem != currPressedItem) { prevPressedItem.Release(); prevPressedUIItemList.RemoveAt(f); f--; } } else if (currTouch.phase == TouchPhase.Ended) { prevPressedItem.CurrentOverUIItem(currPressedItem); prevPressedItem.UpdateTouch(currTouch); prevPressedItem.Release(); prevPressedUIItemList.RemoveAt(f); f--; } else { prevPressedItem.CurrentOverUIItem(currPressedItem); prevPressedItem.UpdateTouch(currTouch); } break; } } if(!wasPrevTouchFound) { prevPressedItem.CurrentOverUIItem(null); prevPressedItem.Release(); prevPressedUIItemList.RemoveAt(f); f--; } } } for (int f = 0; f < touchCounter; f++) { currPressedItem = pressedUIItems[f]; currTouch = allTouches[f]; if (currTouch.phase == TouchPhase.Began) { if (currPressedItem != null) { isNewlyPressed = currPressedItem.Press(currTouch); if (isNewlyPressed) { prevPressedUIItemList.Add(currPressedItem); } } isAnyPressBeganRecorded = true; } } if (isAnyPressBeganRecorded) { if (OnAnyPress != null) { OnAnyPress(); } } } tk2dUIItem RaycastForUIItem( Vector2 screenPos ) { int cameraCount = sortedCameras.Count; for (int i = 0; i < cameraCount; ++i) { tk2dUICamera currCamera = sortedCameras[i]; if (currCamera.RaycastType == tk2dUICamera.tk2dRaycastType.Physics3D) { #if !STRIP_PHYSICS_3D ray = currCamera.HostCamera.ScreenPointToRay( screenPos ); if (Physics.Raycast( ray, out hit, currCamera.HostCamera.farClipPlane - currCamera.HostCamera.nearClipPlane, currCamera.FilteredMask )) { return hit.collider.GetComponent<tk2dUIItem>(); } #endif } else if (currCamera.RaycastType == tk2dUICamera.tk2dRaycastType.Physics2D) { #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) #if !STRIP_PHYSICS_2D Collider2D collider = Physics2D.OverlapPoint(currCamera.HostCamera.ScreenToWorldPoint(screenPos), currCamera.FilteredMask); if (collider != null) { return collider.GetComponent<tk2dUIItem>(); } #endif #else Debug.LogError("Physics2D only supported in Unity 4.3 and above"); #endif } } return null; } public void OverrideClearAllChildrenPresses(tk2dUIItem item) { if (useMultiTouch) { tk2dUIItem tempUIItem; for (int n = 0; n < pressedUIItems.Length; n++) { tempUIItem = pressedUIItems[n]; if (tempUIItem!=null) { if (item.CheckIsUIItemChildOfMe(tempUIItem)) { tempUIItem.CurrentOverUIItem(item); } } } } else { if (pressedUIItem != null) { if (item.CheckIsUIItemChildOfMe(pressedUIItem)) { pressedUIItem.CurrentOverUIItem(item); } } } } }
using System; using System.Reflection; using System.Linq; using log4net; using Utilities; namespace Command { /// <summary> /// Base class of Command, Parameter, and Setting attributes. /// </summary> public abstract class VersionedAttribute : Attribute { /// Description of the command (mandatory) protected string _description; /// Holds the UDA(s) this item has been tagged with, as a | delimited /// string. protected string _uda; /// An alternate name (or alias) by which the item may also be /// referenced. Typically used for settings that may be singular or /// plural. public string Alias { get; set; } /// True if the setting has an alternate name public bool HasAlias { get { return Alias != null; } } /// Description of command or setting public string Description { get { return _description; } } /// Version in which the command was introduced public string Since { get; set; } /// Version in which the command was deprecated public string Deprecated { get; set; } /// Returns true if there is a Since or Deprecated attribute public bool IsVersioned { get { return Since != null || Deprecated != null; } } /// User-defined attribute; can be used to store additional information /// about the setting. public string Uda { get { return _uda; } set { if(_uda == null) { _uda = value; } else { _uda += "|" + value; } } } /// Constructor; forces description to be mandatory public VersionedAttribute(string desc) { _description = desc; } /// Checks if the setting is current for a specified version, based on /// the Since and/or Deprecated settings. public bool IsCurrent(Version version) { bool current = true; if(IsVersioned) { var from = Since != null ? Since.ToVersion() : null; var to = Deprecated != null ? Deprecated.ToVersion() : null; current = (from == null || version >= from) && (to == null || version < to); } return current; } /// <summary> /// Returns true if this setting is tagged with the specified user- /// defined attribute. /// </summary> public bool HasUda(string uda) { bool hasUda = false; if(_uda != null) { hasUda = _uda.Split('|').Contains(uda, StringComparer.OrdinalIgnoreCase); } return hasUda; } } /// <summary> /// Define an attribute which will be used to tag methods that can be /// invoked from a script or command file. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class CommandAttribute : VersionedAttribute { /// Name of the command; this is normally the same as the method that is /// decorated with this attribute public string Name { get; set; } /// Constructor public CommandAttribute(string desc) : base(desc) { } } /// </summary> /// Define an attribute that can be used to tag a method, property, or /// constructor as a source of new instances of the class returned by /// the member. This information will be used by Context objects to /// determine how to obtain objects of the required type when invoking a /// Command. /// </summary> [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false)] public class FactoryAttribute : Attribute { /// Flag indicating whether this Factory is the primary means for /// obtaining these objects, or an alternate public bool Alternate = false; /// Flag indicating whether factory object can be persisted in context /// and reused for other command invocations public bool SingleUse = false; } /// <summary> /// Abstract base class for Parameter and Setting attributes. /// </summary> public abstract class ValueAttribute : VersionedAttribute { /// The default value (if any) for this setting protected object _defaultValue = null; /// A flag indicating whether the attribute has a default value, since /// checking for null is not sufficient (the default value may be null). protected bool _hasDefaultValue = false; /// Whether the parameter has a DefaultValue (since the default may be null) public bool HasDefaultValue { get { return _hasDefaultValue; } } /// Default value for parameter public object DefaultValue { get { return _defaultValue; } set { _defaultValue = value; _hasDefaultValue = true; } } /// Whether the setting is a sensitive value that should not be logged public bool IsSensitive { get; set; } /// The constant part of the enum label that can be omitted public string EnumPrefix { get; set; } /// Constructor; forces description to be mandatory public ValueAttribute(string desc) : base(desc) { } } /// <summary> /// Define an attribute which will be used to specify command parameter /// information, such as default values, sensitive flags, enum prefixes, /// etc. /// </summary> /// <remarks> /// DefaultValues are captured through attributes instead of default values /// on the actual method parameters, since a) default parameter values are /// only available from v4 of .Net, and b) they have restrictions on where /// they can appear (only at the end of the list of parameters). /// </remarks> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public class ParameterAttribute : ValueAttribute { public ParameterAttribute(string desc) : base(desc) { } } /// <summary> /// Used to define the possible settings that can appear in an /// ISettingsCollection subclass. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class SettingAttribute : ValueAttribute, ISetting { /// Name of the setting public string Name { get; set; } /// The Type of value which the setting accepts public Type ParameterType { get; set; } /// Internal name of the setting public string InternalName { get; set; } /// Order setting should appear in (since attributes are returned in no particular order) public int Order { get; set; } /// SortKey, which is the Order prepended to the name public string SortKey { get { return string.Format("{0:D2}{1}", Order, Name); } } /// Constructor; name and description are mandatory, type defaults to /// boolean, default value to null (false) public SettingAttribute(string name, string desc) : base(desc) { Name = name; InternalName = name; ParameterType = typeof(bool); _hasDefaultValue = true; } } /// <summary> /// Used to define a single setting that has one or more dynamic names/values. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class DynamicSettingAttribute : SettingAttribute { /// Constructor; description is mandatory, type defaults to /// boolean, default value to null (false) public DynamicSettingAttribute(string label, string desc) : base("<" + label + ">", desc) { ParameterType = typeof(bool); _hasDefaultValue = true; } } }
//------------------------------------------------------------------------------ // <copyright file="IDeviceContext.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ //#define TRACK_HDC //#define GDI_FINALIZATION_WATCH #if WINFORMS_NAMESPACE namespace System.Windows.Forms.Internal #elif DRAWING_NAMESPACE namespace System.Drawing.Internal #else namespace System.Experimental.Gdi #endif { using System; using System.Collections; using System.Internal; using System.Security; using System.Runtime.InteropServices; using System.Diagnostics; using System.ComponentModel; using System.Drawing; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Versioning; /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext"]/*' /> /// <devdoc> /// Represents a Win32 device context. Provides operations for setting some of the properties /// of a device context. It's the managed wrapper for an HDC. /// /// This class is divided into two files separating the code that needs to be compiled into /// reatail builds and debugging code. /// </devdoc> #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY public #else internal #endif sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDisposable { /// <devdoc> /// This class is a wrapper to a Win32 device context, and the Hdc property is the way to get a /// handle to it. /// /// The hDc is released/deleted only when owned by the object, meaning it was created internally; /// in this case, the object is responsible for releasing/deleting it. /// In the case the object is created from an exisiting hdc, it is not released; this is consistent /// with the Win32 guideline that says if you call GetDC/CreateDC/CreatIC/CreateEnhMetafile, you are /// responsible for calling ReleaseDC/DeleteDC/DeleteEnhMetafile respectivelly. /// /// This class implements some of the operations commonly performed on the properties of a dc in [....], /// specially for interacting with GDI+, like clipping and coordinate transformation. /// Several properties are not persisted in the dc but instead they are set/reset during a more comprehensive /// operation like text rendering or painting; for instance text alignment is set and reset during DrawText (GDI), /// DrawString (GDI+). /// /// Other properties are persisted from operation to operation until they are reset, like clipping, /// one can make several calls to Graphics or WindowsGraphics obect after setting the dc clip area and /// before resetting it; these kinds of properties are the ones implemented in this class. /// This kind of properties place an extra chanllenge in the scenario where a DeviceContext is obtained /// from a Graphics object that has been used with GDI+, because GDI+ saves the hdc internally, rendering the /// DeviceContext underlying hdc out of [....]. DeviceContext needs to support these kind of properties to /// be able to keep the GDI+ and GDI HDCs in [....]. /// /// A few other persisting properties have been implemented in DeviceContext2, among them: /// 1. Window origin. /// 2. Bounding rectangle. /// 3. DC origin. /// 4. View port extent. /// 5. View port origin. /// 6. Window extent /// /// Other non-persisted properties just for information: Background/Forground color, Palette, Color adjustment, /// Color space, ICM mode and profile, Current pen position, Binary raster op (not supported by GDI+), /// Background mode, Logical Pen, DC pen color, ARc direction, Miter limit, Logical brush, DC brush color, /// Brush origin, Polygon filling mode, Bitmap stretching mode, Logical font, Intercharacter spacing, /// Font mapper flags, Text alignment, Test justification, Layout, Path, Meta region. /// See book "Windows Graphics Programming - Feng Yuang", P315 - Device Context Attributes. /// </devdoc> [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] IntPtr hDC; DeviceContextType dcType; public event EventHandler Disposing; bool disposed; // We cache the hWnd when creating the dc from one, to provide support forIDeviceContext.GetHdc/ReleaseHdc. // This hWnd could be null, in such case it is referring to the screen. [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] IntPtr hWnd = (IntPtr) (-1); // Unlikely to be a valid hWnd. IntPtr hInitialPen; IntPtr hInitialBrush; IntPtr hInitialBmp; IntPtr hInitialFont; IntPtr hCurrentPen; IntPtr hCurrentBrush; IntPtr hCurrentBmp; IntPtr hCurrentFont; Stack contextStack; #if GDI_FINALIZATION_WATCH private string AllocationSite = DbgUtil.StackTrace; private string DeAllocationSite = ""; #endif /// /// Class properties... /// /// <devdoc> /// Specifies whether a modification has been applied to the dc, like setting the clipping area or a coordinate transform. /// </devdoc> /// <devdoc> /// The device type the context refers to. /// </devdoc> public DeviceContextType DeviceContextType { get { return this.dcType; } } /// <devdoc> /// This object's hdc. If this property is called, then the object will be used as an HDC wrapper, /// so the hdc is cached and calls to GetHdc/ReleaseHdc won't PInvoke into GDI. /// Call Dispose to properly release the hdc. /// </devdoc> public IntPtr Hdc { [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] get { if( this.hDC == IntPtr.Zero ) { if( this.dcType == DeviceContextType.Display ) { Debug.Assert(!this.disposed, "Accessing a disposed DC, forcing recreation of HDC - this will generate a Handle leak!"); // Note: ReleaseDC must be called from the same thread. This applies only to HDC obtained // from calling GetDC. This means Display DeviceContext objects should never be finalized. this.hDC = ((IDeviceContext)this).GetHdc(); // this.hDC will be released on call to Dispose. CacheInitialState(); } #if GDI_FINALIZATION_WATCH else { try { Debug.WriteLine(string.Format("Allocation stack:\r\n{0}\r\nDeallocation stack:\r\n{1}", AllocationSite, DeAllocationSite)); } catch {} } #endif } Debug.Assert( this.hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + this.dcType ); return this.hDC; } } // VSWhidbey 536325 // Due to a problem with calling DeleteObject() on currently selected GDI objects, // we now track the initial set of objects when a DeviceContext is created. Then, // we also track which objects are currently selected in the DeviceContext. When // a currently selected object is disposed, it is first replaced in the DC and then // deleted. [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] private void CacheInitialState() { Debug.Assert(this.hDC != IntPtr.Zero, "Cannot get initial state without a valid HDC"); hCurrentPen = hInitialPen = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_PEN); hCurrentBrush = hInitialBrush = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BRUSH); hCurrentBmp = hInitialBmp = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_BITMAP); hCurrentFont = hInitialFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, hDC), IntNativeMethods.OBJ_FONT); } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public void DeleteObject(IntPtr handle, GdiObjectType type) { IntPtr handleToDelete = IntPtr.Zero; switch (type) { case GdiObjectType.Pen: if (handle == hCurrentPen) { IntPtr currentPen = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( this, hInitialPen)); Debug.Assert(currentPen == hCurrentPen, "DeviceContext thinks a different pen is selected than the HDC"); hCurrentPen = IntPtr.Zero; } handleToDelete = handle; break; case GdiObjectType.Brush: if (handle == hCurrentBrush) { IntPtr currentBrush = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( this, hInitialBrush)); Debug.Assert(currentBrush == hCurrentBrush, "DeviceContext thinks a different brush is selected than the HDC"); hCurrentBrush = IntPtr.Zero; } handleToDelete = handle; break; case GdiObjectType.Bitmap: if (handle == hCurrentBmp) { IntPtr currentBmp = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, this.Hdc), new HandleRef( this, hInitialBmp)); Debug.Assert(currentBmp == hCurrentBmp, "DeviceContext thinks a different brush is selected than the HDC"); hCurrentBmp = IntPtr.Zero; } handleToDelete = handle; break; } IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, handleToDelete)); } // // object construction API. Publicly constructable from static methods only. // /// <devdoc> /// Constructor to contruct a DeviceContext object from an window handle. /// </devdoc> private DeviceContext(IntPtr hWnd) { this.hWnd = hWnd; this.dcType = DeviceContextType.Display; DeviceContexts.AddDeviceContext(this); // the hDc will be created on demand. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "DeviceContext( hWnd=0x{0:x8} )", unchecked((int) hWnd)))); #endif } /// <devdoc> /// Constructor to contruct a DeviceContext object from an existing Win32 device context handle. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] private DeviceContext(IntPtr hDC, DeviceContextType dcType) { this.hDC = hDC; this.dcType = dcType; CacheInitialState(); DeviceContexts.AddDeviceContext(this); if( dcType == DeviceContextType.Display ) { this.hWnd = IntUnsafeNativeMethods.WindowFromDC( new HandleRef( this, this.hDC) ); } #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) )); #endif } // // /// <devdoc> /// CreateDC creates a DeviceContext object wrapping an hdc created with the Win32 CreateDC function. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public static DeviceContext CreateDC(string driverName, string deviceName, string fileName, HandleRef devMode) { // Note: All input params can be null but not at the same time. See MSDN for information. IntPtr hdc = IntUnsafeNativeMethods.CreateDC(driverName, deviceName, fileName, devMode); return new DeviceContext( hdc, DeviceContextType.NamedDevice ); } /// <devdoc> /// CreateIC creates a DeviceContext object wrapping an hdc created with the Win32 CreateIC function. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public static DeviceContext CreateIC(string driverName, string deviceName, string fileName, HandleRef devMode) { // Note: All input params can be null but not at the same time. See MSDN for information. IntPtr hdc = IntUnsafeNativeMethods.CreateIC(driverName, deviceName, fileName, devMode); return new DeviceContext( hdc, DeviceContextType.Information ); } /// <devdoc> /// Creates a DeviceContext object wrapping a memory DC compatible with the specified device. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public static DeviceContext FromCompatibleDC(IntPtr hdc) { // If hdc is null, the function creates a memory DC compatible with the application's current screen. // Win2K+: (See CreateCompatibleDC in the MSDN). // In this case the thread that calls CreateCompatibleDC owns the HDC that is created. When this thread is destroyed, // the HDC is no longer valid. IntPtr compatibleDc = IntUnsafeNativeMethods.CreateCompatibleDC( new HandleRef(null, hdc) ); return new DeviceContext(compatibleDc, DeviceContextType.Memory); } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.FromHdc"]/*' /> /// <devdoc> /// Used for wrapping an existing hdc. In this case, this object doesn't own the hdc /// so calls to GetHdc/ReleaseHdc don't PInvoke into GDI. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public static DeviceContext FromHdc(IntPtr hdc) { Debug.Assert( hdc != IntPtr.Zero, "hdc == 0" ); return new DeviceContext(hdc, DeviceContextType.Unknown); } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.FromHwnd"]/*' /> /// <devdoc> /// When hwnd is null, we are getting the screen DC. /// </devdoc> public static DeviceContext FromHwnd( IntPtr hwnd ) { return new DeviceContext(hwnd); } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.Finalize"]/*' /> ~DeviceContext() { Dispose(false); } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.Dispose"]/*' /> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.Dispose1"]/*' /> internal void Dispose(bool disposing) { if (disposed) { return; } if (this.Disposing != null) { this.Disposing(this, EventArgs.Empty); } this.disposed = true; #if !DRAWING_NAMESPACE DisposeFont(disposing); #endif switch( this.dcType ) { case DeviceContextType.Display: Debug.Assert( disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from." ); ((IDeviceContext)this).ReleaseHdc(); break; case DeviceContextType.Information: case DeviceContextType.NamedDevice: // CreateDC and CreateIC add an HDC handle to the HandleCollector; to remove it properly we need // to call DeleteHDC. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteHDC(hdc=0x{0:x8})", unchecked((int) this.hDC)))); #endif IntUnsafeNativeMethods.DeleteHDC(new HandleRef(this, this.hDC)); this.hDC = IntPtr.Zero; break; case DeviceContextType.Memory: // CreatCompatibleDC adds a GDI handle to HandleCollector, to remove it properly we need to call // DeleteDC. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteDC(hdc=0x{0:x8})", unchecked((int) this.hDC)))); #endif IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, this.hDC)); this.hDC = IntPtr.Zero; break; // case DeviceContextType.Metafile: - not yet supported. #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY case DeviceContextType.Metafile: IntUnsafeNativeMethods.CloseEnhMetaFile(new HandleRef(this, this.Hdc)); this.hDC = IntPtr.Zero; break; #endif case DeviceContextType.Unknown: default: return; // do nothing, the hdc is not owned by this object. // in this case it is ok if disposed throught finalization. } DbgUtil.AssertFinalization(this, disposing); } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.GetHdc"]/*' /> /// <devdoc> /// Explicit interface method implementation to hide them a bit for usability reasons so the object is seen /// as a wrapper around an hdc that is always available, and for performance reasons since it caches the hdc /// if used in this way. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] IntPtr IDeviceContext.GetHdc() { if (this.hDC == IntPtr.Zero) { Debug.Assert( this.dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device." ); // Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved. // For example, the default font is System. this.hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, this.hWnd)); #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked((int) this.hDC), unchecked((int) this.hWnd)))); #endif } return this.hDC; } /// <include file='doc\IDeviceContext.uex' path='docs/doc[@for="DeviceContext.ReleaseHdc"]/*' /> ///<devdoc> /// If the object was created from a DC, this object doesn't 'own' the dc so we just ignore /// this call. ///</devdoc> void IDeviceContext.ReleaseHdc() { if (this.hDC != IntPtr.Zero && this.dcType == DeviceContextType.Display) { #if TRACK_HDC int retVal = #endif IntUnsafeNativeMethods.ReleaseDC(new HandleRef(this, this.hWnd), new HandleRef(this, this.hDC)); // Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released. #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked((int) this.hDC), unchecked((int) this.hWnd)))); #endif this.hDC = IntPtr.Zero; } } /// <devdoc> /// Specifies whether the DC is in GM_ADVANCE mode (supported only in NT platforms). /// If false, it is in GM_COMPATIBLE mode. /// </devdoc> public DeviceContextGraphicsMode GraphicsMode { [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] get { return (DeviceContextGraphicsMode) IntUnsafeNativeMethods.GetGraphicsMode( new HandleRef( this, this.Hdc ) ); } #if WINFORMS_PUBLIC_GRAPHICS_LIBRARY set { SetGraphicsMode(value); } #endif } /// <devdoc> /// Sets the dc graphics mode and returns the old value. /// </devdoc> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public DeviceContextGraphicsMode SetGraphicsMode(DeviceContextGraphicsMode newMode) { return (DeviceContextGraphicsMode) IntUnsafeNativeMethods.SetGraphicsMode( new HandleRef( this, this.Hdc ), unchecked((int) newMode)); } /// <devdoc> /// Restores the device context to the specified state. The DC is restored by popping state information off a /// stack created by earlier calls to the SaveHdc function. /// The stack can contain the state information for several instances of the DC. If the state specified by the /// specified parameter is not at the top of the stack, RestoreDC deletes all state information between the top /// of the stack and the specified instance. /// Specifies the saved state to be restored. If this parameter is positive, nSavedDC represents a specific /// instance of the state to be restored. If this parameter is negative, nSavedDC represents an instance relative /// to the current state. For example, -1 restores the most recently saved state. /// See MSDN for more info. /// </devdoc> public void RestoreHdc() { #if TRACK_HDC bool result = #endif // Note: Don't use the Hdc property here, it would force handle creation. IntUnsafeNativeMethods.RestoreDC(new HandleRef(this, this.hDC), -1); #if TRACK_HDC // Note: [....] may call this method during app exit at which point the DC may have been finalized already causing this assert to popup. Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8}, state={2})", result, unchecked((int) this.hDC), restoreState) )); #endif Debug.Assert(contextStack != null, "Someone is calling RestoreHdc() before SaveHdc()"); if (contextStack != null) { GraphicsState g = (GraphicsState) contextStack.Pop(); hCurrentBmp = g.hBitmap; hCurrentBrush = g.hBrush; hCurrentPen = g.hPen; hCurrentFont = g.hFont; #if !DRAWING_NAMESPACE if (g.font != null && g.font.IsAlive) { selectedFont = g.font.Target as WindowsFont; } else { WindowsFont previousFont = selectedFont; selectedFont = null; if (previousFont != null && MeasurementDCInfo.IsMeasurementDC(this)) { previousFont.Dispose(); } } #endif } #if OPTIMIZED_MEASUREMENTDC // in this case, GDI will copy back the previously saved font into the DC. // we dont actually know what the font is in our measurement DC so // we need to clear it off. MeasurementDCInfo.ResetIfIsMeasurementDC(this.hDC); #endif } /// <devdoc> /// Saves the current state of the device context by copying data describing selected objects and graphic /// modes (such as the bitmap, brush, palette, font, pen, region, drawing mode, and mapping mode) to a /// context stack. /// The SaveDC function can be used any number of times to save any number of instances of the DC state. /// A saved state can be restored by using the RestoreHdc method. /// See MSDN for more details. /// </devdoc> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public int SaveHdc() { HandleRef hdc = new HandleRef( this, this.Hdc); int state = IntUnsafeNativeMethods.SaveDC(hdc); if (contextStack == null) { contextStack = new Stack(); } GraphicsState g = new GraphicsState(); g.hBitmap = hCurrentBmp; g.hBrush = hCurrentBrush; g.hPen = hCurrentPen; g.hFont = hCurrentFont; #if !DRAWING_NAMESPACE g.font = new WeakReference(selectedFont); #endif contextStack.Push(g); #if TRACK_HDC Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked((int) this.hDC)) )); #endif return state; } /// <devdoc> /// Selects a region as the current clipping region for the device context. /// Remarks (From MSDN): /// - Only a copy of the selected region is used. The region itself can be selected for any number of other device contexts or it can be deleted. /// - The SelectClipRgn function assumes that the coordinates for a region are specified in device units. /// - To remove a device-context's clipping region, specify a NULL region handle. /// </devdoc> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public void SetClip(WindowsRegion region) { HandleRef hdc = new HandleRef(this, this.Hdc); HandleRef hRegion = new HandleRef(region, region.HRegion); IntUnsafeNativeMethods.SelectClipRgn(hdc, hRegion); } ///<devdoc> /// Creates a new clipping region from the intersection of the current clipping region and /// the specified rectangle. ///</devdoc> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public void IntersectClip(WindowsRegion wr) { //if the incoming windowsregion is infinite, there is no need to do any intersecting. if (wr.HRegion == IntPtr.Zero) { return; } WindowsRegion clip = new WindowsRegion(0,0,0,0); try { int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef( this, this.Hdc), new HandleRef(clip, clip.HRegion)); // If the function succeeds and there is a clipping region for the given device context, the return value is 1. if (result == 1) { Debug.Assert(clip.HRegion != IntPtr.Zero); wr.CombineRegion(clip, wr, RegionCombineMode.AND); //1 = AND (or Intersect) } SetClip(wr); } finally { clip.Dispose(); } } /// <devdoc> /// Modifies the viewport origin for a device context using the specified horizontal and vertical offsets in logical units. /// </devdoc> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public void TranslateTransform(int dx, int dy) { IntNativeMethods.POINT orgn = new IntNativeMethods.POINT(); IntUnsafeNativeMethods.OffsetViewportOrgEx( new HandleRef( this, this.Hdc ), dx, dy, orgn ); } /// <summary> /// </summary> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public override bool Equals(object obj) { DeviceContext other = obj as DeviceContext; if (other == this) { return true; } if (other == null) { return false; } // Note: Use property instead of field so the HDC is initialized. Also, this avoid serialization issues (the obj could be a proxy that does not have access to private fields). return other.Hdc == this.Hdc; } /// <summary> /// This allows collections to treat DeviceContext objects wrapping the same HDC as the same objects. /// </summary> [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] public override int GetHashCode() { return this.Hdc.GetHashCode(); } internal class GraphicsState { internal IntPtr hBrush; internal IntPtr hFont; internal IntPtr hPen; internal IntPtr hBitmap; #if !DRAWING_NAMESPACE internal WeakReference font; #endif } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Collections; using NUnit.Framework; using NUnit.TestUtilities; namespace NUnit.Util.Tests { [TestFixture] public class VSProjectTests { private string invalidFile = "invalid.csproj"; private string resourceDir = "resources"; private void WriteInvalidFile( string text ) { StreamWriter writer = new StreamWriter( invalidFile ); writer.WriteLine( text ); writer.Close(); } [TearDown] public void EraseInvalidFile() { if ( File.Exists( invalidFile ) ) File.Delete( invalidFile ); } [Test] public void SolutionExtension() { Assert.IsTrue( VSProject.IsSolutionFile( TestPath( @"/x/y/project.sln" ) ) ); Assert.IsFalse( VSProject.IsSolutionFile( TestPath( @"/x/y/project.sol" ) ) ); } [Test] public void ProjectExtensions() { Assert.IsTrue( VSProject.IsProjectFile( TestPath( @"/x/y/project.csproj" ) ) ); Assert.IsTrue( VSProject.IsProjectFile( TestPath( @"/x/y/project.vbproj" ) ) ); Assert.IsTrue( VSProject.IsProjectFile( TestPath( @"/x/y/project.vcproj" ) ) ); Assert.IsFalse( VSProject.IsProjectFile( TestPath( @"/x/y/project.xyproj" ) ) ); } [Test] public void NotWebProject() { Assert.IsFalse(VSProject.IsProjectFile( @"http://localhost/web.csproj") ); Assert.IsFalse(VSProject.IsProjectFile( @"\MyProject\http://localhost/web.csproj") ); } private void AssertCanLoadProject( string resourceName ) { string fileName = Path.GetFileNameWithoutExtension( resourceName ); using( TempResourceFile file = new TempResourceFile( this.GetType(), resourceDir + "." + resourceName, resourceName ) ) { VSProject project = new VSProject( file.Path ); Assert.AreEqual( fileName, project.Name ); Assert.AreEqual( Path.GetFullPath( file.Path ), project.ProjectPath ); Assert.AreEqual( fileName.ToLower(), Path.GetFileNameWithoutExtension( project.Configs[0].Assemblies[0].ToString().ToLower() ) ); } } [Test] public void LoadCsharpProject() { AssertCanLoadProject( "csharp-sample.csproj" ); } [Test] public void LoadCsharpProjectVS2005() { AssertCanLoadProject( "csharp-sample_VS2005.csproj" ); } [Test] public void LoadVbProject() { AssertCanLoadProject( "vb-sample.vbproj" ); } [Test] public void LoadVbProjectVS2005() { AssertCanLoadProject( "vb-sample_VS2005.vbproj" ); } [Test] public void LoadJsharpProject() { AssertCanLoadProject( "jsharp.vjsproj" ); } [Test] public void LoadJsharpProjectVS2005() { AssertCanLoadProject( "jsharp_VS2005.vjsproj" ); } [Test] public void LoadCppProject() { AssertCanLoadProject( "cpp-sample.vcproj" ); } [Test] public void LoadCppProjectVS2005() { AssertCanLoadProject( "cpp-sample_VS2005.vcproj" ); } [Test] public void LoadProjectWithHebrewFileIncluded() { AssertCanLoadProject( "HebrewFileProblem.csproj" ); } [Test] public void LoadCppProjectWithMacros() { using ( TempResourceFile file = new TempResourceFile(this.GetType(), "resources.CPPLibrary.vcproj", "CPPLibrary.vcproj" )) { VSProject project = new VSProject(file.Path); Assert.AreEqual( "CPPLibrary", project.Name ); Assert.AreEqual( Path.GetFullPath(file.Path), project.ProjectPath); Assert.AreEqual( Path.GetFullPath( @"debug\cpplibrary.dll" ).ToLower(), project.Configs["Debug|Win32"].Assemblies[0].ToString().ToLower()); Assert.AreEqual( Path.GetFullPath( @"release\cpplibrary.dll" ).ToLower(), project.Configs["Release|Win32"].Assemblies[0].ToString().ToLower()); } } [Test] public void GenerateCorrectExtensionsFromVCProjectVS2005() { using (TempResourceFile file = new TempResourceFile(this.GetType(), "resources.cpp-default-library_VS2005.vcproj", "cpp-default-library_VS2005.vcproj")) { VSProject project = new VSProject(file.Path); Assert.AreEqual("cpp-default-library_VS2005", project.Name); Assert.AreEqual(Path.GetFullPath(file.Path), project.ProjectPath); Assert.AreEqual(Path.GetFullPath( TestPath( @"debug/cpp-default-library_VS2005.dll" ) ).ToLower(), project.Configs["Debug|Win32"].Assemblies[0].ToString().ToLower()); Assert.AreEqual(Path.GetFullPath( TestPath( @"release/cpp-default-library_VS2005.dll" ) ).ToLower(), project.Configs["Release|Win32"].Assemblies[0].ToString().ToLower()); } } [Test, ExpectedException( typeof ( ArgumentException ) ) ] public void LoadInvalidFileType() { new VSProject( @"/test.junk" ); } [Test, ExpectedException( typeof ( FileNotFoundException ) ) ] public void FileNotFoundError() { new VSProject( @"/junk.csproj" ); } [Test, ExpectedException( typeof( ArgumentException ) )] public void InvalidXmlFormat() { WriteInvalidFile( "<VisualStudioProject><junk></VisualStudioProject>" ); new VSProject( @"." + System.IO.Path.DirectorySeparatorChar + "invalid.csproj" ); } [Test, ExpectedException( typeof( ArgumentException ) )] public void InvalidProjectFormat() { WriteInvalidFile( "<VisualStudioProject><junk></junk></VisualStudioProject>" ); new VSProject( @"." + System.IO.Path.DirectorySeparatorChar + "invalid.csproj" ); } [Test, ExpectedException( typeof( ArgumentException ) )] public void MissingAttributes() { WriteInvalidFile( "<VisualStudioProject><CSharp><Build><Settings></Settings></Build></CSharp></VisualStudioProject>" ); new VSProject( @"." + System.IO.Path.DirectorySeparatorChar + "invalid.csproj" ); } [Test] public void NoConfigurations() { WriteInvalidFile( "<VisualStudioProject><CSharp><Build><Settings AssemblyName=\"invalid\" OutputType=\"Library\"></Settings></Build></CSharp></VisualStudioProject>" ); VSProject project = new VSProject( @"." + System.IO.Path.DirectorySeparatorChar + "invalid.csproj" ); Assert.AreEqual( 0, project.Configs.Count ); } /// <summary> /// Take a valid Linux path and make a valid windows path out of it /// if we are on Windows. Change slashes to backslashes and, if the /// path starts with a slash, add C: in front of it. /// </summary> private string TestPath(string path) { if (Path.DirectorySeparatorChar != '/') { path = path.Replace('/', Path.DirectorySeparatorChar); if (path[0] == Path.DirectorySeparatorChar) path = "C:" + path; } return path; } } }
using System; using System.Globalization; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using CoApp.Packaging.Common; using CoApp.VSE.Core.Packaging; using CoApp.VSE.Core.Utility; using VSLangProj; using Microsoft.Build.Evaluation; using Microsoft.Build.Construction; using Project = EnvDTE.Project; namespace CoApp.VSE.Core.Extensions { public static class ProjectExtensions { private static readonly HashSet<string> SupportedProjectTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { VsConstants.CsharpProjectTypeGuid, VsConstants.VbProjectTypeGuid, VsConstants.JsProjectTypeGuid, VsConstants.FsharpProjectTypeGuid, VsConstants.VcProjectTypeGuid }; public static string GetName(this Project project) { string name = project.Name; if (project.IsJavaScriptProject()) { const string suffix = " (loading...)"; if (name.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) { name = name.Substring(0, name.Length - suffix.Length); } } return name; } public static bool IsJavaScriptProject(this Project project) { return project != null && VsConstants.JsProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase); } public static string GetDirectory(this Project project) { return Path.GetDirectoryName(project.FullName); } public static bool IsVcProject(this Project project) { return project.Kind != null && project.Kind.Equals(VsConstants.VcProjectTypeGuid, StringComparison.OrdinalIgnoreCase); } public static bool IsNetProject(this Project project) { return project.IsSupported(); } public static bool IsSupported(this Project project) { return project.Kind != null && SupportedProjectTypes.Contains(project.Kind); } public static string GetTargetFramework(this Project project) { return project.AsMsBuildProject().GetPropertyValue("TargetFrameworkMoniker") ?? string.Empty; } public static double GetTargetFrameworkVersion(this Project project, string targetFramework = null) { targetFramework = targetFramework ?? project.GetTargetFramework(); var split = targetFramework.Split(','); var versionStr = split.Count() > 1 ? split[1].Trim().Substring(split[1].IndexOf('=') + 2) : string.Empty; double version; double.TryParse(versionStr, NumberStyles.Any, CultureInfo.InvariantCulture, out version); return version; } /// <summary> /// Checks if project is compatible with the package. /// </summary> public static bool IsCompatible(this Project project, IPackage package) { if (package == null) return true; var targetFramework = project.GetTargetFramework(); var targetFrameworkVersion = project.GetTargetFrameworkVersion(targetFramework); var targetsNetFramework = targetFramework.Contains(".NETFramework") || targetFramework.Contains("Silverlight"); // VC-compatibility var compatible = ((package.GetDeveloperLibraryType() == DeveloperLibraryType.VcInclude || (package.GetDeveloperLibraryType() == DeveloperLibraryType.VcLibrary && project.IsCompatibleArchitecture(package.Architecture))) && project.IsVcProject()); // NET-compatibility compatible = compatible || (package.GetDeveloperLibraryType() == DeveloperLibraryType.Net && project.IsNetProject() && ( (package.Flavor == "" && targetsNetFramework) || (package.Flavor == "[net20]" && (targetsNetFramework && targetFrameworkVersion >= 2.0)) || (package.Flavor == "[net35]" && (targetsNetFramework && targetFrameworkVersion >= 3.5)) || (package.Flavor == "[net40]" && (targetsNetFramework && targetFrameworkVersion >= 4.0)) || (package.Flavor == "[net45]" && (targetsNetFramework && targetFrameworkVersion >= 4.5)) || (package.Flavor == "[silverlight]" && targetsNetFramework) )); return compatible; } /// <summary> /// Checks if VC-project supports specified architecture. /// </summary> public static bool IsCompatibleArchitecture(this Project project, string architecture) { var configurations = project.GetCompatibleConfigurations(architecture); return configurations.Any(); } public static Microsoft.Build.Evaluation.Project AsMsBuildProject(this Project project) { return ProjectCollection.GlobalProjectCollection.GetLoadedProjects(project.FullName).FirstOrDefault() ?? ProjectCollection.GlobalProjectCollection.LoadProject(project.FullName); } /// <summary> /// Get compatible configurations of VC-project. E.g. Debug|Win32, Release|Win32, ... depending on architecture /// </summary> public static IEnumerable<string> GetCompatibleConfigurations(this Project project, string architecture) { var buildProject = project.AsMsBuildProject(); var result = new List<string>(); if (buildProject != null) { var xml = buildProject.Xml; var itemDefinitionGroups = xml.ItemDefinitionGroups; foreach (var itemDefinitionGroup in itemDefinitionGroups) { string condition = itemDefinitionGroup.Condition; string configuration = condition.Substring(33, condition.LastIndexOf("'", StringComparison.InvariantCulture) - 33); // 1. Platform string string platform = configuration.Split('|')[1].ToLowerInvariant(); // 2. TargetMachine definition var machine = project.GetDefinitionValue(configuration, "TargetMachine"); if (((platform == "win32" || platform == "x86") && architecture == "x86") || ((platform == "win64" || platform == "x64") && architecture == "x64") || machine.ToLowerInvariant().Contains(architecture)) { result.Add(configuration); } } } return result; } /// <summary> /// Get configurations of VC-project. E.g. Debug|Win32, Release|Win32, ... /// </summary> public static IEnumerable<string> GetConfigurations(this Project project) { var buildProject = project.AsMsBuildProject(); var result = new List<string>(); if (buildProject != null) { var xml = buildProject.Xml; var itemDefinitionGroups = xml.ItemDefinitionGroups; foreach (var itemDefinitionGroup in itemDefinitionGroups) { string condition = itemDefinitionGroup.Condition; result.Add(condition.Substring(33, condition.LastIndexOf("'", StringComparison.InvariantCulture) - 33)); } } return result; } /// <summary> /// Get definition in VC-project. /// </summary> private static string GetDefinitionValue(this Project project, string configuration, string elementName) { var buildProject = project.AsMsBuildProject(); if (buildProject != null) { foreach (var itemDefinitionGroup in buildProject.Xml.ItemDefinitionGroups) { if (itemDefinitionGroup.Condition.Contains(configuration)) { foreach (ProjectItemDefinitionElement element in itemDefinitionGroup.Children) { switch (element.ItemType) { case "ClCompile": case "Link": foreach (ProjectMetadataElement subElement in element.Children) { if (subElement.Name == elementName) { return subElement.Value; } } break; } } } } } return string.Empty; } /// <summary> /// Set definition in VC-project. /// </summary> private static void SetDefinitionValue(this Project project, string configuration, string elementName, string elementValue) { var buildProject = project.AsMsBuildProject(); if (buildProject != null) { foreach (var itemDefinitionGroup in buildProject.Xml.ItemDefinitionGroups) { if (itemDefinitionGroup.Condition.Contains(configuration)) { foreach (ProjectItemDefinitionElement element in itemDefinitionGroup.Children) { switch (element.ItemType) { case "ClCompile": case "Link": foreach (ProjectMetadataElement subElement in element.Children) { if (subElement.Name == elementName) { // subelement found subElement.Value = elementValue; return; } } break; } // subelement not found, create new if ((element.ItemType == "ClCompile" && elementName == "AdditionalIncludeDirectories") || (element.ItemType == "Link" && (elementName == "AdditionalLibraryDirectories" || elementName == "AdditionalDependencies"))) { element.AddMetadata(elementName, elementValue); } } } } } } private static IEnumerable<Tuple<ProjectItem, AssemblyName>> GetAssemblyReferences(this Microsoft.Build.Evaluation.Project project) { foreach (var referenceProjectItem in project.GetItems("Reference")) { AssemblyName assemblyName = null; try { assemblyName = new AssemblyName(referenceProjectItem.EvaluatedInclude); } catch { } // We can't yield from within the try so we do it out here if everything was successful if (assemblyName != null) { yield return Tuple.Create(referenceProjectItem, assemblyName); } } } /// <summary> /// Add or remove references in .NET-project. /// </summary> public static void ManageReferences(this Project project, PackageReference packageReference, IEnumerable<LibraryReference> libraries) { string path = string.Format(@"{0}\ReferenceAssemblies\{1}\{2}\{3}-{4}\", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), packageReference.CanonicalName.Flavor, packageReference.CanonicalName.Architecture, packageReference.CanonicalName.Name, packageReference.CanonicalName.Version); var buildProject = project.AsMsBuildProject(); var vsProject = (VSProject)project.Object; if (buildProject != null && vsProject != null) { foreach (var lib in libraries) { var assemblyName = Path.GetFileNameWithoutExtension(lib.Name); var assemblyPath = path + lib.Name; Reference reference = null; // Remove old references do { try { reference = vsProject.References.Find(assemblyName); } catch { } if (reference != null) { reference.Remove(); } } while (reference != null); // Add new reference if (lib.IsChecked) { vsProject.References.Add(assemblyPath); var references = buildProject.GetAssemblyReferences(); var referenceItem = references.First(n => n.Item2.Name == assemblyName).Item1; referenceItem.SetMetadataValue("HintPath", assemblyPath); } } } } /// <summary> /// Add or remove library directories and linker dependencies in VC-project. /// </summary> public static void ManageLinkerDefinitions(this Project project, PackageReference packageReference, IEnumerable<Project> projects, IEnumerable<LibraryReference> libraries) { var path = string.Format(@"{0}\lib\{1}\", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), packageReference.CanonicalName.Architecture); foreach (var configuration in project.GetConfigurations()) { var value = project.GetDefinitionValue(configuration, "AdditionalLibraryDirectories"); var paths = new HashSet<string>(value.Split(';')); if (projects.Any(n => n.FullName == project.FullName)) { paths.Add(path); } else { paths.Remove(path); } project.SetDefinitionValue(configuration, "AdditionalLibraryDirectories", string.Join(";", paths)); var configLibraries = libraries.Where(lib => lib.ConfigurationName == configuration); value = project.GetDefinitionValue(configuration, "AdditionalDependencies"); var current = value.Split(';'); var removed = configLibraries.Where(n => !n.IsChecked) .Select(n => Path.GetFileNameWithoutExtension(n.Name) + "-" + packageReference.CanonicalName.Version + ".lib"); var added = configLibraries.Where(n => n.IsChecked) .Select(n => Path.GetFileNameWithoutExtension(n.Name) + "-" + packageReference.CanonicalName.Version + ".lib"); var result = current.Except(removed) .Union(added); project.SetDefinitionValue(configuration, "AdditionalDependencies", string.Join(";", result)); } } /// <summary> /// Add or remove include directories in VC-project. /// </summary> public static void ManageIncludeDirectories(this Project project, PackageReference packageReference, IEnumerable<Project> projects) { var path = string.Format(@"{0}\include\{1}-{2}\", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), packageReference.CanonicalName.Name.Split('-')[0], packageReference.CanonicalName.Version); foreach (var configuration in project.GetConfigurations()) { var value = project.GetDefinitionValue(configuration, "AdditionalIncludeDirectories"); var paths = new HashSet<string>(value.Split(';')); if (projects.Any(n => n.FullName == project.FullName)) { paths.Add(path); } else { paths.Remove(path); } project.SetDefinitionValue(configuration, "AdditionalIncludeDirectories", string.Join(";", paths)); } } public static bool HasPackage(this Project project, IPackage package) { var packageReferenceFile = new PackageReferenceFile(project.GetDirectory() + "/coapp.packages.config"); return packageReferenceFile.FindEntry(package.CanonicalName, true) != null; } } }
// Copyright (c) 2017 Jan Pluskal // //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.ComponentModel.DataAnnotations.Schema; using System.Linq; using Newtonsoft.Json; namespace Netfox.Core.Database.PersistableJsonSeializable { /// <summary> /// Baseclass that allows persisting of scalar values as a collection (which is not supported by EF 4.3) /// </summary> /// <typeparam name="T">Type of the single collection entry that should be persisted.</typeparam> [ComplexType] public class PersistableJsonSerializableDictionary<TKey,Tvalue> : IDictionary<TKey, Tvalue> { /// <summary> /// The internal data container for the list data. /// </summary> private Dictionary<TKey, Tvalue> Data { get; set; } public PersistableJsonSerializableDictionary(Dictionary<TKey, Tvalue> initDictionary) { this.Data = initDictionary; } public PersistableJsonSerializableDictionary() { this.Data = new Dictionary<TKey, Tvalue>(); } public PersistableJsonSerializableDictionary(StringComparer ordinalIgnoreCase) { //if (typeof(string).IsAssignableFrom(typeof(TKey))) // this.Data = new Dictionary<string, Tvalue>(ordinalIgnoreCase); //else this.Data = new Dictionary<TKey, Tvalue>(); } /// <summary> /// DO NOT Modify manually! This is only used to store/load the data. /// </summary> public string SerializedValue { get { return JsonConvert.SerializeObject(this.Data); } set { this.Data.Clear(); if (string.IsNullOrEmpty(value)) { return; } this.Data = JsonConvert.DeserializeObject<Dictionary<TKey, Tvalue>>(value); } } //#region ICollection<T> Members //public void Add(T item) => this.Data.Add(item); //public void AddRange(IEnumerable<T> collection) => this.Data.AddRange(collection); //public void Clear() => this.Data.Clear(); //public bool Contains(T item) => this.Data.Contains(item); //public void CopyTo(T[] array, int arrayIndex) => this.Data.CopyTo(array, arrayIndex); //public int Count => this.Data.Count; //public bool IsReadOnly => false; //public bool Remove(T item) => this.Data.Remove(item); //#endregion //#region IEnumerable<T> Members //public IEnumerator<T> GetEnumerator() => this.Data.GetEnumerator(); //#endregion //#region IEnumerable Members //IEnumerator IEnumerable.GetEnumerator() => this.Data.GetEnumerator(); //#endregion //#region Implementation of IList<T> //public int IndexOf(T item) => this.Data.IndexOf(item); //public void Insert(int index, T item) => this.Data.Insert(index, item); //public void RemoveAt(int index) => this.Data.RemoveAt(index); //public T this[int index] //{ // get { return this.Data[index]; } // set { this.Data[index] = value; } //} //#endregion #region Implementation of IEnumerable /// <summary>Returns an enumerator that iterates through the collection.</summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> public IEnumerator<KeyValuePair<TKey, Tvalue>> GetEnumerator() => this.Data.GetEnumerator(); /// <summary>Returns an enumerator that iterates through a collection.</summary> /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Implementation of ICollection<KeyValuePair<Tkey,Tvalue>> /// <summary>Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.</summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</exception> public void Add(KeyValuePair<TKey, Tvalue> item) => this.Data.Add(item.Key,item.Value); /// <summary>Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.</summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. </exception> public void Clear() => this.Data.Clear(); /// <summary>Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.</summary> /// <returns>true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false.</returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> public bool Contains(KeyValuePair<TKey, Tvalue> item) => this.Data.Contains(item); /// <summary>Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.</summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array" /> is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="arrayIndex" /> is less than 0.</exception> /// <exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1" /> is greater than the available space from <paramref name="arrayIndex" /> to the end of the destination <paramref name="array" />.</exception> public void CopyTo(KeyValuePair<TKey, Tvalue>[] array, int arrayIndex) { throw new NotImplementedException(); } /// <summary>Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1" />.</summary> /// <returns>true if <paramref name="item" /> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />.</returns> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</exception> public bool Remove(KeyValuePair<TKey, Tvalue> item) => this.Data.Remove(item.Key); /// <summary>Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.</summary> /// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.</returns> public int Count => this.Data.Count; /// <summary>Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only.</summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false.</returns> public bool IsReadOnly => false; #endregion #region Implementation of IDictionary<Tkey,Tvalue> /// <summary>Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key.</summary> /// <returns>true if the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the key; otherwise, false.</returns> /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null.</exception> public bool ContainsKey(TKey key) => this.Data.ContainsKey(key); /// <summary>Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2" />.</summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null.</exception> /// <exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2" /> is read-only.</exception> public void Add(TKey key, Tvalue value) => this.Data.Add(key,value); /// <summary>Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2" />.</summary> /// <returns>true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key" /> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2" />.</returns> /// <param name="key">The key of the element to remove.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2" /> is read-only.</exception> public bool Remove(TKey key) => this.Data.Remove(key); /// <summary>Gets the value associated with the specified key.</summary> /// <returns>true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key; otherwise, false.</returns> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null.</exception> public bool TryGetValue(TKey key, out Tvalue value) => this.Data.TryGetValue(key,out value); /// <summary>Gets or sets the element with the specified key.</summary> /// <returns>The element with the specified key.</returns> /// <param name="key">The key of the element to get or set.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="key" /> is null.</exception> /// <exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="key" /> is not found.</exception> /// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2" /> is read-only.</exception> public Tvalue this[TKey key] { get { return this.Data[key]; } set { this.Data[key] = value; } } /// <summary>Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2" />.</summary> /// <returns>An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.</returns> public ICollection<TKey> Keys => this.Data.Keys; /// <summary>Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</summary> /// <returns>An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.</returns> public ICollection<Tvalue> Values => this.Data.Values; #endregion } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using VotingInfo.Database.Contracts; using VotingInfo.Database.Contracts.Auth; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace VotingInfo.Database.Logic.Auth { [Serializable] public abstract partial class UserLogicBase : LogicBase<UserLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<UserContract> Results; public UserLogicBase() { Results = new List<UserContract>(); } /// <summary> /// Run User_Insert. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>The new ID</returns> public virtual int? Insert(string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID ) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run User_Insert. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(UserContract row) { int? result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); result = (int?)cmd.ExecuteScalar(); row.UserId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(UserContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Auth].[User_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); result = (int?)cmd.ExecuteScalar(); row.UserId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<UserContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run User_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> public virtual int Update(int fldUserId , string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) , new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run User_Update. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldUserId , string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) , new SqlParameter("@UserName", fldUserName) , new SqlParameter("@Password", fldPassword) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@AuthToken", fldAuthToken) , new SqlParameter("@UserToken", fldUserToken) , new SqlParameter("@FailedLogins", fldFailedLogins) , new SqlParameter("@IsActive", fldIsActive) , new SqlParameter("@WINSID", fldWINSID) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(UserContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) , new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(UserContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) , new SqlParameter("@UserName", row.UserName) , new SqlParameter("@Password", row.Password) , new SqlParameter("@DisplayName", row.DisplayName) , new SqlParameter("@Email", row.Email) , new SqlParameter("@AuthToken", row.AuthToken) , new SqlParameter("@UserToken", row.UserToken) , new SqlParameter("@FailedLogins", row.FailedLogins) , new SqlParameter("@IsActive", row.IsActive) , new SqlParameter("@WINSID", row.WINSID) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<UserContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run User_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldUserId">Value for UserId</param> public virtual int Delete(int fldUserId ) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run User_Delete. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldUserId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(UserContract row) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(UserContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[User_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", row.UserId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<UserContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldUserId ) { bool result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldUserId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run User_Search, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of UserRow.</returns> public virtual bool Search(string fldUserName , string fldDisplayName , string fldEmail , string fldWINSID ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_Search, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool Search(string fldUserName , string fldDisplayName , string fldEmail , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) , new SqlParameter("@DisplayName", fldDisplayName) , new SqlParameter("@Email", fldEmail) , new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectAll, and return results as a list of UserRow. /// </summary> /// <returns>A collection of UserRow.</returns> public virtual bool SelectAll() { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectAll, and return results as a list of UserRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_List, and return results as a list. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldUserName ) { List<ListItemContract> result = null; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_List]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) result = ListItemLogic.ReadAllNow(r); } }); return result; } /// <summary> /// Run User_List, and return results as a list. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public virtual List<ListItemContract> List(string fldUserName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_List]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) return ListItemLogic.ReadAllNow(r); } } /// <summary> /// Run User_SelectBy_UserId, and return results as a list of UserRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserId(int fldUserId ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_UserId, and return results as a list of UserRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserId(int fldUserId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserId", fldUserId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_UserName, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserName(string fldUserName ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserName]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_UserName, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserName(string fldUserName , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserName]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserName", fldUserName) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_Email, and return results as a list of UserRow. /// </summary> /// <param name="fldEmail">Value for Email</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_Email(string fldEmail ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_Email]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@Email", fldEmail) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_Email, and return results as a list of UserRow. /// </summary> /// <param name="fldEmail">Value for Email</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_Email(string fldEmail , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_Email]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@Email", fldEmail) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_UserToken, and return results as a list of UserRow. /// </summary> /// <param name="fldUserToken">Value for UserToken</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserToken(Guid fldUserToken ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserToken]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserToken", fldUserToken) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_UserToken, and return results as a list of UserRow. /// </summary> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_UserToken(Guid fldUserToken , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_UserToken]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@UserToken", fldUserToken) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run User_SelectBy_WINSID, and return results as a list of UserRow. /// </summary> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_WINSID(string fldWINSID ) { var result = false; VotingInfoDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_WINSID]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run User_SelectBy_WINSID, and return results as a list of UserRow. /// </summary> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public virtual bool SelectBy_WINSID(string fldWINSID , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[User_SelectBy_WINSID]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@WINSID", fldWINSID) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new UserContract { UserId = reader.GetInt32(0), UserName = reader.GetString(1), Password = (byte[])reader.GetValue(2), DisplayName = reader.GetString(3), Email = reader.GetString(4), AuthToken = reader.GetGuid(5), UserToken = reader.GetGuid(6), FailedLogins = reader.GetInt32(7), IsActive = reader.GetBoolean(8), WINSID = reader.IsDBNull(9) ? null : reader.GetString(9), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(UserContract row) { if(row == null) return 0; if(row.UserId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(UserContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.UserId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<UserContract> rows) { var rowCount = 0; VotingInfoDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection.PortableExecutable; using System.Text; namespace R2RDump { /// <summary> /// Represents the debug information for a single method in the ready-to-run image. /// See <a href="https://github.com/dotnet/coreclr/blob/master/src/inc/cordebuginfo.h">src\inc\cordebuginfo.h</a> for /// the fundamental types this is based on. /// </summary> public class DebugInfo { private List<DebugInfoBoundsEntry> _boundsList = new List<DebugInfoBoundsEntry>(); private List<NativeVarInfo> _variablesList = new List<NativeVarInfo>(); private Machine _machine; private bool _normalize; public DebugInfo(byte[] image, int offset, Machine machine, bool normalize) { _machine = machine; _normalize = normalize; // Get the id of the runtime function from the NativeArray uint lookback = 0; uint debugInfoOffset = NativeReader.DecodeUnsigned(image, (uint)offset, ref lookback); if (lookback != 0) { System.Diagnostics.Debug.Assert(0 < lookback && lookback < offset); debugInfoOffset = (uint)offset - lookback; } NibbleReader reader = new NibbleReader(image, (int)debugInfoOffset); uint boundsByteCount = reader.ReadUInt(); uint variablesByteCount = reader.ReadUInt(); int boundsOffset = reader.GetNextByteOffset(); int variablesOffset = (int)(boundsOffset + boundsByteCount); if (boundsByteCount > 0) { ParseBounds(image, boundsOffset); } if (variablesByteCount > 0) { ParseNativeVarInfo(image, variablesOffset); } } public void WriteTo(TextWriter writer, DumpOptions dumpOptions) { if (_boundsList.Count > 0) writer.WriteLine("Debug Info"); writer.WriteLine("\tBounds:"); for (int i = 0; i < _boundsList.Count; ++i) { writer.Write('\t'); if (!dumpOptions.Naked) { writer.Write($"Native Offset: 0x{_boundsList[i].NativeOffset:X}, "); } writer.WriteLine($"IL Offset: 0x{_boundsList[i].ILOffset:X}, Source Types: {_boundsList[i].SourceTypes}"); } writer.WriteLine(""); if (_variablesList.Count > 0) writer.WriteLine("\tVariable Locations:"); for (int i = 0; i < _variablesList.Count; ++i) { var varLoc = _variablesList[i]; writer.WriteLine($"\tVariable Number: {varLoc.VariableNumber}"); writer.WriteLine($"\tStart Offset: 0x{varLoc.StartOffset:X}"); writer.WriteLine($"\tEnd Offset: 0x{varLoc.EndOffset:X}"); writer.WriteLine($"\tLoc Type: {varLoc.VariableLocation.VarLocType}"); switch (varLoc.VariableLocation.VarLocType) { case VarLocType.VLT_REG: case VarLocType.VLT_REG_FP: case VarLocType.VLT_REG_BYREF: writer.WriteLine($"\tRegister: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); break; case VarLocType.VLT_STK: case VarLocType.VLT_STK_BYREF: writer.WriteLine($"\tBase Register: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); writer.WriteLine($"\tStack Offset: {varLoc.VariableLocation.Data2}"); break; case VarLocType.VLT_REG_REG: writer.WriteLine($"\tRegister 1: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); writer.WriteLine($"\tRegister 2: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data2)}"); break; case VarLocType.VLT_REG_STK: writer.WriteLine($"\tRegister: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); writer.WriteLine($"\tBase Register: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data2)}"); writer.WriteLine($"\tStack Offset: {varLoc.VariableLocation.Data3}"); break; case VarLocType.VLT_STK_REG: writer.WriteLine($"\tStack Offset: {varLoc.VariableLocation.Data1}"); writer.WriteLine($"\tBase Register: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data2)}"); writer.WriteLine($"\tRegister: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data3)}"); break; case VarLocType.VLT_STK2: writer.WriteLine($"\tBase Register: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); writer.WriteLine($"\tStack Offset: {varLoc.VariableLocation.Data2}"); break; case VarLocType.VLT_FPSTK: writer.WriteLine($"\tOffset: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); break; case VarLocType.VLT_FIXED_VA: writer.WriteLine($"\tOffset: {GetPlatformSpecificRegister(_machine, varLoc.VariableLocation.Data1)}"); break; default: throw new BadImageFormatException("Unexpected var loc type"); } writer.WriteLine(""); } } /// <summary> /// Convert a register number in debug info into a machine-specific register /// </summary> private static string GetPlatformSpecificRegister(Machine machine, int regnum) { switch (machine) { case Machine.I386: return ((x86.Registers)regnum).ToString(); case Machine.Amd64: return ((Amd64.Registers)regnum).ToString(); case Machine.Arm: return ((Arm.Registers)regnum).ToString(); case Machine.Arm64: return ((Arm64.Registers)regnum).ToString(); default: throw new NotImplementedException($"No implementation for machine type {machine}."); } } private void ParseBounds(byte[] image, int offset) { // Bounds info contains (Native Offset, IL Offset, flags) // - Sorted by native offset (so use a delta encoding for that). // - IL offsets aren't sorted, but they should be close to each other (so a signed delta encoding) // They may also include a sentinel value from MappingTypes. // - flags is 3 indepedent bits. NibbleReader reader = new NibbleReader(image, offset); uint boundsEntryCount = reader.ReadUInt(); Debug.Assert(boundsEntryCount > 0); uint previousNativeOffset = 0; for (int i = 0; i < boundsEntryCount; ++i) { var entry = new DebugInfoBoundsEntry(); previousNativeOffset += reader.ReadUInt(); entry.NativeOffset = previousNativeOffset; entry.ILOffset = (uint)(reader.ReadUInt() + (int)MappingTypes.MaxMappingValue); entry.SourceTypes = (SourceTypes)reader.ReadUInt(); _boundsList.Add(entry); } } private void ParseNativeVarInfo(byte[] image, int offset) { // Each Varinfo has a: // - native start +End offset. We can use a delta for the end offset. // - Il variable number. These are usually small. // - VarLoc information. This is a tagged variant. // The entries aren't sorted in any particular order. NibbleReader reader = new NibbleReader(image, offset); uint nativeVarCount = reader.ReadUInt(); for (int i = 0; i < nativeVarCount; ++i) { var entry = new NativeVarInfo(); entry.StartOffset = reader.ReadUInt(); entry.EndOffset = entry.StartOffset + reader.ReadUInt(); entry.VariableNumber = (uint)(reader.ReadUInt() + (int)ImplicitILArguments.Max); var varLoc = new VarLoc(); varLoc.VarLocType = (VarLocType)reader.ReadUInt(); switch (varLoc.VarLocType) { case VarLocType.VLT_REG: case VarLocType.VLT_REG_FP: case VarLocType.VLT_REG_BYREF: varLoc.Data1 = (int)reader.ReadUInt(); break; case VarLocType.VLT_STK: case VarLocType.VLT_STK_BYREF: varLoc.Data1 = (int)reader.ReadUInt(); varLoc.Data2 = ReadEncodedStackOffset(reader); break; case VarLocType.VLT_REG_REG: varLoc.Data1 = (int)reader.ReadUInt(); varLoc.Data2 = (int)reader.ReadUInt(); break; case VarLocType.VLT_REG_STK: varLoc.Data1 = (int)reader.ReadUInt(); varLoc.Data2 = (int)reader.ReadUInt(); varLoc.Data3 = ReadEncodedStackOffset(reader); break; case VarLocType.VLT_STK_REG: varLoc.Data1 = ReadEncodedStackOffset(reader); varLoc.Data2 = (int)reader.ReadUInt(); varLoc.Data3 = (int)reader.ReadUInt(); break; case VarLocType.VLT_STK2: varLoc.Data1 = (int)reader.ReadUInt(); varLoc.Data2 = ReadEncodedStackOffset(reader); break; case VarLocType.VLT_FPSTK: varLoc.Data1 = (int)reader.ReadUInt(); break; case VarLocType.VLT_FIXED_VA: varLoc.Data1 = (int)reader.ReadUInt(); break; default: throw new BadImageFormatException("Unexpected var loc type"); } entry.VariableLocation = varLoc; _variablesList.Add(entry); } if (_normalize) { _variablesList.Sort(CompareNativeVarInfo); } } private static int CompareNativeVarInfo(NativeVarInfo left, NativeVarInfo right) { if (left.VariableNumber < right.VariableNumber) { return -1; } else if (left.VariableNumber > right.VariableNumber) { return 1; } else if (left.StartOffset < right.StartOffset) { return -1; } else if (left.StartOffset > right.StartOffset) { return 1; } else { return 0; } } private int ReadEncodedStackOffset(NibbleReader reader) { int offset = reader.ReadInt(); if (_machine == Machine.I386) { offset *= 4; // sizeof(DWORD) } return offset; } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Reflection; using System.Threading; namespace System.Web.Routing { /// <summary> /// RouteCollectionExtensions /// </summary> public static class RouteCollectionExtensions { /// <summary> /// Ignores the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="urls">The urls.</param> public static void IgnoreRouteEx(this RouteCollection routes, string[] urls) { foreach (var url in urls) routes.IgnoreRouteEx(url, null); } /// <summary> /// Ignores the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="urls">The urls.</param> /// <param name="constraints">The constraints.</param> public static void IgnoreRouteEx(this RouteCollection routes, string[] urls, object constraints) { foreach (var url in urls) routes.IgnoreRouteEx(url, constraints); } /// <summary> /// Ignores the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="url">The URL.</param> public static void IgnoreRouteEx(this RouteCollection routes, string url) { routes.IgnoreRouteEx(url, null); } /// <summary> /// Ignores the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="url">The URL.</param> /// <param name="constraints">The constraints.</param> public static void IgnoreRouteEx(this RouteCollection routes, string url, object constraints) { if (routes == null) throw new ArgumentNullException("routes"); if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url"); routes.Add(new IgnoreRouteExInternal(url) { Constraints = new RouteValueDictionary(constraints) }); } /// <summary> /// Throws the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="exception">The exception.</param> /// <param name="urls">The urls.</param> public static void ThrowRouteEx(this RouteCollection routes, Exception exception, string[] urls) { foreach (var url in urls) routes.ThrowRouteEx(exception, url, null); } /// <summary> /// Throws the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="exception">The exception.</param> /// <param name="urls">The urls.</param> /// <param name="constraints">The constraints.</param> public static void ThrowRouteEx(this RouteCollection routes, Exception exception, string[] urls, object constraints) { foreach (var url in urls) routes.ThrowRouteEx(exception, url, constraints); } /// <summary> /// Throws the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="exception">The exception.</param> /// <param name="url">The URL.</param> public static void ThrowRouteEx(this RouteCollection routes, Exception exception, string url) { routes.ThrowRouteEx(exception, url, null); } /// <summary> /// Throws the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="exception">The exception.</param> /// <param name="url">The URL.</param> /// <param name="constraints">The constraints.</param> public static void ThrowRouteEx(this RouteCollection routes, Exception exception, string url, object constraints) { if (routes == null) throw new ArgumentNullException("routes"); if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url"); routes.Add(new ThrowRouteExInternal(url, exception) { Constraints = new RouteValueDictionary(constraints) }); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="aliases">The aliases.</param> /// <param name="url">The URL.</param> public static void AliasRouteEx(this RouteCollection routes, string[] aliases, string url) { foreach (var alias in aliases) routes.AliasRouteEx(alias, url, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="aliases">The aliases.</param> /// <param name="url">The URL.</param> /// <param name="aliasConstraints">The alias constraints.</param> public static void AliasRouteEx(this RouteCollection routes, string[] aliases, string url, object aliasConstraints) { foreach (var alias in aliases) routes.AliasRouteEx(alias, url, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="alias">The alias.</param> /// <param name="url">The URL.</param> public static void AliasRouteEx(this RouteCollection routes, string alias, string url) { routes.AliasRouteEx(alias, url, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="alias">The alias.</param> /// <param name="url">The URL.</param> /// <param name="aliasConstraints">The alias constraints.</param> public static void AliasRouteEx(this RouteCollection routes, string alias, string url, object aliasConstraints) { routes.AliasRouteEx(alias, url, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="alias">The alias.</param> /// <param name="url">The URL.</param> /// <param name="aliasConstraints">The alias constraints.</param> /// <param name="routeDataJoiner">The route data joiner.</param> public static void AliasRouteEx(this RouteCollection routes, string alias, string url, object aliasConstraints, Func<RouteData, RouteData, RouteData> routeDataJoiner) { if (routes == null) throw new ArgumentNullException("routes"); if (alias == null) throw new ArgumentNullException("alias"); if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url"); if (routeDataJoiner == null) throw new ArgumentNullException("routeDataJoiner"); #if CLR4 EnsureRouteCollectionReaderWriterLock(routes); #endif routes.Add(new AliasRouteExInternal(alias, () => routes.FindRouteDataByUrl(HttpContext.Current, url), routeDataJoiner) { Constraints = new RouteValueDictionary(aliasConstraints) }); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="aliases">The aliases.</param> /// <param name="routeData">The route data.</param> public static void AliasRouteEx(this RouteCollection routes, string[] aliases, RouteData routeData) { foreach (var alias in aliases) routes.AliasRouteEx(alias, routeData, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="aliases">The aliases.</param> /// <param name="routeData">The route data.</param> /// <param name="aliasConstraints">The alias constraints.</param> public static void AliasRouteEx(this RouteCollection routes, string[] aliases, RouteData routeData, object aliasConstraints) { foreach (var alias in aliases) routes.AliasRouteEx(alias, routeData, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="alias">The alias.</param> /// <param name="routeData">The route data.</param> public static void AliasRouteEx(this RouteCollection routes, string alias, RouteData routeData) { routes.AliasRouteEx(alias, routeData, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="alias">The alias.</param> /// <param name="routeData">The route data.</param> /// <param name="aliasConstraints">The alias constraints.</param> public static void AliasRouteEx(this RouteCollection routes, string alias, RouteData routeData, object aliasConstraints) { routes.AliasRouteEx(alias, routeData, null, (left, right) => left); } /// <summary> /// Aliases the route ex. /// </summary> /// <param name="routes">The routes.</param> /// <param name="alias">The alias.</param> /// <param name="routeData">The route data.</param> /// <param name="aliasConstraints">The alias constraints.</param> /// <param name="routeDataJoiner">The route data joiner.</param> public static void AliasRouteEx(this RouteCollection routes, string alias, RouteData routeData, object aliasConstraints, Func<RouteData, RouteData, RouteData> routeDataJoiner) { if (routes == null) throw new ArgumentNullException("routes"); if (string.IsNullOrEmpty(alias)) throw new ArgumentNullException("alias"); if (routeData == null) throw new ArgumentNullException("routeData"); if (routeDataJoiner == null) throw new ArgumentNullException("routeDataJoiner"); #if CLR4 EnsureRouteCollectionReaderWriterLock(routes); #endif routes.Add(new AliasRouteExInternal(alias, () => routeData, routeDataJoiner) { Constraints = new RouteValueDictionary(aliasConstraints) }); } #if CLR4 private readonly static FieldInfo _rwLockField = typeof(RouteCollection).GetField("_rwLock", BindingFlags.NonPublic | BindingFlags.Instance); private readonly static FieldInfo _fIsReentrantField = typeof(ReaderWriterLockSlim).GetField("fIsReentrant", BindingFlags.NonPublic | BindingFlags.Instance); private static void EnsureRouteCollectionReaderWriterLock(RouteCollection routes) { var rwLock = (ReaderWriterLockSlim)_rwLockField.GetValue(routes); if (rwLock.RecursionPolicy != LockRecursionPolicy.SupportsRecursion) _fIsReentrantField.SetValue(rwLock, true); } #endif #region Internal-Routes private sealed class IgnoreRouteExInternal : Route { public IgnoreRouteExInternal(string url) : base(url, new StopRoutingHandler()) { } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary routeValues) { return null; } } private sealed class AliasRouteExInternal : Route { private Func<RouteData> _routeDataFinder; private Func<RouteData, RouteData, RouteData> _routeDataJoiner; public AliasRouteExInternal(string alias, Func<RouteData> routeDataFinder, Func<RouteData, RouteData, RouteData> routeDataJoiner) : base(alias, null) { _routeDataFinder = routeDataFinder; _routeDataJoiner = routeDataJoiner; } public override RouteData GetRouteData(HttpContextBase httpContext) { var aliasRouteData = base.GetRouteData(httpContext); if (aliasRouteData == null) return null; var routeData = _routeDataFinder(); return (routeData != null ? _routeDataJoiner(routeData, aliasRouteData) : null); } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return null; // base.GetVirtualPath(requestContext, values); } } private sealed class ThrowRouteExInternal : Route { public ThrowRouteExInternal(string url, Exception exception) : base(url, new ThrowRouteExHandlerInternal(exception)) { } public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary routeValues) { return null; } } private sealed class ThrowRouteExHandlerInternal : IRouteHandler { private Exception _exception; public ThrowRouteExHandlerInternal(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); _exception = exception; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { throw _exception; } } #endregion #region Find Route-Data /// <summary> /// Finds the route data by URL. /// </summary> /// <param name="routes">The routes.</param> /// <param name="httpContext">The HTTP context.</param> /// <param name="url">The URL.</param> /// <returns></returns> public static RouteData FindRouteDataByUrl(this RouteCollection routes, HttpContext httpContext, string url) { if (routes == null) throw new ArgumentNullException("routes"); if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url"); var injectedHttpContext = new HttpContextInjector(httpContext, new HttpRequestInjector(httpContext.Request, url)); return routes.GetRouteData(injectedHttpContext); } private sealed class HttpContextInjector : HttpContextWrapper { private HttpRequestBase _request; public HttpContextInjector(HttpContext httpContext, HttpRequestBase request) : base(httpContext) { _request = request; } public override HttpRequestBase Request { get { return _request; } } } private sealed class HttpRequestInjector : HttpRequestWrapper { private string _appRelativeCurrentExecutionFilePath; public HttpRequestInjector(HttpRequest httpRequest, string appRelativeCurrentExecutionFilePath) : base(httpRequest) { _appRelativeCurrentExecutionFilePath = appRelativeCurrentExecutionFilePath; } public override string AppRelativeCurrentExecutionFilePath { get { return _appRelativeCurrentExecutionFilePath; } } } #endregion } }
// Copyright (c) The Mapsui authors. // The Mapsui authors licensed this file under the MIT license. // See the LICENSE file in the project root for full license information. // This file was originally created by Morten Nielsen (www.iter.dk) as part of SharpMap using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Mapsui.Layers; using Mapsui.Nts.Extensions; using Mapsui.Nts.Providers.Shapefile.Indexing; using Mapsui.Providers; using NetTopologySuite.Geometries; namespace Mapsui.Nts.Providers.Shapefile { /// <summary> /// Shapefile geometry type. /// </summary> public enum ShapeType { /// <summary> /// Null shape with no geometric data /// </summary> Null = 0, /// <summary> /// A point consists of a pair of double-precision coordinates. /// Mapsui interprets this as <see cref="Point"/> /// </summary> Point = 1, /// <summary> /// PolyLine is an ordered set of coordinates that consists of one or more parts. A part is a /// connected sequence of two or more points. Parts may or may not be connected to one /// another. Parts may or may not intersect one another. /// Mapsui interprets this as either <see cref="LineString"/> or <see cref="MultiLineString"/> /// </summary> PolyLine = 3, /// <summary> /// A polygon consists of one or more rings. A ring is a connected sequence of four or more /// points that form a closed, non-self-intersecting loop. A polygon may contain multiple /// outer rings. The order of coordinates or orientation for a ring indicates which side of the ring /// is the interior of the polygon. The neighborhood to the right of an observer walking along /// the ring in vertex order is the neighborhood inside the polygon. Coordinates of rings defining /// holes in polygons are in a counterclockwise direction. Vertices for a single, ringed /// polygon are, therefore, always in clockwise order. The rings of a polygon are referred to /// as its parts. /// Mapsui interprets this as either <see cref="Polygon"/> or <see cref="MultiPolygon"/> /// </summary> Polygon = 5, /// <summary> /// A MultiPoint represents a set of points. /// Mapsui interprets this as <see cref="MultiPoint"/> /// </summary> Multipoint = 8, /// <summary> /// A PointZ consists of a triplet of double-precision coordinates plus a measure. /// Mapsui interprets this as <see cref="Point"/> /// </summary> PointZ = 11, /// <summary> /// A PolyLineZ consists of one or more parts. A part is a connected sequence of two or /// more points. Parts may or may not be connected to one another. Parts may or may not /// intersect one another. /// Mapsui interprets this as <see cref="LineString"/> or <see cref="MultiLineString"/> /// </summary> PolyLineZ = 13, /// <summary> /// A PolygonZ consists of a number of rings. A ring is a closed, non-self-intersecting loop. /// A PolygonZ may contain multiple outer rings. The rings of a PolygonZ are referred to as /// its parts. /// Mapsui interprets this as either <see cref="Polygon"/> or <see cref="MultiPolygon"/> /// </summary> PolygonZ = 15, /// <summary> /// A MultiPointZ represents a set of <see cref="PointZ"/>s. /// Mapsui interprets this as <see cref="MultiPoint"/> /// </summary> MultiPointZ = 18, /// <summary> /// A PointM consists of a pair of double-precision coordinates in the order X, Y, plus a measure M. /// Mapsui interprets this as <see cref="Point"/> /// </summary> PointM = 21, /// <summary> /// A shapefile PolyLineM consists of one or more parts. A part is a connected sequence of /// two or more points. Parts may or may not be connected to one another. Parts may or may /// not intersect one another. /// Mapsui interprets this as <see cref="LineString"/> or <see cref="MultiLineString"/> /// </summary> PolyLineM = 23, /// <summary> /// A PolygonM consists of a number of rings. A ring is a closed, non-self-intersecting loop. /// Mapsui interprets this as either <see cref="Polygon"/> or <see cref="MultiPolygon"/> /// </summary> PolygonM = 25, /// <summary> /// A MultiPointM represents a set of <see cref="PointM"/>s. /// Mapsui interprets this as <see cref="MultiPoint"/> /// </summary> MultiPointM = 28, /// <summary> /// A MultiPatch consists of a number of surface patches. Each surface patch describes a /// surface. The surface patches of a MultiPatch are referred to as its parts, and the type of /// part controls how the order of coordinates of an MultiPatch part is interpreted. /// Mapsui doesn't support this feature type. /// </summary> MultiPatch = 31 }; /// <summary> /// Shapefile data provider /// </summary> /// <remarks> /// <para>The ShapeFile provider is used for accessing ESRI ShapeFiles. The ShapeFile should at least contain the /// [filename].shp, [filename].idx, and if feature-data is to be used, also [filename].dbf file.</para> /// <para>The first time the ShapeFile is accessed, Mapsui will automatically create a spatial index /// of the shp-file, and save it as [filename].shp.sidx. If you change or update the contents of the .shp file, /// delete the .sidx file to force Mapsui to rebuilt it. In web applications, the index will automatically /// be cached to memory for faster access, so to reload the index, you will need to restart the web application /// as well.</para> /// <para> /// M and Z values in a shapefile is ignored by Mapsui. /// </para> /// </remarks> public class ShapeFile : IProvider<GeometryFeature>, IDisposable { /// <summary> /// Filter Delegate Method /// </summary> /// <remarks> /// The FilterMethod delegate is used for applying a method that filters data from the data set. /// The method should return 'true' if the feature should be included and false if not. /// </remarks> /// <returns>true if this feature should be included, false if it should be filtered</returns> public delegate bool FilterMethod(IFeature dr); private MRect? _envelope; private int _featureCount; private readonly bool _fileBasedIndex; private string _filename; private bool _isOpen; private ShapeType _shapeType; private BinaryReader? _brShapeFile; private BinaryReader? _brShapeIndex; private readonly DbaseReader? _dbaseFile; private FileStream? _fsShapeFile; private FileStream? _fsShapeIndex; private readonly object _syncRoot = new(); /// <summary> /// Tree used for fast query of data /// </summary> private QuadTree? _tree; /// <summary> /// Initializes a ShapeFile DataProvider. /// </summary> /// <remarks> /// <para>If FileBasedIndex is true, the spatial index will be read from a local copy. If it doesn't exist, /// it will be generated and saved to [filename] + '.sidx'.</para> /// <para>Using a file-based index is especially recommended for ASP.NET applications which will speed up /// start-up time when the cache has been emptied. /// </para> /// </remarks> /// <param name="filename">Path to shape file</param> /// <param name="fileBasedIndex">Use file-based spatial index</param> public ShapeFile(string filename, bool fileBasedIndex = false) { _filename = filename; _fileBasedIndex = fileBasedIndex && File.Exists(Path.ChangeExtension(filename, ".shx")); //Initialize DBF var dbfFile = Path.ChangeExtension(filename, ".dbf"); if (File.Exists(dbfFile)) _dbaseFile = new DbaseReader(dbfFile); //Parse shape header ParseHeader(); //Read projection file ParseProjection(); } /// <summary> /// Gets the <see cref="Shapefile.ShapeType">shape geometry type</see> in this shapefile. /// </summary> /// <remarks> /// The property isn't set until the first time the data source has been opened, /// and will throw an exception if this property has been called since initialization. /// <para>All the non-Null shapes in a shapefile are required to be of the same shape /// type.</para> /// </remarks> public ShapeType ShapeType => _shapeType; /// <summary> /// Gets or sets the filename of the shapefile /// </summary> /// <remarks>If the filename changes, indexes will be rebuilt</remarks> public string Filename { get => _filename; set { if (value != _filename) { lock (_syncRoot) _filename = value; if (_isOpen) throw new ApplicationException("Cannot change filename while data source is open"); ParseHeader(); ParseProjection(); _tree?.Dispose(); _tree = null; } } } /// <summary> /// Gets or sets the encoding used for parsing strings from the DBase DBF file. /// </summary> /// <remarks> /// The DBase default encoding is UTF7"/>. /// </remarks> public Encoding? Encoding { get => _dbaseFile?.Encoding; set { if (_dbaseFile != null) _dbaseFile.Encoding = value; } } /// <summary> /// Filter Delegate Method for limiting the data source /// </summary> public FilterMethod? FilterDelegate { get; set; } private bool _disposed; /// <summary> /// Disposes the object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!_disposed) { if (disposing) { Close(); _envelope = null; _tree?.Dispose(); _tree = null; } _disposed = true; } } /// <summary> /// Finalizes the object /// </summary> ~ShapeFile() { Dispose(false); } /// <summary> /// Opens the data source /// </summary> private void Open() { // TODO: // Get a Connector. The connector returned is guaranteed to be connected and ready to go. // Pooling.Connector connector = Pooling.ConnectorPool.ConnectorPoolManager.RequestConnector(this,true); if (!_isOpen) { _fsShapeIndex?.Dispose(); _fsShapeIndex = new FileStream(_filename.Remove(_filename.Length - 4, 4) + ".shx", FileMode.Open, FileAccess.Read); _brShapeFile?.Dispose(); _brShapeIndex = new BinaryReader(_fsShapeIndex, Encoding.Unicode); _fsShapeFile?.Dispose(); _fsShapeFile = new FileStream(_filename, FileMode.Open, FileAccess.Read); _brShapeFile?.Dispose(); _brShapeFile = new BinaryReader(_fsShapeFile); InitializeShape(_filename, _fileBasedIndex); _dbaseFile?.Open(); _isOpen = true; } } /// <summary> /// Closes the data source /// </summary> private void Close() { if (!_disposed) if (_isOpen) { _brShapeIndex?.Dispose(); _brShapeFile?.Dispose(); _fsShapeFile?.Dispose(); _fsShapeIndex?.Dispose(); _dbaseFile?.Dispose(); _isOpen = false; } } /// <summary> /// Returns geometries whose bounding box intersects 'bbox' /// </summary> /// <remarks> /// <para>Please note that this method doesn't guarantee that the geometries returned actually intersect 'bbox', but only /// that their BoundingBox intersects 'bbox'.</para> /// <para>This method is much faster than the QueryFeatures method, because intersection tests /// are performed on objects simplified by their BoundingBox, and using the Spatial Index.</para> /// </remarks> /// <param name="bbox"></param> /// <returns></returns> public Collection<Geometry> GetGeometriesInView(MRect bbox) { lock (_syncRoot) { Open(); try { //Use the spatial index to get a list of features whose BoundingBox intersects bbox var objectList = GetObjectIDsInViewPrivate(bbox); if (objectList.Count == 0) //no features found. Return an empty set return new Collection<Geometry>(); var geometries = new Collection<Geometry>(); for (var i = 0; i < objectList.Count; i++) { var g = GetGeometryPrivate(objectList[i]); if (g != null) geometries.Add(g); } return geometries; } finally { Close(); } } } /// <summary> /// Returns geometry Object IDs whose bounding box intersects 'bbox' /// </summary> /// <param name="bbox"></param> /// <returns></returns> public Collection<uint> GetObjectIDsInView(MRect bbox) { lock (_syncRoot) { Open(); try { return GetObjectIDsInViewPrivate(bbox); } finally { Close(); } } } private Collection<uint> GetObjectIDsInViewPrivate(MRect? bbox) { if (bbox == null) return new Collection<uint>(); if (!_isOpen) throw new ApplicationException("An attempt was made to read from a closed data source"); //Use the spatial index to get a list of features whose BoundingBox intersects bbox return _tree!.Search(bbox); } /// <summary> /// Returns the geometry corresponding to the Object ID /// </summary> /// <param name="oid">Object ID</param> /// <returns>geometry</returns> public Geometry? GetGeometry(uint oid) { lock (_syncRoot) { Open(); try { return GetGeometryPrivate(oid); } finally { Close(); } } } private Geometry? GetGeometryPrivate(uint oid) { if (FilterDelegate != null) //Apply filtering { var fdr = GetFeature(oid); return fdr?.Geometry; } return ReadGeometry(oid); } /// <summary> /// Returns the total number of features in the data source (without any filter applied) /// </summary> /// <returns></returns> public int GetFeatureCount() { return _featureCount; } /// <summary> /// Returns the extent of the data source /// </summary> /// <returns></returns> public MRect? GetExtent() { lock (_syncRoot) { Open(); try { if (_tree == null) return _envelope; return _tree.Box; } finally { Close(); } } } /// <summary> /// Gets or sets the spatial reference ID (CRS) /// </summary> public string? CRS { get; set; } = ""; private void InitializeShape(string filename, bool fileBasedIndex) { if (!File.Exists(filename)) throw new FileNotFoundException($"Could not find file \"{filename}\""); if (!filename.ToLower().EndsWith(".shp")) throw new Exception("Invalid shapefile filename: " + filename); LoadSpatialIndex(fileBasedIndex); //Load spatial index } /// <summary> /// Reads and parses the header of the .shx index file /// </summary> private void ParseHeader() { _fsShapeIndex?.Dispose(); _fsShapeIndex = new FileStream(Path.ChangeExtension(_filename, ".shx"), FileMode.Open, FileAccess.Read); _brShapeIndex?.Dispose(); _brShapeIndex = new BinaryReader(_fsShapeIndex, Encoding.Unicode); _brShapeIndex.BaseStream.Seek(0, 0); //Check file header if (_brShapeIndex.ReadInt32() != 170328064) //File Code is actually 9994, but in Little Endian Byte Order this is '170328064' throw new ApplicationException("Invalid Shapefile Index (.shx)"); _brShapeIndex.BaseStream.Seek(24, 0); //seek to File Length var indexFileSize = SwapByteOrder(_brShapeIndex.ReadInt32()); //Read file length as big-endian. The length is based on 16bit words _featureCount = (2 * indexFileSize - 100) / 8; //Calculate FeatureCount. Each feature takes up 8 bytes. The header is 100 bytes _brShapeIndex.BaseStream.Seek(32, 0); //seek to ShapeType _shapeType = (ShapeType)_brShapeIndex.ReadInt32(); //Read the spatial bounding box of the contents _brShapeIndex.BaseStream.Seek(36, 0); //seek to box _envelope = new MRect(_brShapeIndex.ReadDouble(), _brShapeIndex.ReadDouble(), _brShapeIndex.ReadDouble(), _brShapeIndex.ReadDouble()); _brShapeIndex.Close(); _fsShapeIndex.Close(); } /// <summary> /// Reads and parses the projection if a projection file exists /// </summary> private void ParseProjection() { var projFile = Path.GetDirectoryName(Filename) + "\\" + Path.GetFileNameWithoutExtension(Filename) + ".prj"; if (File.Exists(projFile)) try { // todo: Automatically parse coordinate system: // var wkt = File.ReadAllText(projFile); // CoordinateSystemWktReader.Parse(wkt); } catch (Exception ex) { Trace.TraceWarning("Coordinate system file '" + projFile + "' found, but could not be parsed. WKT parser returned:" + ex.Message); throw; } } /// <summary> /// Reads the record offsets from the .shx index file and returns the information in an array /// </summary> private int[] ReadIndex() { if (_brShapeIndex is null) return Array.Empty<int>(); var offsetOfRecord = new int[_featureCount]; _brShapeIndex.BaseStream.Seek(100, 0); // Skip the header for (var x = 0; x < _featureCount; ++x) { offsetOfRecord[x] = 2 * SwapByteOrder(_brShapeIndex.ReadInt32()); // Read shape data position // ibuffer); _brShapeIndex.BaseStream.Seek(_brShapeIndex.BaseStream.Position + 4, 0); // Skip content length } return offsetOfRecord; } /// <summary> /// Gets the file position of the n'th shape /// </summary> /// <param name="n">Shape ID</param> /// <returns></returns> private int GetShapeIndex(uint n) { if (_brShapeIndex is null) throw new Exception("_brShapeIndex can not be null"); _brShapeIndex.BaseStream.Seek(100 + n * 8, 0); //seek to the position of the index return 2 * SwapByteOrder(_brShapeIndex.ReadInt32()); //Read shape data position } ///<summary> ///Swaps the byte order of an int32 ///</summary> /// <param name="i">Integer to swap</param> /// <returns>Byte Order swapped int32</returns> private int SwapByteOrder(int i) { var buffer = BitConverter.GetBytes(i); Array.Reverse(buffer, 0, buffer.Length); return BitConverter.ToInt32(buffer, 0); } /// <summary> /// Loads a spatial index from a file. If it doesn't exist, one is created and saved /// </summary> /// <param name="filename"></param> /// <returns>QuadTree index</returns> private QuadTree CreateSpatialIndexFromFile(string filename) { if (File.Exists(filename + ".sidx")) try { return QuadTree.FromFile(filename + ".sidx"); } catch (QuadTree.ObsoleteFileFormatException) { File.Delete(filename + ".sidx"); return CreateSpatialIndexFromFile(filename); } var tree = CreateSpatialIndex(); tree.SaveIndex(filename + ".sidx"); return tree; } /// <summary> /// Generates a spatial index for a specified shape file. /// </summary> private QuadTree CreateSpatialIndex() { var objList = new List<QuadTree.BoxObjects>(); // Convert all the geometries to BoundingBoxes uint i = 0; foreach (var box in GetAllFeatureBoundingBoxes()) if (!double.IsNaN(box.Left) && !double.IsNaN(box.Right) && !double.IsNaN(box.Bottom) && !double.IsNaN(box.Top)) { var g = new QuadTree.BoxObjects { Box = box, Id = i }; objList.Add(g); i++; } Heuristic heuristic; heuristic.Maxdepth = (int)Math.Ceiling(Math.Log(GetFeatureCount(), 2)); heuristic.Minerror = 10; heuristic.Tartricnt = 5; heuristic.Mintricnt = 2; return new QuadTree(objList, 0, heuristic); } private void LoadSpatialIndex(bool loadFromFile) { LoadSpatialIndex(false, loadFromFile); } private void LoadSpatialIndex(bool forceRebuild, bool loadFromFile) { //Only load the tree if we haven't already loaded it, or if we want to force a rebuild if (_tree == null || forceRebuild) { _tree?.Dispose(); _tree = !loadFromFile ? CreateSpatialIndex() : CreateSpatialIndexFromFile(_filename); } } /// <summary> /// Forces a rebuild of the spatial index. If the instance of the ShapeFile provider /// uses a file-based index the file is rewritten to disk. /// </summary> public void RebuildSpatialIndex() { if (_fileBasedIndex) { if (File.Exists(_filename + ".sidx")) File.Delete(_filename + ".sidx"); { _tree?.Dispose(); _tree = CreateSpatialIndexFromFile(_filename); } } else { _tree?.Dispose(); _tree = CreateSpatialIndex(); } } /// <summary> /// Reads all BoundingBoxes of features in the shapefile. This is used for spatial indexing. /// </summary> /// <returns></returns> private IEnumerable<MRect> GetAllFeatureBoundingBoxes() { if (_fsShapeFile is null) yield break; if (_brShapeFile is null) yield break; var offsetOfRecord = ReadIndex(); //Read the whole .idx file if (_shapeType == ShapeType.Point) for (var a = 0; a < _featureCount; ++a) { _fsShapeFile.Seek(offsetOfRecord[a] + 8, 0); // Skip record number and content length if ((ShapeType)_brShapeFile.ReadInt32() != ShapeType.Null) { var x = _brShapeFile.ReadDouble(); var y = _brShapeFile.ReadDouble(); yield return new MRect(x, y, x, y); } } else for (var a = 0; a < _featureCount; ++a) { _fsShapeFile.Seek(offsetOfRecord[a] + 8, 0); // Skip record number and content length if ((ShapeType)_brShapeFile.ReadInt32() != ShapeType.Null) yield return new MRect(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble(), _brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()); } } /// <summary> /// Reads and parses the geometry with ID 'oid' from the ShapeFile /// </summary> /// <remarks><see cref="FilterDelegate">Filtering</see> is not applied to this method</remarks> /// <param name="oid">Object ID</param> /// <returns>geometry</returns> // ReSharper disable once CyclomaticComplexity // Fix when changes need to be made here private Geometry? ReadGeometry(uint oid) { if (_brShapeFile is null) return null; _brShapeFile.BaseStream.Seek(GetShapeIndex(oid) + 8, 0); // Skip record number and content length var type = (ShapeType)_brShapeFile.ReadInt32(); //Shape type if (type == ShapeType.Null) return null; if (_shapeType == ShapeType.Point || _shapeType == ShapeType.PointM || _shapeType == ShapeType.PointZ) return new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble()); if (_shapeType == ShapeType.Multipoint || _shapeType == ShapeType.MultiPointM || _shapeType == ShapeType.MultiPointZ) { _brShapeFile.BaseStream.Seek(32 + _brShapeFile.BaseStream.Position, 0); // Skip min/max box var nPoints = _brShapeFile.ReadInt32(); // Get the number of points if (nPoints == 0) return null; var points = new List<Point>(); for (var i = 0; i < nPoints; i++) points.Add(new Point(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble())); return new MultiPoint(points.ToArray()); } if (_shapeType == ShapeType.PolyLine || _shapeType == ShapeType.Polygon || _shapeType == ShapeType.PolyLineM || _shapeType == ShapeType.PolygonM || _shapeType == ShapeType.PolyLineZ || _shapeType == ShapeType.PolygonZ) { _brShapeFile.BaseStream.Seek(32 + _brShapeFile.BaseStream.Position, 0); // Skip min/max box var nParts = _brShapeFile.ReadInt32(); // Get number of parts (segments) if (nParts == 0) return null; var nPoints = _brShapeFile.ReadInt32(); // Get number of points var segments = new int[nParts + 1]; //Read in the segment indexes for (var b = 0; b < nParts; b++) segments[b] = _brShapeFile.ReadInt32(); //add end point segments[nParts] = nPoints; if ((int)_shapeType % 10 == 3) { var lineStrings = new List<LineString>(); for (var lineId = 0; lineId < nParts; lineId++) { var coordinates = new List<Coordinate>(); for (var i = segments[lineId]; i < segments[lineId + 1]; i++) coordinates.Add(new Coordinate(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble())); lineStrings.Add(new LineString(coordinates.ToArray())); } if (lineStrings.Count == 1) return lineStrings[0]; return new MultiLineString(lineStrings.ToArray()); } else { // First read all the rings var rings = new List<LinearRing>(); for (var ringId = 0; ringId < nParts; ringId++) { var ring = new List<Coordinate>(); for (var i = segments[ringId]; i < segments[ringId + 1]; i++) ring.Add(new Coordinate(_brShapeFile.ReadDouble(), _brShapeFile.ReadDouble())); rings.Add(new LinearRing(ring.ToArray())); } var isCounterClockWise = new bool[rings.Count]; var polygonCount = 0; for (var i = 0; i < rings.Count; i++) { isCounterClockWise[i] = rings[i].IsCCW; if (!isCounterClockWise[i]) polygonCount++; } if (polygonCount == 1) // We only have one polygon { var p = CreatePolygon(rings); return p; } else { var polygons = new List<Polygon>(); var linearRings = new List<LinearRing> { rings[0] }; for (var i = 1; i < rings.Count; i++) if (!isCounterClockWise[i]) { // The !isCCW indicates this is an outerRing (or shell in NTS) // So the previous one is done and is added to the list. A new list of linear rings is created for the next polygon. var p1 = CreatePolygon(linearRings); if (p1 is not null) polygons.Add(p1); linearRings = new List<LinearRing>{ rings[i] }; } else linearRings.Add(rings[i]); var p = CreatePolygon(linearRings); if (p is not null) polygons.Add(p); return new MultiPolygon(polygons.ToArray()); } } } throw new ApplicationException($"Shapefile type {_shapeType} not supported"); } private static Polygon? CreatePolygon(List<LinearRing> poly) { if (poly.Count == 1) return new Polygon(poly[0]); if (poly.Count > 1) return new Polygon(poly[0], poly.Skip(1).ToArray()); return null; } /// <summary> /// Gets a data row from the data source at the specified index belonging to the specified datatable /// </summary> /// <param name="rowId"></param> /// <param name="features">Data table to feature should belong to.</param> /// <returns></returns> public GeometryFeature? GetFeature(uint rowId, List<GeometryFeature>? features = null) { lock (_syncRoot) { Open(); try { return GetFeaturePrivate(rowId, features); } finally { Close(); } } } private GeometryFeature? GetFeaturePrivate(uint rowId, IEnumerable<GeometryFeature>? dt) { if (_dbaseFile != null) { var dr = _dbaseFile.GetFeature(rowId, dt ?? new List<GeometryFeature>()); if (dr != null) { dr.Geometry = ReadGeometry(rowId); if (FilterDelegate == null || FilterDelegate(dr)) return dr; } return null; } throw new ApplicationException("An attempt was made to read DBase data from a shapefile without a valid .DBF file"); } public IEnumerable<GeometryFeature> GetFeatures(FetchInfo fetchInfo) { lock (_syncRoot) { Open(); try { //Use the spatial index to get a list of features whose BoundingBox intersects bbox var objectList = GetObjectIDsInViewPrivate(fetchInfo.Extent); var features = new List<GeometryFeature>(); foreach (var index in objectList) { var feature = _dbaseFile?.GetFeature(index, features); if (feature != null) { feature.Geometry = ReadGeometry(index); if (feature.Geometry?.EnvelopeInternal == null) continue; if (!feature.Geometry.EnvelopeInternal.Intersects(fetchInfo.Extent.ToEnvelope())) continue; if (FilterDelegate != null && !FilterDelegate(feature)) continue; features.Add(feature); } } return features; } finally { Close(); } } } } }
#region Header // Revit MEP API sample application // // Copyright (C) 2007-2021 by Jeremy Tammik, Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software // for any purpose and without fee is hereby granted, provided // that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. // AUTODESK, INC. DOES NOT WARRANT THAT THE OPERATION OF THE // PROGRAM WILL BE UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject // to restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. #endregion // Header #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using WinForms = System.Windows.Forms; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Electrical; using Autodesk.Revit.DB.Mechanical; #endregion // Namespaces namespace AdnRme { class Util { #region Exceptions public class ParameterException : Exception { public ParameterException( string parameterName, string description, Element elem ) : base( string.Format( "'{0}' parameter not defined for {1} {2}", parameterName, description, elem.Id.IntegerValue.ToString() ) ) { } } public class SpaceParameterException : Exception { public SpaceParameterException( string parameterName, Space space ) : base( string.Format( "'{0}' parameter not defined for space {1}", parameterName, space.Number ) ) { } } public class TerminalParameterException : ParameterException { public TerminalParameterException( string parameterName, FamilyInstance terminal ) : base( parameterName, "terminal", terminal ) { } } #endregion // Exceptions #region Formatting public static string PluralSuffix( int n ) { return 1 == n ? "" : "s"; } public static string DotOrColon( int n ) { return 0 == n ? "." : ":"; } public static string IdList( IList<FamilyInstance> elements ) { string s = string.Empty; foreach( Element e in elements ) { if( 0 < s.Length ) { s += ", "; } s += e.Id.IntegerValue.ToString(); } return s; } /// <summary> /// Format a real number and return its string representation. /// </summary> public static string RealString( double a ) { return a.ToString( "0.##" ); } /// <summary> /// Return a description string for a given element. /// </summary> public static string ElementDescription( Element e ) { string description = ( null == e.Category ) ? e.GetType().Name : e.Category.Name; if( null != e.Name ) { description += " '" + e.Name + "'"; } return description; } /// <summary> /// Return a description string including element id for a given element. /// </summary> public static string ElementDescriptionAndId( Element e ) { string description = e.GetType().Name; if( null != e.Category ) { description += " " + e.Category.Name; } string identity = e.Id.IntegerValue.ToString(); if( null != e.Name ) { identity = e.Name + " " + identity; } return string.Format( "{0} <{1}>", description, identity ); } /// <summary> /// Return an element description string for an electrical system browser leaf node. /// </summary> public static string BrowserDescription( Element e ) { FamilyInstance inst = e as FamilyInstance; return ( null == inst ? e.Category.Name : inst.Symbol.Family.Name ) + " " + e.Name; } #endregion // Formatting #region Message const string _caption = "Revit MEP API Sample"; /// <summary> /// MessageBox wrapper for informational message. /// </summary> /// <param name="msg"></param> public static void InfoMsg( string msg ) { WinForms.MessageBox.Show( msg, _caption, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Information ); } /// <summary> /// MessageBox wrapper for error message. /// </summary> /// <param name="msg"></param> public static void ErrorMsg( string msg ) { WinForms.MessageBox.Show( msg, _caption, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Error ); } /// <summary> /// MessageBox wrapper for question message. /// </summary> public static bool QuestionMsg( string msg ) { return WinForms.DialogResult.Yes == WinForms.MessageBox.Show( msg, _caption, WinForms.MessageBoxButtons.YesNo, WinForms.MessageBoxIcon.Question ); } #endregion // Message #region Parameter Access /// <summary> /// Helper to get a specific parameter by name. /// </summary> static Parameter GetParameterFromName( Element elem, string name ) { foreach( Parameter p in elem.Parameters ) { if( p.Definition.Name == name ) { return p; } } return null; } public static Definition GetParameterDefinitionFromName( Element elem, string name ) { Parameter p = GetParameterFromName( elem, name ); return ( null == p ) ? null : p.Definition; } public static double GetParameterValueFromName( Element elem, string name ) { Parameter p = GetParameterFromName( elem, name ); if( null == p ) { throw new ParameterException( name, "element", elem ); } return p.AsDouble(); } public static string GetStringParameterValueFromName(Element elem, string name) { Parameter p = GetParameterFromName(elem, name); if (null == p) { throw new ParameterException(name, "element", elem); } return p.AsString(); } static void DumpParameters( Element elem ) { foreach( Parameter p in elem.Parameters ) { Debug.WriteLine( p.Definition.ParameterType + " " + p.Definition.Name ); } } public static double GetSpaceParameterValue( Space space, BuiltInParameter bip, string name ) { Parameter p = space.get_Parameter( bip ); if( null == p ) { throw new SpaceParameterException( name, space ); } return p.AsDouble(); } public static Parameter GetSpaceParameter( Space space, string name ) { Parameter p = GetParameterFromName( space, name ); if( null == p ) { throw new SpaceParameterException( name, space ); } return p; } public static double GetSpaceParameterValue( Space space, string name ) { Parameter p = GetSpaceParameter( space, name ); return p.AsDouble(); } #if NEED_IS_SUPPLY_AIR_METHOD public static bool IsSupplyAir( FamilyInstance terminal ) { Parameter p = terminal.get_Parameter( Bip.SystemType ); if( null == p ) { throw new TerminalParameterException( Bip.SystemType.ToString(), terminal ); } bool rc = p.AsString().Equals( ParameterValue.SupplyAir ); #if DEBUG ElementId typeId = terminal.GetTypeId(); ElementType t = terminal.Document.get_Element( typeId ) as ElementType; MEPSystemType t2 = terminal.Document.get_Element( typeId ) as MEPSystemType; Debug.Assert( (MEPSystemClassification.SupplyAir == t2.SystemClassification) == rc, "expected parameter check to return correct system classification" ); #endif // DEBUG return rc; } #endif // NEED_IS_SUPPLY_AIR_METHOD public static Parameter GetTerminalFlowParameter( FamilyInstance terminal ) { // // the built-in parameter "Flow" is read-only: // //Parameter p = terminal.get_Parameter( _bipFlow ); // // The parameter we are interested in is not the BuiltInParameter... // Definition d = Util.GetParameterDefinitionFromName( terminal, ParameterName.Flow ); Parameter p = terminal.get_Parameter( d ); if( null == p ) { throw new Util.TerminalParameterException( ParameterName.Flow, terminal ); } return p; } #endregion // Parameter Access #region HVAC Element Access /// <summary> /// Retrieve all supply air terminals from given document. /// Select all family instance elements of BuiltInCategory /// OST_DuctTerminal with system type equal to suppy air. /// </summary> public static FilteredElementCollector GetSupplyAirTerminals( Document doc ) { FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfCategory( BuiltInCategory.OST_DuctTerminal ); collector.OfClass( typeof( FamilyInstance ) ); //int n1 = collector.ToElements().Count; // 61 in sample model // ensure that system type equals supply air: // // in Revit 2009 and 2010 API, this did it: // //ParameterFilter parameterFilter = a.Filter.NewParameterFilter( // Bip.SystemType, CriteriaFilterType.Equal, ParameterValue.SupplyAir ); // in Revit 2011, create an ElementParameter filter. // Create filter by provider and evaluator: ParameterValueProvider provider = new ParameterValueProvider( new ElementId( Bip.SystemType ) ); FilterStringRuleEvaluator evaluator = new FilterStringEquals(); string ruleString = ParameterValue.SupplyAir; FilterRule rule = new FilterStringRule( provider, evaluator, ruleString, false ); ElementParameterFilter filter = new ElementParameterFilter( rule ); collector.WherePasses( filter ); //int n2 = collector.ToElements().Count; // 51 in sample model return collector; } /// <summary> /// Retrieve all spaces in given document. /// </summary> public static List<Space> GetSpaces( Document doc ) { FilteredElementCollector collector = new FilteredElementCollector( doc ); // trying to collect all spaces directly causes // the following error: // // Input type is of an element type that exists // in the API, but not in Revit's native object // model. Try using Autodesk.Revit.DB.Enclosure // instead, and then postprocessing the results // to find the elements of interest. // //collector.OfClass( typeof( Space ) ); collector.OfClass( typeof( SpatialElement ) ); //return ( from e in collector.ToElements() // 2011 // where e is Space // select e as Space ) // .ToList<Space>(); return collector.ToElements().OfType<Space>().ToList<Space>(); // 2012 } #endregion // HVAC Element Access #region Electrical Element Access /// <summary> /// Return all elements of the requested class i.e. System.Type /// matching the given built-in category in the active document. /// </summary> public static FilteredElementCollector GetElementsOfType( Document doc, Type type, BuiltInCategory bic ) { FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfCategory( bic ); collector.OfClass( type ); return collector; } /// <summary> /// Retrieve all electrical equipment elements in the given document, /// identified by the built-in category OST_ElectricalEquipment. /// </summary> public static List<Element> GetElectricalEquipment( Document doc ) { FilteredElementCollector collector = GetElementsOfType( doc, typeof( FamilyInstance ), BuiltInCategory.OST_ElectricalEquipment ); // return a List instead of IList, because we need the method Exists() on it: return new List<Element>( collector.ToElements() ); } /// <summary> /// Retrieve all electrical system elements in the given document. /// </summary> public static IList<Element> GetElectricalSystems( Document doc ) { FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfClass( typeof( ElectricalSystem ) ); return collector.ToElements(); } /// <summary> /// Retrieve all circuit elements in current active document, /// which we identify as all family instance or electrical system /// elements with a non-empty RBS_ELEC_CIRCUIT_NUMBER or "Circuit Number" /// parameter. /// </summary> public static IList<Element> GetCircuitElements( Document doc ) { // // prepend as many 'fast' filters as possible, because parameter access is 'slow': // ElementClassFilter f1 = new ElementClassFilter( typeof( FamilyInstance ) ); ElementClassFilter f2 = new ElementClassFilter( typeof( ElectricalSystem ) ); LogicalOrFilter f3 = new LogicalOrFilter( f1, f2 ); FilteredElementCollector collector = new FilteredElementCollector( doc ).WherePasses( f3 ); BuiltInParameter bip = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER; #if DEBUG int n1 = collector.ToElements().Count; List<Element> a = new List<Element>(); foreach( Element e in collector ) { Parameter p = e.get_Parameter( BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER ); if( null != p && 0 < p.AsString().Length ) { a.Add( e ); } } int n2 = a.Count; Debug.Assert( n1 > n2, "expected filter to eliminate something" ); List<Element> b = ( from e in collector.ToElements() where ( null != e.get_Parameter( bip ) ) && ( 0 < e.get_Parameter( bip ).AsString().Length ) select e ).ToList<Element>(); int n3 = b.Count; Debug.Assert( n2 == n3, "expected to reproduce same result" ); #endif // DEBUG // // this is unclear ... negating the rule that says the parameter // exists and is empty could mean that elements pass if the parameter // is non-empty, but also if the parameter does not exist ... // so maybe returning the collection b instead of c would be a safer bet? // ParameterValueProvider provider = new ParameterValueProvider( new ElementId( bip ) ); FilterStringRuleEvaluator evaluator = new FilterStringEquals(); FilterRule rule = new FilterStringRule( provider, evaluator, string.Empty, false ); ElementParameterFilter filter = new ElementParameterFilter( rule, true ); collector.WherePasses( filter ); IList<Element> c = collector.ToElements(); int n4 = c.Count; Debug.Assert( n2 == n4, "expected to reproduce same result" ); return c; } /// <summary> /// Return the one and only project information element using Revit 2009 filtering /// by searching for the "Project Information" category. Only one such element exists. /// </summary> public static Element GetProjectInfoElem( Document doc ) { //Filter filterCategory = app.Create.Filter.NewCategoryFilter( BuiltInCategory.OST_ProjectInformation ); //ElementIterator i = app.ActiveDocument.get_Elements( filterCategory ); //i.MoveNext(); //Element e = i.Current as Element; FilteredElementCollector collector = new FilteredElementCollector( doc ); collector.OfCategory( BuiltInCategory.OST_ProjectInformation ); Debug.Assert( 1 == collector.ToElements().Count, "expected one single element to be returned" ); Element e = collector.FirstElement(); Debug.Assert( null != e, "expected valid project information element" ); return e; } #endregion // Electrical Element Access } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using CodeSight.Server.Areas.HelpPage.ModelDescriptions; using CodeSight.Server.Areas.HelpPage.Models; namespace CodeSight.Server.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Globalization; using Newtonsoft.Json; namespace iSukces.UnitedValues { public partial struct SpecificHeatCapacity { public SpecificHeatCapacity(decimal value, EnergyUnit energy, MassUnit mass, KelvinTemperatureUnit temperature) : this(value, new EnergyMassDensityUnit(energy, mass), temperature) { } } } // -----===== autogenerated code =====----- // ReSharper disable All // generator: FractionValuesGenerator, UnitJsonConverterGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator, MultiplyAlgebraGenerator namespace iSukces.UnitedValues { [Serializable] [JsonConverter(typeof(SpecificHeatCapacityJsonConverter))] public partial struct SpecificHeatCapacity : IUnitedValue<SpecificHeatCapacityUnit>, IEquatable<SpecificHeatCapacity>, IFormattable { /// <summary> /// creates instance of SpecificHeatCapacity /// </summary> /// <param name="value">value</param> /// <param name="unit">unit</param> public SpecificHeatCapacity(decimal value, SpecificHeatCapacityUnit unit) { Value = value; Unit = unit; } public SpecificHeatCapacity(decimal value, EnergyMassDensityUnit counterUnit, KelvinTemperatureUnit denominatorUnit) { Value = value; Unit = new SpecificHeatCapacityUnit(counterUnit, denominatorUnit); } public SpecificHeatCapacity ConvertTo(SpecificHeatCapacityUnit newUnit) { // generator : FractionValuesGenerator.Add_ConvertTo if (Unit.Equals(newUnit)) return this; var a = new EnergyMassDensity(Value, Unit.CounterUnit); var b = new KelvinTemperature(1, Unit.DenominatorUnit); a = a.ConvertTo(newUnit.CounterUnit); b = b.ConvertTo(newUnit.DenominatorUnit); return new SpecificHeatCapacity(a.Value / b.Value, newUnit); } public bool Equals(SpecificHeatCapacity other) { return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit); } public bool Equals(IUnitedValue<SpecificHeatCapacityUnit> other) { if (other is null) return false; return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit); } public override bool Equals(object other) { return other is IUnitedValue<SpecificHeatCapacityUnit> unitedValue ? Equals(unitedValue) : false; } public decimal GetBaseUnitValue() { // generator : BasicUnitValuesGenerator.Add_GetBaseUnitValue var factor1 = GlobalUnitRegistry.Factors.Get(Unit.CounterUnit); var factor2 = GlobalUnitRegistry.Factors.Get(Unit.DenominatorUnit); if ((factor1.HasValue && factor2.HasValue)) return Value * factor1.Value / factor2.Value; throw new Exception("Unable to find multiplication for unit " + Unit); } public override int GetHashCode() { unchecked { return (Value.GetHashCode() * 397) ^ Unit?.GetHashCode() ?? 0; } } public SpecificHeatCapacity Round(int decimalPlaces) { return new SpecificHeatCapacity(Math.Round(Value, decimalPlaces), Unit); } /// <summary> /// Returns unit name /// </summary> public override string ToString() { return Value.ToString(CultureInfo.InvariantCulture) + Unit.UnitName; } /// <summary> /// Returns unit name /// </summary> /// <param name="format"></param> /// <param name="provider"></param> public string ToString(string format, IFormatProvider provider = null) { return this.ToStringFormat(format, provider); } public SpecificHeatCapacity WithCounterUnit(EnergyMassDensityUnit newUnit) { // generator : FractionValuesGenerator.Add_WithCounterUnit var oldUnit = Unit.CounterUnit; if (oldUnit == newUnit) return this; var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit); var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit); var resultUnit = Unit.WithCounterUnit(newUnit); return new SpecificHeatCapacity(oldFactor / newFactor * Value, resultUnit); } public SpecificHeatCapacity WithDenominatorUnit(KelvinTemperatureUnit newUnit) { // generator : FractionValuesGenerator.Add_WithDenominatorUnit var oldUnit = Unit.DenominatorUnit; if (oldUnit == newUnit) return this; var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit); var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit); var resultUnit = Unit.WithDenominatorUnit(newUnit); return new SpecificHeatCapacity(newFactor / oldFactor * Value, resultUnit); } /// <summary> /// Inequality operator /// </summary> /// <param name="left">first value to compare</param> /// <param name="right">second value to compare</param> public static bool operator !=(SpecificHeatCapacity left, SpecificHeatCapacity right) { return !left.Equals(right); } /// <summary> /// Multiplication operation /// </summary> /// <param name="deltaKelvinTemperature">left factor (multiplicand)</param> /// <param name="specificHeatCapacity">rigth factor (multiplier)</param> public static EnergyMassDensity operator *(DeltaKelvinTemperature deltaKelvinTemperature, SpecificHeatCapacity specificHeatCapacity) { // generator : MultiplyAlgebraGenerator.CreateCodeForRightFractionValue // scenario B var unit = new SpecificHeatCapacityUnit(specificHeatCapacity.Unit.CounterUnit, deltaKelvinTemperature.Unit); var specificHeatCapacityConverted = specificHeatCapacity.WithDenominatorUnit(deltaKelvinTemperature.Unit); var value = deltaKelvinTemperature.Value * specificHeatCapacityConverted.Value; return new EnergyMassDensity(value, specificHeatCapacity.Unit.CounterUnit); } /// <summary> /// Multiplication operation /// </summary> /// <param name="specificHeatCapacity">left factor (multiplicand)</param> /// <param name="deltaKelvinTemperature">rigth factor (multiplier)</param> public static EnergyMassDensity operator *(SpecificHeatCapacity specificHeatCapacity, DeltaKelvinTemperature deltaKelvinTemperature) { // generator : MultiplyAlgebraGenerator.CreateCodeForLeftFractionValue // EnergyMassDensity operator *(SpecificHeatCapacity specificHeatCapacity, DeltaKelvinTemperature deltaKelvinTemperature) // scenario with hint // .Is<SpecificHeatCapacity, DeltaKelvinTemperature, EnergyMassDensity>("*") // hint location Add_EnergyMassDensity_DeltaKelvinTemperature_SpecificHeatCapacity, line 16 var specificHeatCapacityUnit = specificHeatCapacity.Unit; var tmp1 = specificHeatCapacityUnit.CounterUnit; var resultUnit = new EnergyMassDensityUnit(tmp1.CounterUnit, tmp1.DenominatorUnit); var deltaKelvinTemperatureConverted = deltaKelvinTemperature.ConvertTo(specificHeatCapacityUnit.DenominatorUnit); var value = specificHeatCapacity.Value * deltaKelvinTemperatureConverted.Value; return new EnergyMassDensity(value, resultUnit); // scenario D1 } /// <summary> /// Multiplication operation /// </summary> /// <param name="deltaKelvinTemperature">left factor (multiplicand)</param> /// <param name="specificHeatCapacity">rigth factor (multiplier)</param> public static EnergyMassDensity? operator *(DeltaKelvinTemperature? deltaKelvinTemperature, SpecificHeatCapacity specificHeatCapacity) { // generator : MultiplyAlgebraGenerator.CreateCode if (deltaKelvinTemperature is null) return null; return deltaKelvinTemperature.Value * specificHeatCapacity; } /// <summary> /// Multiplication operation /// </summary> /// <param name="specificHeatCapacity">left factor (multiplicand)</param> /// <param name="deltaKelvinTemperature">rigth factor (multiplier)</param> public static EnergyMassDensity? operator *(SpecificHeatCapacity? specificHeatCapacity, DeltaKelvinTemperature deltaKelvinTemperature) { // generator : MultiplyAlgebraGenerator.CreateCode if (specificHeatCapacity is null) return null; return specificHeatCapacity.Value * deltaKelvinTemperature; } /// <summary> /// Multiplication operation /// </summary> /// <param name="deltaKelvinTemperature">left factor (multiplicand)</param> /// <param name="specificHeatCapacity">rigth factor (multiplier)</param> public static EnergyMassDensity? operator *(DeltaKelvinTemperature deltaKelvinTemperature, SpecificHeatCapacity? specificHeatCapacity) { // generator : MultiplyAlgebraGenerator.CreateCode if (specificHeatCapacity is null) return null; return deltaKelvinTemperature * specificHeatCapacity.Value; } /// <summary> /// Multiplication operation /// </summary> /// <param name="specificHeatCapacity">left factor (multiplicand)</param> /// <param name="deltaKelvinTemperature">rigth factor (multiplier)</param> public static EnergyMassDensity? operator *(SpecificHeatCapacity specificHeatCapacity, DeltaKelvinTemperature? deltaKelvinTemperature) { // generator : MultiplyAlgebraGenerator.CreateCode if (deltaKelvinTemperature is null) return null; return specificHeatCapacity * deltaKelvinTemperature.Value; } /// <summary> /// Multiplication operation /// </summary> /// <param name="deltaKelvinTemperature">left factor (multiplicand)</param> /// <param name="specificHeatCapacity">rigth factor (multiplier)</param> public static EnergyMassDensity? operator *(DeltaKelvinTemperature? deltaKelvinTemperature, SpecificHeatCapacity? specificHeatCapacity) { // generator : MultiplyAlgebraGenerator.CreateCode if (deltaKelvinTemperature is null || specificHeatCapacity is null) return null; return deltaKelvinTemperature.Value * specificHeatCapacity.Value; } /// <summary> /// Multiplication operation /// </summary> /// <param name="specificHeatCapacity">left factor (multiplicand)</param> /// <param name="deltaKelvinTemperature">rigth factor (multiplier)</param> public static EnergyMassDensity? operator *(SpecificHeatCapacity? specificHeatCapacity, DeltaKelvinTemperature? deltaKelvinTemperature) { // generator : MultiplyAlgebraGenerator.CreateCode if (specificHeatCapacity is null || deltaKelvinTemperature is null) return null; return specificHeatCapacity.Value * deltaKelvinTemperature.Value; } /// <summary> /// Equality operator /// </summary> /// <param name="left">first value to compare</param> /// <param name="right">second value to compare</param> public static bool operator ==(SpecificHeatCapacity left, SpecificHeatCapacity right) { return left.Equals(right); } public static SpecificHeatCapacity Parse(string value) { // generator : FractionValuesGenerator.Add_Parse throw new NotImplementedException("Not implemented due to unknown split method name."); } /// <summary> /// value /// </summary> public decimal Value { get; } /// <summary> /// unit /// </summary> public SpecificHeatCapacityUnit Unit { get; } } public partial class SpecificHeatCapacityJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(SpecificHeatCapacityUnit); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The JsonReader to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.ValueType == typeof(string)) { if (objectType == typeof(SpecificHeatCapacity)) return SpecificHeatCapacity.Parse((string)reader.Value); } throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is null) writer.WriteNull(); else writer.WriteValue(value.ToString()); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.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 2/8/2010 10:01:52 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; namespace DotSpatial.Data { /// <summary> /// TiledImage is a special kind of image coverage where the images specifically form tiles that /// are adjacent and perfectly aligned to represent a larger image. /// </summary> public class TiledImage : RasterBoundDataSet, ITiledImage, IImageData { #region Private Variables private int _numBands; private int _stride; private TileCollection _tiles; private WorldFile _worldFile; #endregion #region Constructors /// <summary> /// Creates a new instance of the TiledImage where the fileName is specified. /// This doesn't actually open the file until the Open method is called. /// </summary> /// <param name="fileName"></param> public TiledImage(string fileName) { Filename = fileName; } /// <summary> /// Creates a new instance of TiledImage /// </summary> public TiledImage(int width, int height) { Init(width, height); } #endregion #region Methods /// <summary> /// Gets or sets the array of tiles used for this /// </summary> public virtual IImageData[,] Tiles { get { return _tiles.Tiles; } set { _tiles.Tiles = value; } } /// <summary> /// /// </summary> protected TileCollection TileCollection { get { return _tiles; } set { _tiles = value; } } #region IImageData Members /// <summary> /// This should be overridden with custom file handling /// </summary> public virtual void Open() { } #endregion #region ITiledImage Members /// <inheritdoc /> public virtual Bitmap GetBitmap(Extent envelope, Size pixelSize) { Bitmap result = new Bitmap(pixelSize.Width, pixelSize.Height); Graphics g = Graphics.FromImage(result); foreach (var image in GetImages()) { Extent bounds = envelope.Intersection(image.Extent); Size ps = new Size((int)(pixelSize.Width * bounds.Width / envelope.Width), (int)(pixelSize.Height * bounds.Height / envelope.Height)); int x = pixelSize.Width * (int)((bounds.X - envelope.X) / envelope.Width); int y = pixelSize.Height * (int)((envelope.Y - bounds.Y) / envelope.Height); if (ps.Width > 0 && ps.Height > 0) { Bitmap tile = image.GetBitmap(bounds, ps); g.DrawImageUnscaled(tile, x, y); } } return result; } /// <inheritdoc /> public override void Close() { if (Tiles == null) return; foreach (IImageData image in Tiles) { if (image != null) image.Close(); } base.Close(); } #endregion /// <summary> /// Even if this TiledImage has already been constructed, we can initialize the tile collection later. /// </summary> /// <param name="width"></param> /// <param name="height"></param> public void Init(int width, int height) { _tiles = new TileCollection(width, height); } /// <summary> /// Calls a method that calculates the proper image bounds for each of the extents of the tiles, /// given the affine coefficients for the whole image. /// </summary> /// <param name="affine"> x' = A + Bx + Cy; y' = D + Ex + Fy</param> public void SetTileBounds(double[] affine) { _tiles.SetTileBounds(affine); } #endregion #region Properties /// <inheritdoc /> public int Height { get { return _tiles.Height; } set { } } /// <inheritdoc /> public int Stride { get { return _stride; } set { _stride = value; } } /// <inheritdoc /> public int Width { get { return _tiles.Width; } set { } } #endregion #region IImageData Members /// <summary> /// Gets or sets the number of bands /// </summary> public int NumBands { get { return _numBands; } set { _numBands = value; } } /// <inheritdoc /> public int BytesPerPixel { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <inheritdoc /> public void CopyValues(IImageData source) { throw new NotImplementedException(); } /// <inheritdoc /> public Bitmap GetBitmap() { throw new NotImplementedException(); } /// <inheritdoc /> public Bitmap GetBitmap(Extent envelope, Rectangle window) { return GetBitmap(envelope, new Size(window.Width, window.Height)); } /// <inheritdoc /> public Color GetColor(int row, int column) { throw new NotImplementedException(); } /// <inheritdoc /> public void CopyBitmapToValues() { throw new NotImplementedException(); } /// <inheritdoc /> public void Save() { throw new NotImplementedException(); } /// <inheritdoc /> public void SaveAs(string fileName) { throw new NotImplementedException(); } /// <inheritdoc /> public void SetColor(int row, int column, Color col) { throw new NotImplementedException(); } /// <inheritdoc /> public void CopyValuesToBitmap() { throw new NotImplementedException(); } /// <inheritdoc /> public byte[] Values { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Not Implemented. /// </summary> /// <returns></returns> public IEnumerable<Color> GetColorPalette() { throw new NotImplementedException(); } /// <summary> /// Not Implemented /// </summary> /// <param name="value"></param> public void SetColorPalette(IEnumerable<Color> value) { throw new NotImplementedException(); } /// <summary> /// Not implemented /// </summary> /// <param name="xOffset"></param> /// <param name="yOffset"></param> /// <param name="xSize"></param> /// <param name="ySize"></param> /// <returns></returns> public Bitmap ReadBlock(int xOffset, int yOffset, int xSize, int ySize) { throw new NotImplementedException(); } /// <summary> /// Not Implemented /// </summary> /// <param name="value"></param> /// <param name="xOffset"></param> /// <param name="yOffset"></param> public void WriteBlock(Bitmap value, int xOffset, int yOffset) { throw new NotImplementedException(); } /// <summary> /// Not implemented /// </summary> public void UpdateOverviews() { throw new NotImplementedException(); } /// <summary> /// Not Implemented /// </summary> public ImageBandType BandType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion #region ITiledImage Members /// <inheritdoc /> public int TileWidth { get { return _tiles.TileWidth; } } /// <inheritdoc /> public int TileHeight { get { return _tiles.TileHeight; } } /// <inheritdoc /> public int Count { get { return _tiles.NumTiles; } } /// <inheritdoc /> public override Extent Extent { get { Extent ext = new Extent(); foreach (IImageData image in _tiles) { ext.ExpandToInclude(image.Extent); } return ext; } } /// <inheritdoc /> public IEnumerable<IImageData> GetImages() { return _tiles; } /// <summary> /// Gets or sets the WorldFile for this set of tiles. /// </summary> public WorldFile WorldFile { get { return _worldFile; } set { _worldFile = value; } } #endregion /// <inheritdoc /> protected override void Dispose(bool disposeManagedResources) { foreach (IImageData tile in _tiles) { tile.Dispose(); } base.Dispose(disposeManagedResources); } } }
// 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 HorizontalSubtractInt32() { var test = new HorizontalBinaryOpTest__HorizontalSubtractInt32(); 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class HorizontalBinaryOpTest__HorizontalSubtractInt32 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int Op2ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private HorizontalBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static HorizontalBinaryOpTest__HorizontalSubtractInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); } public HorizontalBinaryOpTest__HorizontalSubtractInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new HorizontalBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Ssse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Ssse3.HorizontalSubtract( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Ssse3.HorizontalSubtract( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Ssse3.HorizontalSubtract( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalSubtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalSubtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Ssse3).GetMethod(nameof(Ssse3.HorizontalSubtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Ssse3.HorizontalSubtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Ssse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Ssse3.HorizontalSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new HorizontalBinaryOpTest__HorizontalSubtractInt32(); var result = Ssse3.HorizontalSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Ssse3.HorizontalSubtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { for (var outer = 0; outer < (VectorSize / 16); outer++) { for (var inner = 0; inner < (8 / sizeof(Int32)); inner++) { var i1 = (outer * (16 / sizeof(Int32))) + inner; var i2 = i1 + (8 / sizeof(Int32)); var i3 = (outer * (16 / sizeof(Int32))) + (inner * 2); if (result[i1] != (int)(left[i3] - left[i3 + 1])) { Succeeded = false; break; } if (result[i2] != (int)(right[i3] - right[i3 + 1])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Ssse3)}.{nameof(Ssse3.HorizontalSubtract)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B02_Continent (editable child object).<br/> /// This is a generated base class of <see cref="B02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B03_SubContinentObjects"/> of type <see cref="B03_SubContinentColl"/> (1:M relation to <see cref="B04_SubContinent"/>)<br/> /// This class is an item of <see cref="B01_ContinentColl"/> collection. /// </remarks> [Serializable] public partial class B02_Continent : BusinessBase<B02_Continent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continent ID"); /// <summary> /// Gets the Continent ID. /// </summary> /// <value>The Continent ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continent Name"); /// <summary> /// Gets or sets the Continent Name. /// </summary> /// <value>The Continent Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } set { SetProperty(Continent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_Child> B03_Continent_SingleObjectProperty = RegisterProperty<B03_Continent_Child>(p => p.B03_Continent_SingleObject, "B03 Continent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the B03 Continent Single Object ("parent load" child property). /// </summary> /// <value>The B03 Continent Single Object.</value> public B03_Continent_Child B03_Continent_SingleObject { get { return GetProperty(B03_Continent_SingleObjectProperty); } private set { LoadProperty(B03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_ReChild> B03_Continent_ASingleObjectProperty = RegisterProperty<B03_Continent_ReChild>(p => p.B03_Continent_ASingleObject, "B03 Continent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the B03 Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The B03 Continent ASingle Object.</value> public B03_Continent_ReChild B03_Continent_ASingleObject { get { return GetProperty(B03_Continent_ASingleObjectProperty); } private set { LoadProperty(B03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<B03_SubContinentColl> B03_SubContinentObjectsProperty = RegisterProperty<B03_SubContinentColl>(p => p.B03_SubContinentObjects, "B03 SubContinent Objects", RelationshipTypes.Child); /// <summary> /// Gets the B03 Sub Continent Objects ("parent load" child property). /// </summary> /// <value>The B03 Sub Continent Objects.</value> public B03_SubContinentColl B03_SubContinentObjects { get { return GetProperty(B03_SubContinentObjectsProperty); } private set { LoadProperty(B03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B02_Continent"/> object. /// </summary> /// <returns>A reference to the created <see cref="B02_Continent"/> object.</returns> internal static B02_Continent NewB02_Continent() { return DataPortal.CreateChild<B02_Continent>(); } /// <summary> /// Factory method. Loads a <see cref="B02_Continent"/> object from the given B02_ContinentDto. /// </summary> /// <param name="data">The <see cref="B02_ContinentDto"/>.</param> /// <returns>A reference to the fetched <see cref="B02_Continent"/> object.</returns> internal static B02_Continent GetB02_Continent(B02_ContinentDto data) { B02_Continent obj = new B02_Continent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.LoadProperty(B03_SubContinentObjectsProperty, B03_SubContinentColl.NewB03_SubContinentColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B02_Continent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B02_Continent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(B03_Continent_SingleObjectProperty, DataPortal.CreateChild<B03_Continent_Child>()); LoadProperty(B03_Continent_ASingleObjectProperty, DataPortal.CreateChild<B03_Continent_ReChild>()); LoadProperty(B03_SubContinentObjectsProperty, DataPortal.CreateChild<B03_SubContinentColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B02_Continent"/> object from the given <see cref="B02_ContinentDto"/>. /// </summary> /// <param name="data">The B02_ContinentDto to use.</param> private void Fetch(B02_ContinentDto data) { // Value properties LoadProperty(Continent_IDProperty, data.Continent_ID); LoadProperty(Continent_NameProperty, data.Continent_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Loads child objects from the given DAL provider. /// </summary> /// <param name="dal">The DAL provider to use.</param> internal void FetchChildren(IB01_ContinentCollDal dal) { foreach (var item in dal.B03_Continent_Child) { var child = B03_Continent_Child.GetB03_Continent_Child(item); var obj = ((B01_ContinentColl)Parent).FindB02_ContinentByParentProperties(child.continent_ID1); obj.LoadProperty(B03_Continent_SingleObjectProperty, child); } foreach (var item in dal.B03_Continent_ReChild) { var child = B03_Continent_ReChild.GetB03_Continent_ReChild(item); var obj = ((B01_ContinentColl)Parent).FindB02_ContinentByParentProperties(child.continent_ID2); obj.LoadProperty(B03_Continent_ASingleObjectProperty, child); } var b03_SubContinentColl = B03_SubContinentColl.GetB03_SubContinentColl(dal.B03_SubContinentColl); b03_SubContinentColl.LoadItems((B01_ContinentColl)Parent); foreach (var item in dal.B05_SubContinent_Child) { var child = B05_SubContinent_Child.GetB05_SubContinent_Child(item); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID1); obj.LoadChild(child); } foreach (var item in dal.B05_SubContinent_ReChild) { var child = B05_SubContinent_ReChild.GetB05_SubContinent_ReChild(item); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID2); obj.LoadChild(child); } var b05_CountryColl = B05_CountryColl.GetB05_CountryColl(dal.B05_CountryColl); b05_CountryColl.LoadItems(b03_SubContinentColl); foreach (var item in dal.B07_Country_Child) { var child = B07_Country_Child.GetB07_Country_Child(item); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID1); obj.LoadChild(child); } foreach (var item in dal.B07_Country_ReChild) { var child = B07_Country_ReChild.GetB07_Country_ReChild(item); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID2); obj.LoadChild(child); } var b07_RegionColl = B07_RegionColl.GetB07_RegionColl(dal.B07_RegionColl); b07_RegionColl.LoadItems(b05_CountryColl); foreach (var item in dal.B09_Region_Child) { var child = B09_Region_Child.GetB09_Region_Child(item); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID1); obj.LoadChild(child); } foreach (var item in dal.B09_Region_ReChild) { var child = B09_Region_ReChild.GetB09_Region_ReChild(item); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID2); obj.LoadChild(child); } var b09_CityColl = B09_CityColl.GetB09_CityColl(dal.B09_CityColl); b09_CityColl.LoadItems(b07_RegionColl); foreach (var item in dal.B11_City_Child) { var child = B11_City_Child.GetB11_City_Child(item); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID1); obj.LoadChild(child); } foreach (var item in dal.B11_City_ReChild) { var child = B11_City_ReChild.GetB11_City_ReChild(item); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID2); obj.LoadChild(child); } var b11_CityRoadColl = B11_CityRoadColl.GetB11_CityRoadColl(dal.B11_CityRoadColl); b11_CityRoadColl.LoadItems(b09_CityColl); } /// <summary> /// Inserts a new <see cref="B02_Continent"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert() { var dto = new B02_ContinentDto(); dto.Continent_Name = Continent_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IB02_ContinentDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(Continent_IDProperty, resultDto.Continent_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="B02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new B02_ContinentDto(); dto.Continent_ID = Continent_ID; dto.Continent_Name = Continent_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IB02_ContinentDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="B02_Continent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IB02_ContinentDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Continent_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase { [Fact] public void Never() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object F = 1; object P { get { return 3; } } } class P { public P(C c) { } public object G = 2; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object Q { get { return 4; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("G", "2", "object {int}", "new P(new C()).G"), EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DebuggerBrowsableAttributes are not inherited. /// </summary> [Fact] public void Never_OverridesAndImplements() { var source = @"using System.Diagnostics; interface I { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P1 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P2 { get; } object P3 { get; } object P4 { get; } } abstract class A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P5 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal virtual object P6 { get { return 0; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P7 { get; } internal abstract object P8 { get; } } class B : A, I { public object P1 { get { return 1; } } object I.P2 { get { return 2; } } object I.P3 { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object I.P4 { get { return 4; } } internal override object P5 { get { return 5; } } internal override object P6 { get { return 6; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P7 { get { return 7; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P8 { get { return 8; } } } class C { I o = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("c", value); Verify(evalResult, EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[0]); Verify(children, EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly), EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly), EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly), EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly), EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DkmClrDebuggerBrowsableAttributes are obtained from the /// containing type and associated with the member name. For /// explicit interface implementations, the name will include /// namespace and type. /// </summary> [Fact] public void Never_ExplicitNamespaceGeneric() { var source = @"using System.Diagnostics; namespace N1 { namespace N2 { class A<T> { internal interface I<U> { T P { get; } U Q { get; } } } } class B : N2.A<object>.I<int> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object N2.A<object>.I<int>.P { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Q { get { return 2; } } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("N1.B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{N1.B}", "N1.B", "o")); } [Fact] public void RootHidden() { var source = @"using System.Diagnostics; struct S { internal S(int[] x, object[] y) : this() { this.F = x; this.Q = y; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int[] F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int P { get { return this.F.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object[] Q { get; private set; } } class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly B G = new B { H = 4 }; } class B { internal object H; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeA = assembly.GetType("A"); var value = CreateDkmClrValue( value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }), type: new DkmClrType((TypeImpl)typeS), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.F[0]"), EvalResult("[1]", "2", "int", "o.F[1]"), EvalResult("[0]", "3", "object {int}", "o.Q[0]"), EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[3]), EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H")); } [Fact] public void RootHidden_Exception() { var source = @"using System; using System.Diagnostics; class E : Exception { } class F : E { object G = 1; } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] object P { get { throw new F(); } } }"; using (new EnsureEnglishUICulture()) { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children[1], EvalResult("G", "1", "object {int}", null)); Verify(children[7], EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } /// <summary> /// Instance of type where all members are marked /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]. /// </summary> [WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")] [Fact] public void RootHidden_Empty() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F1 = new C(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F2 = new C(); } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F3 = new object(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F4 = null; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable. var children = GetChildren(evalResult); Verify(children); // No children. } [Fact] public void DebuggerBrowsable_GenericType() { var source = @"using System.Diagnostics; class C<T> { internal C(T f, T g) { this.F = f; this.G = g; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal readonly T F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly T G; } struct S { internal S(object o) { this.O = o; } internal readonly object O; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeC = assembly.GetType("C`1").MakeGenericType(typeS); var value = CreateDkmClrValue( value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)), type: new DkmClrType((TypeImpl)typeC), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void RootHidden_ExplicitImplementation() { var source = @"using System.Diagnostics; interface I<T> { T P { get; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] T Q { get; } } class A { internal object F; } class B : I<A> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] A I<A>.P { get { return new A() { F = 1 }; } } A I<A>.Q { get { return new A() { F = 2 }; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"), EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F")); } [Fact] public void RootHidden_ProxyType() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class A { internal A(int f) { this.F = f; } internal int F; } class P { private readonly A a; public P(A a) { this.a = a; } public object Q { get { return this.a.F; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object R { get { return this.a.F + 1; } } } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F = new A(1); internal object G = new A(3); }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("F", "1", "int", "((A)o.F).F")); Verify(GetChildren(children[2]), EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [Fact] public void RootHidden_Recursive() { var source = @"using System.Diagnostics; class A { internal A(object o) { this.F = o; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F; } class B { internal B(object o) { this.F = o; } internal object F; }"; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue( value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))), type: new DkmClrType((TypeImpl)typeA), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F")); } [Fact] public void RootHidden_OnStaticMembers() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object F = new B(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object P { get { return new C(); } } internal static object G = 1; } class C { internal static object Q { get { return 3; } } internal object H = 2; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("G", "1", "object {int}", "B.G"), EvalResult("H", "2", "object {int}", "((C)B.P).H"), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[2]); Verify(children, EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly)); } // Dev12 exposes the contents of RootHidden members even // if the members are private (e.g.: ImmutableArray<T>). [Fact] public void RootHidden_OnNonPublicMembers() { var source = @"using System.Diagnostics; public class C<T> { public C(params T[] items) { this.items = items; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private T[] items; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(1, 2, 3), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.items[0]"), EvalResult("[1]", "2", "int", "o.items[1]"), EvalResult("[2]", "3", "int", "o.items[2]")); } // Dev12 does not merge "Static members" (or "Non-Public // members") across multiple RootHidden members. In // other words, there may be multiple "Static members" (or // "Non-Public members") rows within the same container. [Fact] public void RootHidden_WithStaticAndNonPublicMembers() { var source = @"using System.Diagnostics; public class A { public static int PA { get { return 1; } } internal int FA = 2; } public class B { internal int PB { get { return 3; } } public static int FB = 4; } public class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly object FA = new A(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object PB { get { return new B(); } } public static int PC { get { return 5; } } internal int FC = 6; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers); var evalResult = FormatResult("o", value, inspectionContext: inspectionContext); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult, inspectionContext: inspectionContext); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); Verify(GetChildren(children[0]), EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("FA", "2", "int", "((A)o.FA).FA")); Verify(GetChildren(children[2]), EvalResult("FB", "4", "int", "B.FB")); Verify(GetChildren(children[3]), EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[4]), EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[5]), EvalResult("FC", "6", "int", "o.FC")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; public class C<T> { public T X; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Y; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(evalResult), EvalResult("X", "0", "int", "o.X")); } [WorkItem(18581, "https://github.com/dotnet/roslyn/issues/18581")] [Fact] public void AccessibilityNotTrumpedByAttribute() { var source = @"using System.Diagnostics; class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int[] _someArray = { 10, 20 }; private object SomethingPrivate = 3; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] internal object InternalCollapsed { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] private object PrivateCollapsed { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private int[] PrivateRootHidden { get { return _someArray; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "10", "int", "(new C()).PrivateRootHidden[0]"), EvalResult("[1]", "20", "int", "(new C()).PrivateRootHidden[1]"), EvalResult("Non-Public members", null, "", "new C(), hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); var nonPublicChildren = GetChildren(children[2]); Verify(nonPublicChildren, EvalResult("InternalCollapsed", "1", "object {int}", "(new C()).InternalCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Internal), EvalResult("PrivateCollapsed", "3", "object {int}", "(new C()).PrivateCollapsed", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private), EvalResult("SomethingPrivate", "3", "object {int}", "(new C()).SomethingPrivate", DkmEvaluationResultFlags.None, DkmEvaluationResultCategory.Data, DkmEvaluationResultAccessType.Private)); } } }
using System.Linq; using hw.DebugFormatter; using hw.UnitTest; using ReniUI.Formatting; namespace ReniUI.Test.Formatting; [UnitTest] [TestFixture] [Declaration] [Basics] [Lists] [ThenElse] public sealed class Complex : DependenceProvider { [Test] [UnitTest] public void MultilineBreakTest11() { const string text = @"1; repeat: @ ^ while() then ( ^ body(), repeat(^) ); 2"; const string expected = @"1; repeat: @ ^ while() then ( ^ body(), repeat(^) ); 2"; text.SimpleFormattingTest(expected, 20, 0, 4, lineBreaksAtComplexDeclaration: true); } [Test] [UnitTest] public void Reformat() { const string text = @"systemdata:{1 type instance(); Memory:((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) );}; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print "; var expectedText = @"systemdata: { 1 type instance(); Memory: ((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) ); }; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print" .Replace("\r\n", "\n"); text.SimpleFormattingTest(expectedText, 100, 0, 4, lineBreaksAtComplexDeclaration: true); } [Test] [UnitTest] // ReSharper disable once InconsistentNaming public void Reformat1_120() { const string text = @"systemdata:{1 type instance(); Memory:((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) );}; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print "; var expectedText = @"systemdata: { 1 type instance(); Memory: ((0 type *('100' to_number_of_base 64)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; repeat: @ ^ while() then ( ^ body(), repeat(^) ); }; 1 = 1 then 2 else 4; 3; (Text('H') << 'allo') dump_print"; text.SimpleFormattingTest(expectedText, 120, 1, 4, lineBreaksAtComplexDeclaration: true); } [Test] [UnitTest] // ReSharper disable once InconsistentNaming public void Reformat1_120TopLineBreak() { const string text = @"(aaaaa ( ))"; var expectedText = @"( aaaaa ( ) )".Replace("\r\n", "\n"); text.SimpleFormattingTest(expectedText, 120, 1, 4, lineBreaksAtComplexDeclaration: true); } [UnitTest] // ReSharper disable once InconsistentNaming public void Reformat1_120EmptyBrackets() { const string text = @"( )"; text.SimpleFormattingTest(maxLineLength: 120, emptyLineLimit: 1, indentCount: 4 , lineBreaksAtComplexDeclaration: true); } [Test] [UnitTest] public void Reformat2() { const string text = @"systemdata: { Memory:((0 type *(125)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; }; "; const string expectedText = @"systemdata: { Memory: ((0 type *(125)) mutable) instance(); !mutable FreePointer: Memory array_reference mutable; };"; text.SimpleFormattingTest(expectedText, 60, 0, 4, lineBreaksAtComplexDeclaration: true); } [Test] [UnitTest] public void TwoLevelParenthesis() { const string text = @"aaaaa;llll:bbbbb;(cccccxsssss)"; const string expectedText = @"aaaaa; llll: bbbbb; ( cccccxsssss )"; text.SimpleFormattingTest(expectedText, 12, 1, 4, lineBreaksAtComplexDeclaration: true); } [Test] [UnitTest] public void UseLineBreakBeforeParenthesis() { const string text = @"a:{ 1234512345, 12345}"; var expectedText = @"a: { 1234512345, 12345 }" .Replace("\r\n", "\n"); var compiler = CompilerBrowser.FromText(text); var newSource = compiler.Reformat ( new ReniUI.Formatting.Configuration { MaxLineLength = 10, EmptyLineLimit = 0 }.Create() ) .Replace("\r\n", "\n"); var lineCount = newSource.Count(item => item == '\n'); (lineCount > 0).Assert(); (newSource == expectedText).Assert("\n\"" + newSource + "\""); } [Test] [UnitTest] public void HalfList() { const string text = @"System: ( ssssss"; text.SimpleFormattingTest(maxLineLength: 12, emptyLineLimit: 1, indentCount: 4 , lineBreaksAtComplexDeclaration: true); } }
using System; using NTumbleBit.BouncyCastle.Crypto.Utilities; using NTumbleBit.BouncyCastle.Utilities; namespace NTumbleBit.BouncyCastle.Crypto.Digests { /** * SHA-224 as described in RFC 3874 * <pre> * block word digest * SHA-1 512 32 160 * SHA-224 512 32 224 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ internal class Sha224Digest : GeneralDigest { private const int DigestLength = 28; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; /** * Standard constructor */ public Sha224Digest() { Reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha224Digest( Sha224Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha224Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-224"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if(++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if(xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE(H1, output, outOff); Pack.UInt32_To_BE(H2, output, outOff + 4); Pack.UInt32_To_BE(H3, output, outOff + 8); Pack.UInt32_To_BE(H4, output, outOff + 12); Pack.UInt32_To_BE(H5, output, outOff + 16); Pack.UInt32_To_BE(H6, output, outOff + 20); Pack.UInt32_To_BE(H7, output, outOff + 24); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); /* SHA-224 initial hash value */ H1 = 0xc1059ed8; H2 = 0x367cd507; H3 = 0x3070dd17; H4 = 0xf70e5939; H5 = 0xffc00b31; H6 = 0x68581511; H7 = 0x64f98fa7; H8 = 0xbefa4fa4; xOff = 0; Array.Clear(X, 0, X.Length); } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for(int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; i++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0(a) + Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0(h) + Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0(g) + Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0(f) + Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0(e) + Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0(d) + Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0(c) + Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0(b) + Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } /* SHA-224 functions */ private static uint Ch(uint x, uint y, uint z) { return (x & y) ^ (~x & z); } private static uint Maj(uint x, uint y, uint z) { return (x & y) ^ (x & z) ^ (y & z); } private static uint Sum0(uint x) { return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); } private static uint Sum1(uint x) { return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); } private static uint Theta0(uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1(uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-224 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ internal static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public override IMemoable Copy() { return new Sha224Digest(this); } public override void Reset(IMemoable other) { Sha224Digest d = (Sha224Digest)other; CopyIn(d); } } }
using Autofac; using AutoMapper; using Miningcore.Blockchain.Bitcoin; using Miningcore.Blockchain.Bitcoin.DaemonResponses; using Miningcore.Blockchain.Equihash.Configuration; using Miningcore.Blockchain.Equihash.DaemonRequests; using Miningcore.Blockchain.Equihash.DaemonResponses; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.Messaging; using Miningcore.Mining; using Miningcore.Persistence; using Miningcore.Persistence.Model; using Miningcore.Persistence.Repositories; using Miningcore.Time; using NBitcoin; using Newtonsoft.Json.Linq; using Contract = Miningcore.Contracts.Contract; using IBlockRepository = Miningcore.Persistence.Repositories.IBlockRepository; namespace Miningcore.Blockchain.Equihash; [CoinFamily(CoinFamily.Equihash)] public class EquihashPayoutHandler : BitcoinPayoutHandler { public EquihashPayoutHandler( IComponentContext ctx, IConnectionFactory cf, IMapper mapper, IShareRepository shareRepo, IBlockRepository blockRepo, IBalanceRepository balanceRepo, IPaymentRepository paymentRepo, IMasterClock clock, IMessageBus messageBus) : base(ctx, cf, mapper, shareRepo, blockRepo, balanceRepo, paymentRepo, clock, messageBus) { } protected EquihashPoolConfigExtra poolExtraConfig; protected bool supportsNativeShielding; protected Network network; protected EquihashCoinTemplate.EquihashNetworkParams chainConfig; protected override string LogCategory => "Equihash Payout Handler"; protected const decimal TransferFee = 0.0001m; protected const int ZMinConfirmations = 8; #region IPayoutHandler public override async Task ConfigureAsync(ClusterConfig clusterConfig, PoolConfig poolConfig, CancellationToken ct) { await base.ConfigureAsync(clusterConfig, poolConfig, ct); poolExtraConfig = poolConfig.Extra.SafeExtensionDataAs<EquihashPoolConfigExtra>(); // detect network var blockchainInfoResponse = await rpcClient.ExecuteAsync<BlockchainInfo>(logger, BitcoinCommands.GetBlockchainInfo, ct); network = Network.GetNetwork(blockchainInfoResponse.Response.Chain.ToLower()); chainConfig = poolConfig.Template.As<EquihashCoinTemplate>().GetNetwork(network.ChainName); // detect z_shieldcoinbase support var response = await rpcClient.ExecuteAsync<JObject>(logger, EquihashCommands.ZShieldCoinbase, ct); supportsNativeShielding = response.Error.Code != (int) BitcoinRPCErrorCode.RPC_METHOD_NOT_FOUND; } public override async Task PayoutAsync(IMiningPool pool, Balance[] balances, CancellationToken ct) { Contract.RequiresNonNull(balances, nameof(balances)); // Shield first if(supportsNativeShielding) await ShieldCoinbaseAsync(ct); else await ShieldCoinbaseEmulatedAsync(ct); // send in batches with no more than 50 recipients to avoid running into tx size limits var pageSize = 50; var pageCount = (int) Math.Ceiling(balances.Length / (double) pageSize); for(var i = 0; i < pageCount; i++) { var didUnlockWallet = false; // get a page full of balances var page = balances .Skip(i * pageSize) .Take(pageSize) .ToArray(); // build args var amounts = page .Where(x => x.Amount > 0) .Select(x => new ZSendManyRecipient { Address = x.Address, Amount = Math.Round(x.Amount, 8) }) .ToList(); if(amounts.Count == 0) return; var pageAmount = amounts.Sum(x => x.Amount); // check shielded balance var balanceResponse = await rpcClient.ExecuteAsync<object>(logger, EquihashCommands.ZGetBalance, ct, new object[] { poolExtraConfig.ZAddress, // default account ZMinConfirmations, // only spend funds covered by this many confirmations }); if(balanceResponse.Error != null || (decimal) (double) balanceResponse.Response - TransferFee < pageAmount) { logger.Info(() => $"[{LogCategory}] Insufficient shielded balance for payment of {FormatAmount(pageAmount)}"); return; } logger.Info(() => $"[{LogCategory}] Paying {FormatAmount(pageAmount)} to {page.Length} addresses"); var args = new object[] { poolExtraConfig.ZAddress, // default account amounts, // addresses and associated amounts ZMinConfirmations, // only spend funds covered by this many confirmations TransferFee }; // send command tryTransfer: var response = await rpcClient.ExecuteAsync<string>(logger, EquihashCommands.ZSendMany, ct, args); if(response.Error == null) { var operationId = response.Response; // check result if(string.IsNullOrEmpty(operationId)) logger.Error(() => $"[{LogCategory}] {EquihashCommands.ZSendMany} did not return a operation id!"); else { logger.Info(() => $"[{LogCategory}] Tracking payment operation id: {operationId}"); var continueWaiting = true; while(continueWaiting) { var operationResultResponse = await rpcClient.ExecuteAsync<ZCashAsyncOperationStatus[]>(logger, EquihashCommands.ZGetOperationResult, ct, new object[] { new object[] { operationId } }); if(operationResultResponse.Error == null && operationResultResponse.Response?.Any(x => x.OperationId == operationId) == true) { var operationResult = operationResultResponse.Response.First(x => x.OperationId == operationId); if(!Enum.TryParse(operationResult.Status, true, out ZOperationStatus status)) { logger.Error(() => $"Unrecognized operation status: {operationResult.Status}"); break; } switch(status) { case ZOperationStatus.Success: var txId = operationResult.Result?.Value<string>("txid") ?? string.Empty; logger.Info(() => $"[{LogCategory}] {EquihashCommands.ZSendMany} completed with transaction id: {txId}"); await PersistPaymentsAsync(page, txId); NotifyPayoutSuccess(poolConfig.Id, page, new[] { txId }, null); continueWaiting = false; continue; case ZOperationStatus.Cancelled: case ZOperationStatus.Failed: logger.Error(() => $"{EquihashCommands.ZSendMany} failed: {operationResult.Error.Message} code {operationResult.Error.Code}"); NotifyPayoutFailure(poolConfig.Id, page, $"{EquihashCommands.ZSendMany} failed: {operationResult.Error.Message} code {operationResult.Error.Code}", null); continueWaiting = false; continue; } } logger.Info(() => $"[{LogCategory}] Waiting for completion: {operationId}"); await Task.Delay(TimeSpan.FromSeconds(10), ct); } } } else { if(response.Error.Code == (int) BitcoinRPCErrorCode.RPC_WALLET_UNLOCK_NEEDED && !didUnlockWallet) { if(!string.IsNullOrEmpty(extraPoolPaymentProcessingConfig?.WalletPassword)) { logger.Info(() => $"[{LogCategory}] Unlocking wallet"); var unlockResponse = await rpcClient.ExecuteAsync<JToken>(logger, BitcoinCommands.WalletPassphrase, ct, new[] { (object) extraPoolPaymentProcessingConfig.WalletPassword, (object) 5 // unlock for N seconds }); if(unlockResponse.Error == null) { didUnlockWallet = true; goto tryTransfer; } else { logger.Error(() => $"[{LogCategory}] {BitcoinCommands.WalletPassphrase} returned error: {response.Error.Message} code {response.Error.Code}"); NotifyPayoutFailure(poolConfig.Id, page, $"{BitcoinCommands.WalletPassphrase} returned error: {response.Error.Message} code {response.Error.Code}", null); break; } } else { logger.Error(() => $"[{LogCategory}] Wallet is locked but walletPassword was not configured. Unable to send funds."); NotifyPayoutFailure(poolConfig.Id, page, "Wallet is locked but walletPassword was not configured. Unable to send funds.", null); break; } } else { logger.Error(() => $"[{LogCategory}] {EquihashCommands.ZSendMany} returned error: {response.Error.Message} code {response.Error.Code}"); NotifyPayoutFailure(poolConfig.Id, page, $"{EquihashCommands.ZSendMany} returned error: {response.Error.Message} code {response.Error.Code}", null); } } } // lock wallet logger.Info(() => $"[{LogCategory}] Locking wallet"); await rpcClient.ExecuteAsync<JToken>(logger, BitcoinCommands.WalletLock, ct); } #endregion // IPayoutHandler /// <summary> /// ZCash coins are mined into a t-addr (transparent address), but can only be /// spent to a z-addr (shielded address), and must be swept out of the t-addr /// in one transaction with no change. /// </summary> private async Task ShieldCoinbaseAsync(CancellationToken ct) { logger.Info(() => $"[{LogCategory}] Shielding ZCash Coinbase funds"); var args = new object[] { poolConfig.Address, // source: pool's t-addr receiving coinbase rewards poolExtraConfig.ZAddress, // dest: pool's z-addr }; var response = await rpcClient.ExecuteAsync<ZCashShieldingResponse>(logger, EquihashCommands.ZShieldCoinbase, ct, args); if(response.Error != null) { if(response.Error.Code == -6) logger.Info(() => $"[{LogCategory}] No funds to shield"); else logger.Error(() => $"[{LogCategory}] {EquihashCommands.ZShieldCoinbase} returned error: {response.Error.Message} code {response.Error.Code}"); return; } var operationId = response.Response.OperationId; logger.Info(() => $"[{LogCategory}] {EquihashCommands.ZShieldCoinbase} operation id: {operationId}"); var continueWaiting = true; while(continueWaiting) { var operationResultResponse = await rpcClient.ExecuteAsync<ZCashAsyncOperationStatus[]>(logger, EquihashCommands.ZGetOperationResult, ct, new object[] { new object[] { operationId } }); if(operationResultResponse.Error == null && operationResultResponse.Response?.Any(x => x.OperationId == operationId) == true) { var operationResult = operationResultResponse.Response.First(x => x.OperationId == operationId); if(!Enum.TryParse(operationResult.Status, true, out ZOperationStatus status)) { logger.Error(() => $"Unrecognized operation status: {operationResult.Status}"); break; } switch(status) { case ZOperationStatus.Success: logger.Info(() => $"[{LogCategory}] {EquihashCommands.ZShieldCoinbase} successful"); continueWaiting = false; continue; case ZOperationStatus.Cancelled: case ZOperationStatus.Failed: logger.Error(() => $"{EquihashCommands.ZShieldCoinbase} failed: {operationResult.Error.Message} code {operationResult.Error.Code}"); continueWaiting = false; continue; } } logger.Info(() => $"[{LogCategory}] Waiting for shielding operation completion: {operationId}"); await Task.Delay(TimeSpan.FromSeconds(10), ct); } } private async Task ShieldCoinbaseEmulatedAsync(CancellationToken ct) { logger.Info(() => $"[{LogCategory}] Shielding ZCash Coinbase funds (emulated)"); // get t-addr unspent balance for just the coinbase address (pool wallet) var unspentResponse = await rpcClient.ExecuteAsync<Utxo[]>(logger, BitcoinCommands.ListUnspent, ct); if(unspentResponse.Error != null) { logger.Error(() => $"[{LogCategory}] {BitcoinCommands.ListUnspent} returned error: {unspentResponse.Error.Message} code {unspentResponse.Error.Code}"); return; } var balance = unspentResponse.Response .Where(x => x.Spendable && x.Address == poolConfig.Address) .Sum(x => x.Amount); // make sure there's enough balance to shield after reserves if(balance - TransferFee <= TransferFee) { logger.Info(() => $"[{LogCategory}] Balance {FormatAmount(balance)} too small for emulated shielding"); return; } logger.Info(() => $"[{LogCategory}] Transferring {FormatAmount(balance - TransferFee)} to pool's z-addr"); // transfer to z-addr var recipient = new ZSendManyRecipient { Address = poolExtraConfig.ZAddress, Amount = balance - TransferFee }; var args = new object[] { poolConfig.Address, // default account new object[] // addresses and associated amounts { recipient }, 1, TransferFee }; // send command var sendResponse = await rpcClient.ExecuteAsync<string>(logger, EquihashCommands.ZSendMany, ct, args); if(sendResponse.Error != null) { logger.Error(() => $"[{LogCategory}] {EquihashCommands.ZSendMany} returned error: {unspentResponse.Error.Message} code {unspentResponse.Error.Code}"); return; } var operationId = sendResponse.Response; logger.Info(() => $"[{LogCategory}] {EquihashCommands.ZSendMany} operation id: {operationId}"); var continueWaiting = true; while(continueWaiting) { var operationResultResponse = await rpcClient.ExecuteAsync<ZCashAsyncOperationStatus[]>(logger, EquihashCommands.ZGetOperationResult, ct, new object[] { new object[] { operationId } }); if(operationResultResponse.Error == null && operationResultResponse.Response?.Any(x => x.OperationId == operationId) == true) { var operationResult = operationResultResponse.Response.First(x => x.OperationId == operationId); if(!Enum.TryParse(operationResult.Status, true, out ZOperationStatus status)) { logger.Error(() => $"Unrecognized operation status: {operationResult.Status}"); break; } switch(status) { case ZOperationStatus.Success: var txId = operationResult.Result?.Value<string>("txid") ?? string.Empty; logger.Info(() => $"[{LogCategory}] Transfer completed with transaction id: {txId}"); continueWaiting = false; continue; case ZOperationStatus.Cancelled: case ZOperationStatus.Failed: logger.Error(() => $"{EquihashCommands.ZSendMany} failed: {operationResult.Error.Message} code {operationResult.Error.Code}"); continueWaiting = false; continue; } } logger.Info(() => $"[{LogCategory}] Waiting for shielding transfer completion: {operationId}"); await Task.Delay(TimeSpan.FromSeconds(10), ct); } } }
// 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 defines many COM dual interfaces which are legacy and, // cannot be changed. Tolerate possible obsoletion. // #pragma warning disable CS0618 // Type or member is obsolete namespace System.DirectoryServices.AccountManagement { using System.Runtime.InteropServices; using System; using System.Security; using System.Security.Permissions; using System.Text; internal class Constants { private Constants() { } internal static byte[] GUID_USERS_CONTAINER_BYTE = new byte[] { 0xa9, 0xd1, 0xca, 0x15, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd }; internal static byte[] GUID_COMPUTRS_CONTAINER_BYTE = new byte[] { 0xaa, 0x31, 0x28, 0x25, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd }; internal static byte[] GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = new byte[] { 0x22, 0xb7, 0x0c, 0x67, 0xd5, 0x6e, 0x4e, 0xfb, 0x91, 0xe9, 0x30, 0x0f, 0xca, 0x3d, 0xc1, 0xaa }; } internal class SafeNativeMethods { // To stop the compiler from autogenerating a constructor for this class private SafeNativeMethods() { } [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThreadId", CharSet = CharSet.Unicode)] static extern public int GetCurrentThreadId(); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)] static extern public int LsaNtStatusToWinError(int ntStatus); } internal class UnsafeNativeMethods { // To stop the compiler from autogenerating a constructor for this class private UnsafeNativeMethods() { } [DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject); public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject) { try { return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject); } catch (EntryPointNotFoundException) { throw new InvalidOperationException(SR.AdsiNotInstalled); } } // // ADSI Interopt // internal enum ADS_PASSWORD_ENCODING_ENUM { ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0, ADS_PASSWORD_ENCODE_CLEAR = 1 } internal enum ADS_OPTION_ENUM { ADS_OPTION_SERVERNAME = 0, ADS_OPTION_REFERRALS = 1, ADS_OPTION_PAGE_SIZE = 2, ADS_OPTION_SECURITY_MASK = 3, ADS_OPTION_MUTUAL_AUTH_STATUS = 4, ADS_OPTION_QUOTA = 5, ADS_OPTION_PASSWORD_PORTNUMBER = 6, ADS_OPTION_PASSWORD_METHOD = 7, ADS_OPTION_ACCUMULATIVE_MODIFICATION = 8, ADS_OPTION_SKIP_SID_LOOKUP = 9 } [ComImport, Guid("7E99C0A2-F935-11D2-BA96-00C04FB6D0D1"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IADsDNWithBinary { object BinaryValue { get; set; } string DNString { get; set; } } [ComImport, Guid("9068270b-0939-11D1-8be1-00c04fd8d503"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IADsLargeInteger { int HighPart { get; set; } int LowPart { get; set; } } [ComImport, Guid("927971f5-0939-11d1-8be1-00c04fd8d503")] public class ADsLargeInteger { } [ComImport, Guid("46f14fda-232b-11d1-a808-00c04fd8d5a8"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IAdsObjectOptions { [return: MarshalAs(UnmanagedType.Struct)] object GetOption( [In] int option); void PutOption( [In] int option, [In, MarshalAs(UnmanagedType.Struct)] object vProp); } [ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IADs { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string Class { [return: MarshalAs(UnmanagedType.BStr)] get; } string GUID { [return: MarshalAs(UnmanagedType.BStr)] get; } string ADsPath { [return: MarshalAs(UnmanagedType.BStr)] get; } string Parent { [return: MarshalAs(UnmanagedType.BStr)] get; } string Schema { [return: MarshalAs(UnmanagedType.BStr)] get; } void GetInfo(); void SetInfo(); [return: MarshalAs(UnmanagedType.Struct)] object Get( [In, MarshalAs(UnmanagedType.BStr)] string bstrName); void Put( [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] object vProp); [return: MarshalAs(UnmanagedType.Struct)] object GetEx( [In, MarshalAs(UnmanagedType.BStr)] string bstrName); void PutEx( [In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] object vProp); void GetInfoEx( [In, MarshalAs(UnmanagedType.Struct)] object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved); } [ComImport, Guid("27636b00-410f-11cf-b1ff-02608c9e7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IADsGroup { string Name { [return: MarshalAs(UnmanagedType.BStr)] get; } string Class { [return: MarshalAs(UnmanagedType.BStr)] get; } string GUID { [return: MarshalAs(UnmanagedType.BStr)] get; } string ADsPath { [return: MarshalAs(UnmanagedType.BStr)] get; } string Parent { [return: MarshalAs(UnmanagedType.BStr)] get; } string Schema { [return: MarshalAs(UnmanagedType.BStr)] get; } void GetInfo(); void SetInfo(); [return: MarshalAs(UnmanagedType.Struct)] object Get( [In, MarshalAs(UnmanagedType.BStr)] string bstrName); void Put( [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] object vProp); [return: MarshalAs(UnmanagedType.Struct)] object GetEx( [In, MarshalAs(UnmanagedType.BStr)] string bstrName); void PutEx( [In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In, MarshalAs(UnmanagedType.Struct)] object vProp); void GetInfoEx( [In, MarshalAs(UnmanagedType.Struct)] object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved); string Description { [return: MarshalAs(UnmanagedType.BStr)] get; [param: MarshalAs(UnmanagedType.BStr)] set; } IADsMembers Members(); bool IsMember([In, MarshalAs(UnmanagedType.BStr)] string bstrMember); void Add([In, MarshalAs(UnmanagedType.BStr)] string bstrNewItem); void Remove([In, MarshalAs(UnmanagedType.BStr)] string bstrItemToBeRemoved); } [ComImport, Guid("451a0030-72ec-11cf-b03b-00aa006e0975"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IADsMembers { int Count { [return: MarshalAs(UnmanagedType.U4)] get; } object _NewEnum { [return: MarshalAs(UnmanagedType.Interface)] get; } object Filter { [return: MarshalAs(UnmanagedType.Struct)] get; [param: MarshalAs(UnmanagedType.Struct)] set; } } [ComImport, Guid("080d0d78-f421-11d0-a36e-00c04fb950dc")] public class Pathname { } [ComImport, Guid("d592aed4-f420-11d0-a36e-00c04fb950dc"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] public interface IADsPathname { void Set( [In, MarshalAs(UnmanagedType.BStr)] string bstrADsPath, [In, MarshalAs(UnmanagedType.U4)] int lnSetType ); void SetDisplayType( [In, MarshalAs(UnmanagedType.U4)] int lnDisplayType ); [return: MarshalAs(UnmanagedType.BStr)] string Retrieve( [In, MarshalAs(UnmanagedType.U4)] int lnFormatType ); [return: MarshalAs(UnmanagedType.U4)] int GetNumElements(); [return: MarshalAs(UnmanagedType.BStr)] string GetElement( [In, MarshalAs(UnmanagedType.U4)] int lnElementIndex ); void AddLeafElement( [In, MarshalAs(UnmanagedType.BStr)] string bstrLeafElement ); void RemoveLeafElement(); [return: MarshalAs(UnmanagedType.Struct)] object CopyPath(); [return: MarshalAs(UnmanagedType.BStr)] string GetEscapedElement( [In, MarshalAs(UnmanagedType.U4)] int lnReserved, [In, MarshalAs(UnmanagedType.BStr)] string bstrInStr ); int EscapedMode { [return: MarshalAs(UnmanagedType.U4)] get; [param: MarshalAs(UnmanagedType.U4)] set; } } // // DSInteropt // /* typedef enum { DsRole_RoleStandaloneWorkstation, DsRole_RoleMemberWorkstation, DsRole_RoleStandaloneServer, DsRole_RoleMemberServer, DsRole_RoleBackupDomainController, DsRole_RolePrimaryDomainController, DsRole_WorkstationWithSharedAccountDomain, DsRole_ServerWithSharedAccountDomain, DsRole_MemberWorkstationWithSharedAccountDomain, DsRole_MemberServerWithSharedAccountDomain }DSROLE_MACHINE_ROLE; */ public enum DSROLE_MACHINE_ROLE { DsRole_RoleStandaloneWorkstation, DsRole_RoleMemberWorkstation, DsRole_RoleStandaloneServer, DsRole_RoleMemberServer, DsRole_RoleBackupDomainController, DsRole_RolePrimaryDomainController, DsRole_WorkstationWithSharedAccountDomain, DsRole_ServerWithSharedAccountDomain, DsRole_MemberWorkstationWithSharedAccountDomain, DsRole_MemberServerWithSharedAccountDomain } /* typedef enum { DsRolePrimaryDomainInfoBasic, DsRoleUpgradeStatus, DsRoleOperationState, DsRolePrimaryDomainInfoBasicEx }DSROLE_PRIMARY_DOMAIN_INFO_LEVEL; */ public enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL { DsRolePrimaryDomainInfoBasic = 1, DsRoleUpgradeStatus = 2, DsRoleOperationState = 3, DsRolePrimaryDomainInfoBasicEx = 4 } /* typedef struct _DSROLE_PRIMARY_DOMAIN_INFO_BASIC { DSROLE_MACHINE_ROLE MachineRole; ULONG Flags; LPWSTR DomainNameFlat; LPWSTR DomainNameDns; LPWSTR DomainForestName; GUID DomainGuid; } DSROLE_PRIMARY_DOMAIN_INFO_BASIC, *PDSROLE_PRIMARY_DOMAIN_INFO_BASIC; */ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC { public DSROLE_MACHINE_ROLE MachineRole; public uint Flags; [MarshalAs(UnmanagedType.LPWStr)] public string DomainNameFlat; [MarshalAs(UnmanagedType.LPWStr)] public string DomainNameDns; [MarshalAs(UnmanagedType.LPWStr)] public string DomainForestName; public Guid DomainGuid = new Guid(); } /* DWORD DsRoleGetPrimaryDomainInformation( LPCWSTR lpServer, DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, PBYTE* Buffer ); */ [DllImport("dsrole.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)] public static extern int DsRoleGetPrimaryDomainInformation( [MarshalAs(UnmanagedType.LPTStr)] string lpServer, [In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel, out IntPtr Buffer); /*typedef struct _DOMAIN_CONTROLLER_INFO { LPTSTR DomainControllerName; LPTSTR DomainControllerAddress; ULONG DomainControllerAddressType; GUID DomainGuid; LPTSTR DomainName; LPTSTR DnsForestName; ULONG Flags; LPTSTR DcSiteName; LPTSTR ClientSiteName; } DOMAIN_CONTROLLER_INFO, *PDOMAIN_CONTROLLER_INFO; */ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class DomainControllerInfo { public string DomainControllerName = null; public string DomainControllerAddress = null; public int DomainControllerAddressType = 0; public Guid DomainGuid = new Guid(); public string DomainName = null; public string DnsForestName = null; public int Flags = 0; public string DcSiteName = null; public string ClientSiteName = null; } /* void DsRoleFreeMemory( PVOID Buffer ); */ [DllImport("dsrole.dll")] public static extern int DsRoleFreeMemory( [In] IntPtr buffer); /*DWORD DsGetDcName( LPCTSTR ComputerName, LPCTSTR DomainName, GUID* DomainGuid, LPCTSTR SiteName, ULONG Flags, PDOMAIN_CONTROLLER_INFO* DomainControllerInfo );*/ [DllImport("logoncli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)] public static extern int DsGetDcName( [In] string computerName, [In] string domainName, [In] IntPtr domainGuid, [In] string siteName, [In] int flags, [Out] out IntPtr domainControllerInfo); /* typedef struct _WKSTA_INFO_100 { DWORD wki100_platform_id; LMSTR wki100_computername; LMSTR wki100_langroup; DWORD wki100_ver_major; DWORD wki100_ver_minor; } WKSTA_INFO_100, *PWKSTA_INFO_100; */ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class WKSTA_INFO_100 { public int wki100_platform_id = 0; public string wki100_computername = null; public string wki100_langroup = null; public int wki100_ver_major = 0; public int wki100_ver_minor = 0; }; [DllImport("wkscli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "NetWkstaGetInfo", CharSet = CharSet.Unicode)] public static extern int NetWkstaGetInfo(string server, int level, ref IntPtr buffer); [DllImport("netutils.dll")] public static extern int NetApiBufferFree( [In] IntPtr buffer); // // SID // [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode)] public static extern bool ConvertSidToStringSid(IntPtr sid, ref string stringSid); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode)] public static extern bool ConvertStringSidToSid(string stringSid, ref IntPtr sid); [DllImport("advapi32.dll")] public static extern int GetLengthSid(IntPtr sid); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool IsValidSid(IntPtr sid); [DllImport("advapi32.dll")] public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid); [DllImport("advapi32.dll")] public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index); [DllImport("advapi32.dll")] public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid); [DllImport("advapi32.dll")] public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource); [DllImport("kernel32.dll")] public static extern IntPtr LocalFree(IntPtr ptr); [DllImport("Credui.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "CredUIParseUserNameW", CharSet = CharSet.Unicode)] public static extern int CredUIParseUserName( string pszUserName, StringBuilder pszUser, uint ulUserMaxChars, StringBuilder pszDomain, uint ulDomainMaxChars ); // These contants were taken from the wincred.h file public const int CRED_MAX_USERNAME_LENGTH = 514; public const int CRED_MAX_DOMAIN_TARGET_LENGTH = 338; /* BOOL LookupAccountSid( LPCTSTR lpSystemName, PSID lpSid, LPTSTR lpName, LPDWORD cchName, LPTSTR lpReferencedDomainName, LPDWORD cchReferencedDomainName, PSID_NAME_USE peUse ); */ [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LookupAccountSidW", CharSet = CharSet.Unicode)] public static extern bool LookupAccountSid( string computerName, IntPtr sid, StringBuilder name, ref int nameLength, StringBuilder domainName, ref int domainNameLength, ref int usage); // // AuthZ functions // internal sealed class AUTHZ_RM_FLAG { private AUTHZ_RM_FLAG() { } public static int AUTHZ_RM_FLAG_NO_AUDIT = 0x1; public static int AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 0x2; public static int AUTHZ_VALID_RM_INIT_FLAGS = (AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION); } [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)] static extern public bool AuthzInitializeResourceManager( int flags, IntPtr pfnAccessCheck, IntPtr pfnComputeDynamicGroups, IntPtr pfnFreeDynamicGroups, string name, out IntPtr rm ); /* BOOL WINAPI AuthzInitializeContextFromSid( DWORD Flags, PSID UserSid, AUTHZ_RESOURCE_MANAGER_HANDLE AuthzResourceManager, PLARGE_INTEGER pExpirationTime, LUID Identifier, PVOID DynamicGroupArgs, PAUTHZ_CLIENT_CONTEXT_HANDLE pAuthzClientContext ); */ [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)] static extern public bool AuthzInitializeContextFromSid( int Flags, IntPtr UserSid, IntPtr AuthzResourceManager, IntPtr pExpirationTime, LUID Identitifier, IntPtr DynamicGroupArgs, out IntPtr pAuthzClientContext ); /* [DllImport("authz.dll", SetLastError=true, CallingConvention=CallingConvention.StdCall, EntryPoint="AuthzInitializeContextFromToken", CharSet=CharSet.Unicode)] static extern public bool AuthzInitializeContextFromToken( int Flags, IntPtr TokenHandle, IntPtr AuthzResourceManager, IntPtr pExpirationTime, LUID Identitifier, IntPtr DynamicGroupArgs, out IntPtr pAuthzClientContext ); */ [DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzGetInformationFromContext", CharSet = CharSet.Unicode)] static extern public bool AuthzGetInformationFromContext( IntPtr hAuthzClientContext, int InfoClass, int BufferSize, out int pSizeRequired, IntPtr Buffer ); [DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeContext", CharSet = CharSet.Unicode)] static extern public bool AuthzFreeContext( IntPtr AuthzClientContext ); [DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeResourceManager", CharSet = CharSet.Unicode)] static extern public bool AuthzFreeResourceManager( IntPtr rm ); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LUID { public int low; public int high; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class TOKEN_GROUPS { public int groupCount = 0; public IntPtr groups = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class SID_AND_ATTR { public IntPtr pSid = IntPtr.Zero; public int attrs = 0; } // // Token // [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class TOKEN_USER { public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR(); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class SID_IDENTIFIER_AUTHORITY { public byte b1 = 0; public byte b2 = 0; public byte b3 = 0; public byte b4 = 0; public byte b5 = 0; public byte b6 = 0; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class LSA_OBJECT_ATTRIBUTES { public int length = 0; public IntPtr rootDirectory = IntPtr.Zero; public IntPtr objectName = IntPtr.Zero; public int attributes = 0; public IntPtr securityDescriptor = IntPtr.Zero; public IntPtr securityQualityOfService = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class POLICY_ACCOUNT_DOMAIN_INFO { public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING(); public IntPtr domainSid = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class LSA_UNICODE_STRING { public ushort length = 0; public ushort maximumLength = 0; public IntPtr buffer = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class LSA_UNICODE_STRING_Managed { public ushort length = 0; public ushort maximumLength = 0; public string buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class LSA_TRANSLATED_NAME { public int use = 0; public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING(); public int domainIndex = 0; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class LSA_REFERENCED_DOMAIN_LIST { // To stop the compiler from autogenerating a constructor for this class private LSA_REFERENCED_DOMAIN_LIST() { } public int entries = 0; public IntPtr domains = IntPtr.Zero; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public sealed class LSA_TRUST_INFORMATION { public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING(); private IntPtr _pSid = IntPtr.Zero; } [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenThreadToken", CharSet = CharSet.Unicode)] static extern public bool OpenThreadToken( IntPtr threadHandle, int desiredAccess, bool openAsSelf, ref IntPtr tokenHandle ); [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenProcessToken", CharSet = CharSet.Unicode)] static extern public bool OpenProcessToken( IntPtr processHandle, int desiredAccess, ref IntPtr tokenHandle ); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "CloseHandle", CharSet = CharSet.Unicode)] static extern public bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)] static extern public IntPtr GetCurrentThread(); [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)] static extern public IntPtr GetCurrentProcess(); [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetTokenInformation", CharSet = CharSet.Unicode)] static extern public bool GetTokenInformation( IntPtr tokenHandle, int tokenInformationClass, IntPtr buffer, int bufferSize, ref int returnLength ); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaOpenPolicy", CharSet = CharSet.Unicode)] static extern public int LsaOpenPolicy( IntPtr lsaUnicodeString, IntPtr lsaObjectAttributes, int desiredAccess, ref IntPtr policyHandle); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)] static extern public int LsaQueryInformationPolicy( IntPtr policyHandle, int policyInformationClass, ref IntPtr buffer ); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaLookupSids", CharSet = CharSet.Unicode)] public static extern int LsaLookupSids( IntPtr policyHandle, int count, IntPtr[] sids, out IntPtr referencedDomains, out IntPtr names ); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaFreeMemory", CharSet = CharSet.Unicode)] static extern public int LsaFreeMemory(IntPtr buffer); [DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaClose", CharSet = CharSet.Unicode)] static extern public int LsaClose(IntPtr policyHandle); // // Impersonation // [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode)] static extern public int LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ImpersonateLoggedOnUser", CharSet = CharSet.Unicode)] static extern public int ImpersonateLoggedOnUser(IntPtr hToken); [DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "RevertToSelf", CharSet = CharSet.Unicode)] static extern public int RevertToSelf(); public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100, FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200, FORMAT_MESSAGE_FROM_STRING = 0x00000400, FORMAT_MESSAGE_FROM_HMODULE = 0x00000800, FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000, FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000, FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF; [DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] public static extern int FormatMessageW(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments); } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com) 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Collections.Generic; using System.IO; using System.Xml; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using Prebuild.Core.Utilities; namespace Prebuild.Core.Nodes { /// <summary> /// A set of values that the Project's type can be /// </summary> public enum ProjectType { /// <summary> /// The project is a console executable /// </summary> Exe, /// <summary> /// The project is a windows executable /// </summary> WinExe, /// <summary> /// The project is a library /// </summary> Library, /// <summary> /// The project is a website /// </summary> Web, } /// <summary> /// /// </summary> public enum ClrRuntime { /// <summary> /// /// </summary> Microsoft, /// <summary> /// /// </summary> Mono } /// <summary> /// The version of the .NET framework to use (Required for VS2008) /// <remarks>We don't need .NET 1.1 in here, it'll default when using vs2003.</remarks> /// </summary> public enum FrameworkVersion { /// <summary> /// .NET 2.0 /// </summary> v2_0, /// <summary> /// .NET 3.0 /// </summary> v3_0, /// <summary> /// .NET 3.5 /// </summary> v3_5, /// <summary> /// .NET 4.0 /// </summary> v4_0, /// <summary> /// .NET 4.5 /// </summary> v4_5, /// <summary> /// .NET 4.5.1 /// </summary> v4_5_1 } /// <summary> /// The Node object representing /Prebuild/Solution/Project elements /// </summary> [DataNode("Project")] public class ProjectNode : DataNode, IComparable { #region Fields private string m_Name = "unknown"; private string m_Path = ""; private string m_FullPath = ""; private string m_AssemblyName; private string m_AppIcon = ""; private string m_ConfigFile = ""; private string m_DesignerFolder = ""; private string m_Language = "C#"; private ProjectType m_Type = ProjectType.Exe; private ClrRuntime m_Runtime = ClrRuntime.Microsoft; private FrameworkVersion m_Framework = FrameworkVersion.v2_0; private string m_StartupObject = ""; private string m_RootNamespace; private string m_FilterGroups = ""; private string m_Version = ""; private Guid m_Guid; private string m_DebugStartParameters; private readonly Dictionary<string, ConfigurationNode> m_Configurations = new Dictionary<string, ConfigurationNode>(); private readonly List<ReferencePathNode> m_ReferencePaths = new List<ReferencePathNode>(); private readonly List<ReferenceNode> m_References = new List<ReferenceNode>(); private readonly List<AuthorNode> m_Authors = new List<AuthorNode>(); private FilesNode m_Files; #endregion #region Properties /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return m_Name; } } /// <summary> /// The version of the .NET Framework to compile under /// </summary> public FrameworkVersion FrameworkVersion { get { return m_Framework; } } /// <summary> /// Gets the path. /// </summary> /// <value>The path.</value> public string Path { get { return m_Path; } } /// <summary> /// Gets the filter groups. /// </summary> /// <value>The filter groups.</value> public string FilterGroups { get { return m_FilterGroups; } } /// <summary> /// Gets the project's version /// </summary> /// <value>The project's version.</value> public string Version { get { return m_Version; } } /// <summary> /// Gets the full path. /// </summary> /// <value>The full path.</value> public string FullPath { get { return m_FullPath; } } /// <summary> /// Gets the name of the assembly. /// </summary> /// <value>The name of the assembly.</value> public string AssemblyName { get { return m_AssemblyName; } } /// <summary> /// Gets the app icon. /// </summary> /// <value>The app icon.</value> public string AppIcon { get { return m_AppIcon; } } /// <summary> /// Gets the app icon. /// </summary> /// <value>The app icon.</value> public string ConfigFile { get { return m_ConfigFile; } } /// <summary> /// /// </summary> public string DesignerFolder { get { return m_DesignerFolder; } } /// <summary> /// Gets the language. /// </summary> /// <value>The language.</value> public string Language { get { return m_Language; } } /// <summary> /// Gets the type. /// </summary> /// <value>The type.</value> public ProjectType Type { get { return m_Type; } } /// <summary> /// Gets the runtime. /// </summary> /// <value>The runtime.</value> public ClrRuntime Runtime { get { return m_Runtime; } } private bool m_GenerateAssemblyInfoFile; /// <summary> /// /// </summary> public bool GenerateAssemblyInfoFile { get { return m_GenerateAssemblyInfoFile; } set { m_GenerateAssemblyInfoFile = value; } } /// <summary> /// Gets the startup object. /// </summary> /// <value>The startup object.</value> public string StartupObject { get { return m_StartupObject; } } /// <summary> /// Gets the root namespace. /// </summary> /// <value>The root namespace.</value> public string RootNamespace { get { return m_RootNamespace; } } /// <summary> /// Gets the configurations. /// </summary> /// <value>The configurations.</value> public List<ConfigurationNode> Configurations { get { List<ConfigurationNode> tmp = new List<ConfigurationNode>(ConfigurationsTable.Values); tmp.Sort(); return tmp; } } /// <summary> /// Gets the configurations table. /// </summary> /// <value>The configurations table.</value> public Dictionary<string, ConfigurationNode> ConfigurationsTable { get { return m_Configurations; } } /// <summary> /// Gets the reference paths. /// </summary> /// <value>The reference paths.</value> public List<ReferencePathNode> ReferencePaths { get { List<ReferencePathNode> tmp = new List<ReferencePathNode>(m_ReferencePaths); tmp.Sort(); return tmp; } } /// <summary> /// Gets the references. /// </summary> /// <value>The references.</value> public List<ReferenceNode> References { get { List<ReferenceNode> tmp = new List<ReferenceNode>(m_References); tmp.Sort(); return tmp; } } /// <summary> /// Gets the Authors list. /// </summary> /// <value>The list of the project's authors.</value> public List<AuthorNode> Authors { get { return m_Authors; } } /// <summary> /// Gets the files. /// </summary> /// <value>The files.</value> public FilesNode Files { get { return m_Files; } } /// <summary> /// Gets or sets the parent. /// </summary> /// <value>The parent.</value> public override IDataNode Parent { get { return base.Parent; } set { base.Parent = value; if(base.Parent is SolutionNode && m_Configurations.Count < 1) { SolutionNode parent = (SolutionNode)base.Parent; foreach(ConfigurationNode conf in parent.Configurations) { m_Configurations[conf.NameAndPlatform] = (ConfigurationNode) conf.Clone(); } } } } /// <summary> /// Gets the GUID. /// </summary> /// <value>The GUID.</value> public Guid Guid { get { return m_Guid; } } public string DebugStartParameters { get { return m_DebugStartParameters; } } #endregion #region Private Methods private void HandleConfiguration(ConfigurationNode conf) { if(String.Compare(conf.Name, "all", true) == 0) //apply changes to all, this may not always be applied first, //so it *may* override changes to the same properties for configurations defines at the project level { foreach(ConfigurationNode confNode in m_Configurations.Values) { conf.CopyTo(confNode);//update the config templates defines at the project level with the overrides } } if(m_Configurations.ContainsKey(conf.NameAndPlatform)) { ConfigurationNode parentConf = m_Configurations[conf.NameAndPlatform]; conf.CopyTo(parentConf);//update the config templates defines at the project level with the overrides } else { m_Configurations[conf.NameAndPlatform] = conf; } } #endregion #region Public Methods /// <summary> /// Parses the specified node. /// </summary> /// <param name="node">The node.</param> public override void Parse(XmlNode node) { m_Name = Helper.AttributeValue(node, "name", m_Name); m_Path = Helper.AttributeValue(node, "path", m_Path); m_FilterGroups = Helper.AttributeValue(node, "filterGroups", m_FilterGroups); m_Version = Helper.AttributeValue(node, "version", m_Version); m_AppIcon = Helper.AttributeValue(node, "icon", m_AppIcon); m_ConfigFile = Helper.AttributeValue(node, "configFile", m_ConfigFile); m_DesignerFolder = Helper.AttributeValue(node, "designerFolder", m_DesignerFolder); m_AssemblyName = Helper.AttributeValue(node, "assemblyName", m_AssemblyName); m_Language = Helper.AttributeValue(node, "language", m_Language); m_Type = (ProjectType)Helper.EnumAttributeValue(node, "type", typeof(ProjectType), m_Type); m_Runtime = (ClrRuntime)Helper.EnumAttributeValue(node, "runtime", typeof(ClrRuntime), m_Runtime); m_Framework = (FrameworkVersion)Helper.EnumAttributeValue(node, "frameworkVersion", typeof(FrameworkVersion), m_Framework); m_StartupObject = Helper.AttributeValue(node, "startupObject", m_StartupObject); m_RootNamespace = Helper.AttributeValue(node, "rootNamespace", m_RootNamespace); int hash = m_Name.GetHashCode(); Guid guidByHash = new Guid(hash, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); string guid = Helper.AttributeValue(node, "guid", guidByHash.ToString()); m_Guid = new Guid(guid); m_GenerateAssemblyInfoFile = Helper.ParseBoolean(node, "generateAssemblyInfoFile", false); m_DebugStartParameters = Helper.AttributeValue(node, "debugStartParameters", string.Empty); if(string.IsNullOrEmpty(m_AssemblyName)) { m_AssemblyName = m_Name; } if(string.IsNullOrEmpty(m_RootNamespace)) { m_RootNamespace = m_Name; } m_FullPath = m_Path; try { m_FullPath = Helper.ResolvePath(m_FullPath); } catch { throw new WarningException("Could not resolve Solution path: {0}", m_Path); } Kernel.Instance.CurrentWorkingDirectory.Push(); try { Helper.SetCurrentDir(m_FullPath); if( node == null ) { throw new ArgumentNullException("node"); } foreach(XmlNode child in node.ChildNodes) { IDataNode dataNode = Kernel.Instance.ParseNode(child, this); if(dataNode is ConfigurationNode) { HandleConfiguration((ConfigurationNode)dataNode); } else if(dataNode is ReferencePathNode) { m_ReferencePaths.Add((ReferencePathNode)dataNode); } else if(dataNode is ReferenceNode) { m_References.Add((ReferenceNode)dataNode); } else if(dataNode is AuthorNode) { m_Authors.Add((AuthorNode)dataNode); } else if(dataNode is FilesNode) { m_Files = (FilesNode)dataNode; } } } finally { Kernel.Instance.CurrentWorkingDirectory.Pop(); } } #endregion #region IComparable Members public int CompareTo(object obj) { ProjectNode that = (ProjectNode)obj; return m_Name.CompareTo(that.m_Name); } #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.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Razor.Language.CodeGeneration; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Razor; using Xunit; using Xunit.Sdk; namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests { public class RazorIntegrationTestBase { internal const string ArbitraryWindowsPath = "x:\\dir\\subdir\\Test"; internal const string ArbitraryMacLinuxPath = "/dir/subdir/Test"; // Creating the initial compilation + reading references is on the order of 250ms without caching // so making sure it doesn't happen for each test. protected static readonly CSharpCompilation DefaultBaseCompilation; private static CSharpParseOptions CSharpParseOptions { get; } static RazorIntegrationTestBase() { var referenceAssemblyRoots = new[] { typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).Assembly, // System.Runtime typeof(Enumerable).Assembly, // Other .NET fundamental types typeof(System.Linq.Expressions.Expression).Assembly, typeof(ComponentBase).Assembly, }; var referenceAssemblies = referenceAssemblyRoots .SelectMany(assembly => assembly.GetReferencedAssemblies().Concat(new[] { assembly.GetName() })) .Distinct() .Select(Assembly.Load) .Select(assembly => MetadataReference.CreateFromFile(assembly.Location)) .ToList(); DefaultBaseCompilation = CSharpCompilation.Create( "TestAssembly", Array.Empty<SyntaxTree>(), referenceAssemblies, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); CSharpParseOptions = new CSharpParseOptions(LanguageVersion.Preview); } public RazorIntegrationTestBase() { AdditionalSyntaxTrees = new List<SyntaxTree>(); AdditionalRazorItems = new List<RazorProjectItem>(); ImportItems = new List<RazorProjectItem>(); BaseCompilation = DefaultBaseCompilation; Configuration = RazorConfiguration.Default; FileSystem = new VirtualRazorProjectFileSystem(); PathSeparator = Path.DirectorySeparatorChar.ToString(); WorkingDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ArbitraryWindowsPath : ArbitraryMacLinuxPath; DefaultRootNamespace = "Test"; // Matches the default working directory DefaultFileName = "TestComponent.cshtml"; } internal List<RazorProjectItem> AdditionalRazorItems { get; } internal List<RazorProjectItem> ImportItems { get; } internal List<SyntaxTree> AdditionalSyntaxTrees { get; } internal virtual CSharpCompilation BaseCompilation { get; } internal virtual RazorConfiguration Configuration { get; } internal virtual string DefaultRootNamespace { get; } internal virtual string DefaultFileName { get; } internal virtual bool DesignTime { get; } internal virtual bool DeclarationOnly { get; } /// <summary> /// Gets a hardcoded document kind to be added to each code document that's created. This can /// be used to generate components. /// </summary> internal virtual string FileKind { get; } internal virtual VirtualRazorProjectFileSystem FileSystem { get; } // Used to force a specific style of line-endings for testing. This matters // for the baseline tests that exercise line mappings. Even though we normalize // newlines for testing, the difference between platforms affects the data through // the *count* of characters written. internal virtual string LineEnding { get; } internal virtual string PathSeparator { get; } internal virtual bool NormalizeSourceLineEndings { get; } internal virtual bool UseTwoPhaseCompilation { get; } internal virtual string WorkingDirectory { get; } // intentionally private - we don't want individual tests messing with the project engine private RazorProjectEngine CreateProjectEngine(RazorConfiguration configuration, MetadataReference[] references, bool supportLocalizedComponentNames) { return RazorProjectEngine.Create(configuration, FileSystem, b => { b.SetRootNamespace(DefaultRootNamespace); // Turn off checksums, we're testing code generation. b.Features.Add(new SuppressChecksum()); if (supportLocalizedComponentNames) { b.Features.Add(new SupportLocalizedComponentNames()); } b.Features.Add(new TestImportProjectFeature(ImportItems)); if (LineEnding != null) { b.Phases.Insert(0, new ForceLineEndingPhase(LineEnding)); } b.Features.Add(new CompilationTagHelperFeature()); b.Features.Add(new DefaultMetadataReferenceFeature() { References = references, }); b.SetCSharpLanguageVersion(CSharpParseOptions.LanguageVersion); CompilerFeatures.Register(b); }); } internal RazorProjectItem CreateProjectItem(string cshtmlRelativePath, string cshtmlContent, string fileKind = null, string cssScope = null) { var fullPath = WorkingDirectory + PathSeparator + cshtmlRelativePath; // FilePaths in Razor are **always** are of the form '/a/b/c.cshtml' var filePath = cshtmlRelativePath.Replace('\\', '/'); if (!filePath.StartsWith("/", StringComparison.Ordinal)) { filePath = '/' + filePath; } if (NormalizeSourceLineEndings) { cshtmlContent = cshtmlContent.Replace("\r", "").Replace("\n", LineEnding); } return new TestRazorProjectItem( filePath: filePath, physicalPath: fullPath, relativePhysicalPath: cshtmlRelativePath, basePath: WorkingDirectory, fileKind: fileKind ?? FileKind, cssScope: cssScope) { Content = cshtmlContent.TrimStart(), }; } protected CompileToCSharpResult CompileToCSharp(string cshtmlContent, bool throwOnFailure=true, string cssScope = null, bool supportLocalizedComponentNames = false) { return CompileToCSharp(DefaultFileName, cshtmlContent, throwOnFailure, cssScope: cssScope, supportLocalizedComponentNames: supportLocalizedComponentNames); } protected CompileToCSharpResult CompileToCSharp(string cshtmlRelativePath, string cshtmlContent, bool throwOnFailure = true, string fileKind = null, string cssScope = null, bool supportLocalizedComponentNames = false) { if (DeclarationOnly && DesignTime) { throw new InvalidOperationException($"{nameof(DeclarationOnly)} cannot be used with {nameof(DesignTime)}."); } if (DeclarationOnly && UseTwoPhaseCompilation) { throw new InvalidOperationException($"{nameof(DeclarationOnly)} cannot be used with {nameof(UseTwoPhaseCompilation)}."); } if (UseTwoPhaseCompilation) { // The first phase won't include any metadata references for component discovery. This mirrors // what the build does. var projectEngine = CreateProjectEngine(Configuration, Array.Empty<MetadataReference>(), supportLocalizedComponentNames); RazorCodeDocument codeDocument; foreach (var item in AdditionalRazorItems) { // Result of generating declarations codeDocument = projectEngine.ProcessDeclarationOnly(item); Assert.Empty(codeDocument.GetCSharpDocument().Diagnostics); var syntaxTree = Parse(codeDocument.GetCSharpDocument().GeneratedCode, path: item.FilePath); AdditionalSyntaxTrees.Add(syntaxTree); } // Result of generating declarations var projectItem = CreateProjectItem(cshtmlRelativePath, cshtmlContent, fileKind, cssScope); codeDocument = projectEngine.ProcessDeclarationOnly(projectItem); var declaration = new CompileToCSharpResult { BaseCompilation = BaseCompilation.AddSyntaxTrees(AdditionalSyntaxTrees), CodeDocument = codeDocument, Code = codeDocument.GetCSharpDocument().GeneratedCode, Diagnostics = codeDocument.GetCSharpDocument().Diagnostics, }; // Result of doing 'temp' compilation var tempAssembly = CompileToAssembly(declaration, throwOnFailure); // Add the 'temp' compilation as a metadata reference var references = BaseCompilation.References.Concat(new[] { tempAssembly.Compilation.ToMetadataReference() }).ToArray(); projectEngine = CreateProjectEngine(Configuration, references, supportLocalizedComponentNames); // Now update the any additional files foreach (var item in AdditionalRazorItems) { // Result of generating definition codeDocument = DesignTime ? projectEngine.ProcessDesignTime(item) : projectEngine.Process(item); Assert.Empty(codeDocument.GetCSharpDocument().Diagnostics); // Replace the 'declaration' syntax tree var syntaxTree = Parse(codeDocument.GetCSharpDocument().GeneratedCode, path: item.FilePath); AdditionalSyntaxTrees.RemoveAll(st => st.FilePath == item.FilePath); AdditionalSyntaxTrees.Add(syntaxTree); } // Result of real code generation for the document under test codeDocument = DesignTime ? projectEngine.ProcessDesignTime(projectItem) : projectEngine.Process(projectItem); return new CompileToCSharpResult { BaseCompilation = BaseCompilation.AddSyntaxTrees(AdditionalSyntaxTrees), CodeDocument = codeDocument, Code = codeDocument.GetCSharpDocument().GeneratedCode, Diagnostics = codeDocument.GetCSharpDocument().Diagnostics, }; } else { // For single phase compilation tests just use the base compilation's references. // This will include the built-in components. var projectEngine = CreateProjectEngine(Configuration, BaseCompilation.References.ToArray(), supportLocalizedComponentNames); var projectItem = CreateProjectItem(cshtmlRelativePath, cshtmlContent, fileKind, cssScope); RazorCodeDocument codeDocument; if (DeclarationOnly) { codeDocument = projectEngine.ProcessDeclarationOnly(projectItem); } else if (DesignTime) { codeDocument = projectEngine.ProcessDesignTime(projectItem); } else { codeDocument = projectEngine.Process(projectItem); } return new CompileToCSharpResult { BaseCompilation = BaseCompilation.AddSyntaxTrees(AdditionalSyntaxTrees), CodeDocument = codeDocument, Code = codeDocument.GetCSharpDocument().GeneratedCode, Diagnostics = codeDocument.GetCSharpDocument().Diagnostics, }; } } protected CompileToAssemblyResult CompileToAssembly(string cshtmlRelativePath, string cshtmlContent) { var cSharpResult = CompileToCSharp(cshtmlRelativePath, cshtmlContent); return CompileToAssembly(cSharpResult); } protected CompileToAssemblyResult CompileToAssembly(CompileToCSharpResult cSharpResult, bool throwOnFailure = true) { if (cSharpResult.Diagnostics.Any() && throwOnFailure) { var diagnosticsLog = string.Join(Environment.NewLine, cSharpResult.Diagnostics.Select(d => d.ToString()).ToArray()); throw new InvalidOperationException($"Aborting compilation to assembly because RazorCompiler returned nonempty diagnostics: {diagnosticsLog}"); } var syntaxTrees = new[] { Parse(cSharpResult.Code), }; var compilation = cSharpResult.BaseCompilation.AddSyntaxTrees(syntaxTrees); var diagnostics = compilation .GetDiagnostics() .Where(d => d.Severity != DiagnosticSeverity.Hidden); if (diagnostics.Any() && throwOnFailure) { throw new CompilationFailedException(compilation); } else if (diagnostics.Any()) { return new CompileToAssemblyResult { Compilation = compilation, Diagnostics = diagnostics, }; } using (var peStream = new MemoryStream()) { compilation.Emit(peStream); return new CompileToAssemblyResult { Compilation = compilation, Diagnostics = diagnostics, Assembly = diagnostics.Any() ? null : Assembly.Load(peStream.ToArray()) }; } } protected IComponent CompileToComponent(string cshtmlSource) { var assemblyResult = CompileToAssembly(DefaultFileName, cshtmlSource); var componentFullTypeName = $"{DefaultRootNamespace}.{Path.GetFileNameWithoutExtension(DefaultFileName)}"; return CompileToComponent(assemblyResult, componentFullTypeName); } protected IComponent CompileToComponent(CompileToCSharpResult cSharpResult, string fullTypeName) { return CompileToComponent(CompileToAssembly(cSharpResult), fullTypeName); } protected IComponent CompileToComponent(CompileToAssemblyResult assemblyResult, string fullTypeName) { var componentType = assemblyResult.Assembly.GetType(fullTypeName); if (componentType == null) { throw new XunitException( $"Failed to find component type '{fullTypeName}'. Found types:" + Environment.NewLine + string.Join(Environment.NewLine, assemblyResult.Assembly.ExportedTypes.Select(t => t.FullName))); } return (IComponent)Activator.CreateInstance(componentType); } protected static CSharpSyntaxTree Parse(string text, string path = null) { return (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(text, CSharpParseOptions, path: path); } protected static string FullTypeName<T>() => typeof(T).FullName.Replace('+', '.'); protected static void AssertSourceEquals(string expected, CompileToCSharpResult generated) { // Normalize the paths inside the expected result to match the OS paths if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var windowsPath = Path.Combine(ArbitraryWindowsPath, generated.CodeDocument.Source.RelativePath).Replace('/', '\\'); expected = expected.Replace(windowsPath, generated.CodeDocument.Source.FilePath); } expected = expected.Trim(); Assert.Equal(expected, generated.Code.Trim(), ignoreLineEndingDifferences: true); } protected class CompileToCSharpResult { // A compilation that can be used *with* this code to compile an assembly public Compilation BaseCompilation { get; set; } public RazorCodeDocument CodeDocument { get; set; } public string Code { get; set; } public IEnumerable<RazorDiagnostic> Diagnostics { get; set; } } protected class CompileToAssemblyResult { public Assembly Assembly { get; set; } public Compilation Compilation { get; set; } public string VerboseLog { get; set; } public IEnumerable<Diagnostic> Diagnostics { get; set; } } private class CompilationFailedException : XunitException { public CompilationFailedException(Compilation compilation) { Compilation = compilation; } public Compilation Compilation { get; } public override string Message { get { var builder = new StringBuilder(); builder.AppendLine("Compilation failed: "); var diagnostics = Compilation.GetDiagnostics(); var syntaxTreesWithErrors = new HashSet<SyntaxTree>(); foreach (var diagnostic in diagnostics) { builder.AppendLine(diagnostic.ToString()); if (diagnostic.Location.IsInSource) { syntaxTreesWithErrors.Add(diagnostic.Location.SourceTree); } } if (syntaxTreesWithErrors.Any()) { builder.AppendLine(); builder.AppendLine(); foreach (var syntaxTree in syntaxTreesWithErrors) { builder.AppendLine($"File {syntaxTree.FilePath ?? "unknown"}:"); builder.AppendLine(syntaxTree.GetText().ToString()); } } return builder.ToString(); } } } private class SuppressChecksum : IConfigureRazorCodeGenerationOptionsFeature { public int Order => 0; public RazorEngine Engine { get; set; } public void Configure(RazorCodeGenerationOptionsBuilder options) { options.SuppressChecksum = true; } } private class SupportLocalizedComponentNames : IConfigureRazorCodeGenerationOptionsFeature { public int Order => 0; public RazorEngine Engine { get; set; } public void Configure(RazorCodeGenerationOptionsBuilder options) { options.SupportLocalizedComponentNames = true; } } private class ForceLineEndingPhase : RazorEnginePhaseBase { public ForceLineEndingPhase(string lineEnding) { LineEnding = lineEnding; } public string LineEnding { get; } protected override void ExecuteCore(RazorCodeDocument codeDocument) { var field = typeof(CodeRenderingContext).GetField("NewLineString", BindingFlags.Static | BindingFlags.NonPublic); var key = field.GetValue(null); codeDocument.Items[key] = LineEnding; } } private class TestImportProjectFeature : IImportProjectFeature { private readonly List<RazorProjectItem> _imports; public TestImportProjectFeature(List<RazorProjectItem> imports) { _imports = imports; } public RazorProjectEngine ProjectEngine { get; set; } public IReadOnlyList<RazorProjectItem> GetImports(RazorProjectItem projectItem) { return _imports; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { private sealed class CurlResponseMessage : HttpResponseMessage { internal uint _headerBytesReceived; internal CurlResponseMessage(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null EasyRequest"); RequestMessage = easy._requestMessage; ResponseStream = new CurlResponseStream(easy); Content = new NoWriteNoSeekStreamContent(ResponseStream, CancellationToken.None); // On Windows, we pass the equivalent of the easy._cancellationToken // in to StreamContent's ctor. This in turn passes that token through // to ReadAsync operations on the stream response stream when HttpClient // reads from the response stream to buffer it with ResponseContentRead. // We don't need to do that here in the Unix implementation as, until the // SendAsync task completes, the handler will have registered with the // CancellationToken with an action that will cancel all work related to // the easy handle if cancellation occurs, and that includes canceling any // pending reads on the response stream. It wouldn't hurt anything functionally // to still pass easy._cancellationToken here, but it will increase costs // a bit, as each read will then need to allocate a larger state object as // well as register with and unregister from the cancellation token. } internal CurlResponseStream ResponseStream { get; } } /// <summary> /// Provides a response stream that allows libcurl to transfer data asynchronously to a reader. /// When writing data to the response stream, either all or none of the data will be transferred, /// and if none, libcurl will pause the connection until a reader is waiting to consume the data. /// Readers consume the data via ReadAsync, which registers a read state with the stream, to be /// filled in by a pending write. Read is just a thin wrapper around ReadAsync, since the underlying /// mechanism must be asynchronous to prevent blocking libcurl's processing. /// </summary> private sealed class CurlResponseStream : Stream { /// <summary>A cached task storing the Int32 value 0.</summary> private static readonly Task<int> s_zeroTask = Task.FromResult(0); /// <summary> /// A sentinel object used in the <see cref="_completed"/> field to indicate that /// the stream completed successfully. /// </summary> private static readonly Exception s_completionSentinel = new Exception("s_completionSentinel"); /// <summary>A object used to synchronize all access to state on this response stream.</summary> private readonly object _lockObject = new object(); /// <summary>The associated EasyRequest.</summary> private readonly EasyRequest _easy; /// <summary>Stores whether Dispose has been called on the stream.</summary> private bool _disposed = false; /// <summary> /// Null if the Stream has not been completed, non-null if it has been completed. /// If non-null, it'll either be the <see cref="s_completionSentinel"/> object, meaning the stream completed /// successfully, or it'll be an Exception object representing the error that caused completion. /// That error will be transferred to any subsequent read requests. /// </summary> private Exception _completed; /// <summary> /// The state associated with a pending read request. When a reader requests data, it puts /// its state here for the writer to fill in when data is available. /// </summary> private ReadState _pendingReadRequest; /// <summary> /// When data is provided by libcurl, it must be consumed all or nothing: either all of the data is consumed, or /// we must pause the connection. Since a read could need to be satisfied with only some of the data provided, /// we store the rest here until all reads can consume it. If a subsequent write callback comes in to provide /// more data, the connection will then be paused until this buffer is entirely consumed. /// </summary> private byte[] _remainingData; /// <summary> /// The offset into <see cref="_remainingData"/> from which the next read should occur. /// </summary> private int _remainingDataOffset; /// <summary> /// The remaining number of bytes in <see cref="_remainingData"/> available to be read. /// </summary> private int _remainingDataCount; internal CurlResponseStream(EasyRequest easy) { Debug.Assert(easy != null, "Expected non-null associated EasyRequest"); _easy = easy; } public override bool CanRead => !_disposed; public override bool CanWrite => false; public override bool CanSeek => false; public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } public override void Flush() { // Nothing to do. } /// <summary> /// Writes the <paramref name="length"/> bytes starting at <paramref name="pointer"/> to the stream. /// </summary> /// <returns> /// <paramref name="length"/> if all of the data was written, or /// <see cref="Interop.libcurl.CURL_WRITEFUNC_PAUSE"/> if the data wasn't copied and the connection /// should be paused until a reader is available. /// </returns> internal ulong TransferDataToResponseStream(IntPtr pointer, long length) { Debug.Assert(pointer != IntPtr.Zero, "Expected a non-null pointer"); Debug.Assert(length >= 0, "Expected a non-negative length"); EventSourceTrace("Length: {0}", length); CheckDisposed(); // If there's no data to write, consider everything transferred. if (length == 0) { return 0; } lock (_lockObject) { VerifyInvariants(); // If there's existing data in the remaining data buffer, or if there's no pending read request, // we need to pause until the existing data is consumed or until there's a waiting read. if (_remainingDataCount > 0) { EventSourceTrace("Pausing transfer to response stream. Remaining bytes: {0}", _remainingDataCount); return Interop.Http.CURL_WRITEFUNC_PAUSE; } else if (_pendingReadRequest == null) { EventSourceTrace("Pausing transfer to response stream. No pending read request"); return Interop.Http.CURL_WRITEFUNC_PAUSE; } // There's no data in the buffer and there is a pending read request. // Transfer as much data as we can to the read request, completing it. int numBytesForTask = (int)Math.Min(length, _pendingReadRequest._count); Debug.Assert(numBytesForTask > 0, "We must be copying a positive amount."); Marshal.Copy(pointer, _pendingReadRequest._buffer, _pendingReadRequest._offset, numBytesForTask); EventSourceTrace("Completing pending read with {0} bytes", numBytesForTask); _pendingReadRequest.SetResult(numBytesForTask); ClearPendingReadRequest(); // If there's any data left, transfer it to our remaining buffer. libcurl does not support // partial transfers of data, so since we just took some of it to satisfy the read request // we must take the rest of it. (If libcurl then comes back to us subsequently with more data // before this buffered data has been consumed, at that point we won't consume any of the // subsequent offering and will ask libcurl to pause.) if (numBytesForTask < length) { IntPtr remainingPointer = pointer + numBytesForTask; _remainingDataCount = checked((int)(length - numBytesForTask)); _remainingDataOffset = 0; // Make sure our remaining data buffer exists and is big enough to hold the data if (_remainingData == null) { _remainingData = new byte[_remainingDataCount]; } else if (_remainingData.Length < _remainingDataCount) { _remainingData = new byte[Math.Max(_remainingData.Length * 2, _remainingDataCount)]; } // Copy the remaining data to the buffer EventSourceTrace("Storing {0} bytes for later", _remainingDataCount); Marshal.Copy(remainingPointer, _remainingData, 0, _remainingDataCount); } // All of the data from libcurl was consumed. return (ulong)length; } } public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (offset > buffer.Length - count) throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer)); CheckDisposed(); EventSourceTrace("Buffer: {0}, Offset: {1}, Count: {2}", buffer.Length, offset, count); // Check for cancellation if (cancellationToken.IsCancellationRequested) { EventSourceTrace("Canceled"); return Task.FromCanceled<int>(cancellationToken); } lock (_lockObject) { VerifyInvariants(); // If there's currently a pending read, fail this read, as we don't support concurrent reads. if (_pendingReadRequest != null) { EventSourceTrace("Failing due to existing pending read; concurrent reads not supported."); return Task.FromException<int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)); } // If the stream was already completed with failure, complete the read as a failure. if (_completed != null && _completed != s_completionSentinel) { EventSourceTrace("Failing read with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; return (oce != null && oce.CancellationToken.IsCancellationRequested) ? Task.FromCanceled<int>(oce.CancellationToken) : Task.FromException<int>(MapToReadWriteIOException(_completed, isRead: true)); } // Quick check for if no data was actually requested. We do this after the check // for errors so that we can still fail the read and transfer the exception if we should. if (count == 0) { return s_zeroTask; } // If there's any data left over from a previous call, grab as much as we can. if (_remainingDataCount > 0) { int bytesToCopy = Math.Min(count, _remainingDataCount); Buffer.BlockCopy(_remainingData, _remainingDataOffset, buffer, offset, bytesToCopy); _remainingDataOffset += bytesToCopy; _remainingDataCount -= bytesToCopy; Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative"); Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size"); EventSourceTrace("Read {0} bytes", bytesToCopy); return Task.FromResult(bytesToCopy); } // If the stream has already been completed, complete the read immediately. if (_completed == s_completionSentinel) { EventSourceTrace("Stream already completed"); return s_zeroTask; } // Finally, the stream is still alive, and we want to read some data, but there's no data // in the buffer so we need to register ourself to get the next write. if (cancellationToken.CanBeCanceled) { // If the cancellation token is cancelable, then we need to register for cancellation. // We create a special CancelableReadState that carries with it additional info: // the cancellation token and the registration with that token. When cancellation // is requested, we schedule a work item that tries to remove the read state // from being pending, canceling it in the process. This needs to happen under the // lock, which is why we schedule the operation to run asynchronously: if it ran // synchronously, it could deadlock due to code on another thread holding the lock // and calling Dispose on the registration concurrently with the call to Cancel // the cancellation token. Dispose on the registration won't return until the action // associated with the registration has completed, but if that action is currently // executing and is blocked on the lock that's held while calling Dispose... deadlock. var crs = new CancelableReadState(buffer, offset, count, this, cancellationToken); crs._registration = cancellationToken.Register(s1 => { ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state"); Task.Factory.StartNew(s2 => { var crsRef = (CancelableReadState)s2; Debug.Assert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested."); lock (crsRef._stream._lockObject) { if (crsRef._stream._pendingReadRequest == crsRef) { crsRef._stream.EventSourceTrace("Canceling"); crsRef.TrySetCanceled(crsRef._token); crsRef._stream.ClearPendingReadRequest(); } } }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); }, crs); _pendingReadRequest = crs; } else { // The token isn't cancelable. Just create a normal read state. _pendingReadRequest = new ReadState(buffer, offset, count); } _easy._associatedMultiAgent.RequestUnpause(_easy); _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read return _pendingReadRequest.Task; } } /// <summary>Notifies the stream that no more data will be written.</summary> internal void SignalComplete(Exception error = null, bool forceCancel = false) { lock (_lockObject) { VerifyInvariants(); // If we already completed, nothing more to do if (_completed != null) { EventSourceTrace("Already completed"); return; } // Mark ourselves as being completed EventSourceTrace("Marking as complete"); _completed = error ?? s_completionSentinel; // If the request wasn't already completed, and if requested, send a cancellation // request to ensure that the connection gets cleaned up. This is only necessary // to do if this method is being called for a reason other than the request/response // completing naturally, e.g. if the response stream is being disposed of before // all of the response has been downloaded. if (forceCancel) { EventSourceTrace("Completing the response stream prematurely."); _easy._associatedMultiAgent.RequestCancel(_easy); } // If there's a pending read request, complete it, either with 0 bytes for success // or with the exception/CancellationToken for failure. if (_pendingReadRequest != null) { if (_completed == s_completionSentinel) { EventSourceTrace("Completing pending read with 0 bytes"); _pendingReadRequest.TrySetResult(0); } else { EventSourceTrace("Failing pending read task with error: {0}", _completed); OperationCanceledException oce = _completed as OperationCanceledException; if (oce != null) { _pendingReadRequest.TrySetCanceled(oce.CancellationToken); } else { _pendingReadRequest.TrySetException(MapToReadWriteIOException(_completed, isRead: true)); } } ClearPendingReadRequest(); } } } /// <summary> /// Clears a pending read request, making sure any cancellation registration is unregistered and /// ensuring that the EasyRequest has dropped its strong reference to itself, which should only /// exist while an active async operation is going. /// </summary> private void ClearPendingReadRequest() { Debug.Assert(Monitor.IsEntered(_lockObject), "Lock object must be held to manipulate _pendingReadRequest"); Debug.Assert(_pendingReadRequest != null, "Should only be clearing the pending read request if there is one"); Debug.Assert(_pendingReadRequest.Task.IsCompleted, "The pending request should have been completed"); (_pendingReadRequest as CancelableReadState)?._registration.Dispose(); _pendingReadRequest = null; // The async operation has completed. We no longer want to be holding a strong reference. _easy._selfStrongToWeakReference.MakeWeak(); } ~CurlResponseStream() { Dispose(disposing: false); } protected override void Dispose(bool disposing) { // disposing is ignored. We need to SignalComplete whether this is due to Dispose // or due to finalization, so that we don't leave Tasks uncompleted, don't leave // connections paused, etc. if (!_disposed) { EventSourceTrace("Disposing response stream"); _disposed = true; SignalComplete(forceCancel: true); } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, agent: null, easy: _easy, memberName: memberName); } private void EventSourceTrace<TArg0, TArg1, TArg2>(string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(formatMessage, arg0, arg1, arg2, agent: null, easy: _easy, memberName: memberName); } private void EventSourceTrace(string message, [CallerMemberName] string memberName = null) { CurlHandler.EventSourceTrace(message, agent: null, easy: _easy, memberName: memberName); } /// <summary>Verifies various invariants that must be true about our state.</summary> [Conditional("DEBUG")] private void VerifyInvariants() { Debug.Assert(Monitor.IsEntered(_lockObject), "Can only verify invariants while holding the lock"); Debug.Assert(_remainingDataCount >= 0, "Remaining data count should never be negative."); Debug.Assert(_remainingDataCount == 0 || _remainingData != null, "If there's remaining data, there must be a buffer to store it."); Debug.Assert(_remainingData == null || _remainingDataCount <= _remainingData.Length, "The buffer must be large enough for the data length."); Debug.Assert(_remainingData == null || _remainingDataOffset <= _remainingData.Length, "The offset must not walk off the buffer."); Debug.Assert(!((_remainingDataCount > 0) && (_pendingReadRequest != null)), "We can't have both remaining data and a pending request."); Debug.Assert(!((_completed != null) && (_pendingReadRequest != null)), "We can't both be completed and have a pending request."); Debug.Assert(_pendingReadRequest == null || !_pendingReadRequest.Task.IsCompleted, "A pending read request must not have been completed yet."); } /// <summary>State associated with a pending read request.</summary> private class ReadState : TaskCompletionSource<int> { internal readonly byte[] _buffer; internal readonly int _offset; internal readonly int _count; internal ReadState(byte[] buffer, int offset, int count) : base(TaskCreationOptions.RunContinuationsAsynchronously) { Debug.Assert(buffer != null, "Need non-null buffer"); Debug.Assert(offset >= 0, "Need non-negative offset"); Debug.Assert(count > 0, "Need positive count"); _buffer = buffer; _offset = offset; _count = count; } } /// <summary>State associated with a pending read request that's cancelable.</summary> private sealed class CancelableReadState : ReadState { internal readonly CurlResponseStream _stream; internal readonly CancellationToken _token; internal CancellationTokenRegistration _registration; internal CancelableReadState(byte[] buffer, int offset, int count, CurlResponseStream responseStream, CancellationToken cancellationToken) : base(buffer, offset, count) { _stream = responseStream; _token = cancellationToken; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using Telerik.Core; namespace Telerik.Charting { internal class CartesianChartAreaModel : ChartAreaModelWithAxes { internal const string NoHorizontalAxisKey = "NoHorizontalAxis"; internal const string NoVerticalAxisKey = "NoVerticalAxis"; // TODO: Remove this if it is not used. /// <summary> /// Gets the <see cref="CartesianChartGridModel"/> instance that decorates the background of this plot area. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public CartesianChartGridModel Grid { get { return this.grid as CartesianChartGridModel; } } internal override Tuple<object, object> ConvertPointToData(RadPoint coordinates) { return this.ConvertPointToData(coordinates, this.primaryFirstAxis, this.primarySecondAxis); } internal Tuple<object, object> ConvertPointToData(RadPoint coordinates, AxisModel firstAxis, AxisModel secondAxis) { object firstValue = null; object secondValue = null; if (this.view != null) { RadRect plotArea = this.plotArea.layoutSlot; double panOffsetX = this.view.PlotOriginX * plotArea.Width; double panOffsetY = this.view.PlotOriginY * plotArea.Height; RadRect plotAreaVirtualSize = new RadRect(plotArea.X, plotArea.Y, plotArea.Width * this.view.ZoomWidth, plotArea.Height * this.view.ZoomHeight); if (firstAxis != null && this.FirstAxes.Contains(firstAxis) && firstAxis.isUpdated) { firstValue = firstAxis.ConvertPhysicalUnitsToData(coordinates.X - panOffsetX, plotAreaVirtualSize); } if (secondAxis != null && this.SecondAxes.Contains(secondAxis) && secondAxis.isUpdated) { secondValue = secondAxis.ConvertPhysicalUnitsToData(coordinates.Y - panOffsetY, plotAreaVirtualSize); } } return new Tuple<object, object>(firstValue, secondValue); } internal override RadPoint ConvertDataToPoint(Tuple<object, object> data) { return this.ConvertDataToPoint(data, this.primaryFirstAxis, this.primarySecondAxis); } internal RadPoint ConvertDataToPoint(Tuple<object, object> data, AxisModel firstAxis, AxisModel secondAxis) { RadPoint coordinates = new RadPoint(double.NaN, double.NaN); if (this.view != null) { RadRect plotArea = this.plotArea.layoutSlot; RadRect plotAreaVirtualSize = new RadRect(plotArea.X, plotArea.Y, plotArea.Width * this.view.ZoomWidth, plotArea.Height * this.view.ZoomHeight); if (firstAxis != null && this.FirstAxes.Contains(firstAxis) && firstAxis.isUpdated) { AxisPlotInfo plotInfo = firstAxis.CreatePlotInfo(data.Item1); if (plotInfo != null) { coordinates.X = plotInfo.CenterX(plotAreaVirtualSize); } } if (secondAxis != null && this.SecondAxes.Contains(secondAxis) && secondAxis.isUpdated) { AxisPlotInfo plotInfo = secondAxis.CreatePlotInfo(data.Item2); if (plotInfo != null) { coordinates.Y = plotInfo.CenterY(plotAreaVirtualSize); } } } return coordinates; } internal override void ApplyLayoutRounding() { foreach (var axis in this.FirstAxes) { axis.ApplyLayoutRounding(); } foreach (var axis in this.SecondAxes) { axis.ApplyLayoutRounding(); } foreach (var seriesCombineStrategy in this.SeriesCombineStrategies.EnumerateValues()) { if (seriesCombineStrategy.HasCombination) { seriesCombineStrategy.ApplyLayoutRounding(this); } else { // ask each series to apply layout rounding foreach (ChartSeriesModel series in seriesCombineStrategy.NonCombinedSeries) { series.ApplyLayoutRounding(); } } } } internal override IEnumerable<string> GetNotLoadedReasons() { if (this.FirstAxes.Count == 0) { yield return NoHorizontalAxisKey; } if (this.SecondAxes.Count == 0) { yield return NoVerticalAxisKey; } } protected override RadRect ArrangeAxes(RadRect availableRect) { RadSize availableSize = new RadSize(availableRect.Width, availableRect.Height); // Populate stacks AxisStack[] stacks = this.PrepareAxesStacks(availableSize); AxisStack leftStack = stacks[0]; AxisStack topStack = stacks[1]; AxisStack rightStack = stacks[2]; AxisStack bottomStack = stacks[3]; RadRect plotAreaRect = CalculatePlotAreaRect(availableRect, leftStack, topStack, rightStack, bottomStack); int maxIterations = 10; int currentIteration = 0; // axes may need several passes to adjust their desired size due to label fit mode bool isArrangeValid; do { isArrangeValid = true; // Although this seems an anti-pattern, it actually is safety coding // The logic behind axes layout is not completely verified yet and we do not want to enter an endless loop if (currentIteration > maxIterations) { Debug.Assert(false, "Entering endless loop"); break; } if (!leftStack.IsEmpty) { double lastRightPoint = plotAreaRect.X; foreach (var axis in leftStack.axes) { var finalRect = new RadRect(lastRightPoint - axis.desiredSize.Width, plotAreaRect.Y, axis.desiredSize.Width, plotAreaRect.Height); lastRightPoint = finalRect.X; RadSize lastAxisDesiredSize = axis.desiredSize; axis.Arrange(finalRect); if (axis.desiredSize.Width != lastAxisDesiredSize.Width) { leftStack.desiredWidth += axis.desiredSize.Width - lastAxisDesiredSize.Width; isArrangeValid = false; } } } if (!topStack.IsEmpty) { double lastBottomPoint = plotAreaRect.Y; foreach (var axis in topStack.axes) { var finalRect = new RadRect(plotAreaRect.X, lastBottomPoint - axis.desiredSize.Height, plotAreaRect.Width, axis.desiredSize.Height); lastBottomPoint = finalRect.Y; RadSize lastAxisDesiredSize = axis.desiredSize; axis.Arrange(finalRect); if (axis.desiredSize.Height != lastAxisDesiredSize.Height) { topStack.desiredHeight += axis.desiredSize.Height - lastAxisDesiredSize.Height; isArrangeValid = false; } } } if (!rightStack.IsEmpty) { double lastLeftPoint = plotAreaRect.Right; foreach (var axis in rightStack.axes) { var finalRect = new RadRect(lastLeftPoint, plotAreaRect.Y, axis.desiredSize.Width, plotAreaRect.Height); lastLeftPoint = finalRect.Right; RadSize lastAxisDesiredSize = axis.desiredSize; axis.Arrange(finalRect); if (axis.desiredSize.Width != lastAxisDesiredSize.Width) { rightStack.desiredWidth += axis.desiredSize.Width - lastAxisDesiredSize.Width; isArrangeValid = false; } } } if (!bottomStack.IsEmpty) { double lastTopPoint = plotAreaRect.Bottom; foreach (var axis in bottomStack.axes) { var finalRect = new RadRect(plotAreaRect.X, lastTopPoint, plotAreaRect.Width, axis.desiredSize.Height); lastTopPoint = finalRect.Bottom; RadSize lastAxisDesiredSize = axis.desiredSize; axis.Arrange(finalRect); if (axis.desiredSize.Height != finalRect.Height) { bottomStack.desiredHeight += axis.desiredSize.Height - lastAxisDesiredSize.Height; isArrangeValid = false; } } } if (!isArrangeValid) { plotAreaRect = CalculatePlotAreaRect(availableRect, leftStack, topStack, rightStack, bottomStack); } currentIteration++; } while (!isArrangeValid); return plotAreaRect; } private static RadRect CalculatePlotAreaRect(RadRect availableRect, AxisStack leftStack, AxisStack topStack, AxisStack rightStack, AxisStack bottomStack) { RadPoint topLeft = new RadPoint(); double finalLeftRectWidth = leftStack.desiredWidth + leftStack.desiredMargin.Left + leftStack.desiredMargin.Right; double maxLeftMargin = Math.Max(topStack.desiredMargin.Left, bottomStack.desiredMargin.Left); topLeft.X = Math.Max(finalLeftRectWidth, maxLeftMargin); double finalTopRectHeight = topStack.desiredHeight + topStack.desiredMargin.Top + topStack.desiredMargin.Bottom; double maxTopMargin = Math.Max(leftStack.desiredMargin.Top, rightStack.desiredMargin.Top); topLeft.Y = Math.Max(finalTopRectHeight, maxTopMargin); RadPoint bottomRight = new RadPoint(); double finalRightRectWidth = rightStack.desiredWidth + rightStack.desiredMargin.Left + rightStack.desiredMargin.Right; double maxRightMargin = Math.Max(topStack.desiredMargin.Right, bottomStack.desiredMargin.Right); bottomRight.X = availableRect.Width - Math.Max(finalRightRectWidth, maxRightMargin); double finalBottomRectHeight = bottomStack.desiredHeight + bottomStack.desiredMargin.Top + bottomStack.desiredMargin.Bottom; double maxBottomMargin = Math.Max(leftStack.desiredMargin.Bottom, rightStack.desiredMargin.Bottom); bottomRight.Y = availableRect.Height - Math.Max(finalBottomRectHeight, maxBottomMargin); RadRect plotAreaRect = new RadRect(topLeft, bottomRight); return RadRect.Round(plotAreaRect); } private AxisStack[] PrepareAxesStacks(RadSize availableSize) { // horizontal stacks AxisStack leftStack; AxisStack rightStack; List<AxisModel> leftAxes = new List<AxisModel>(); List<AxisModel> rightAxes = new List<AxisModel>(); foreach (var axis in this.SecondAxes) { if (axis.HorizontalLocation == AxisHorizontalLocation.Left) { leftAxes.Add(axis); } else { rightAxes.Add(axis); } } leftStack = new AxisStack(leftAxes); rightStack = new AxisStack(rightAxes); // vertical stacks AxisStack topStack; AxisStack bottomStack; List<AxisModel> topAxes = new List<AxisModel>(); List<AxisModel> bottomAxes = new List<AxisModel>(); foreach (var axis in this.FirstAxes) { if (axis.VerticalLocation == AxisVerticalLocation.Bottom) { bottomAxes.Add(axis); } else { topAxes.Add(axis); } } bottomStack = new AxisStack(bottomAxes); topStack = new AxisStack(topAxes); leftStack.Measure(availableSize); topStack.Measure(availableSize); rightStack.Measure(availableSize); bottomStack.Measure(availableSize); return new AxisStack[] { leftStack, topStack, rightStack, bottomStack }; } private class AxisStack { internal RadThickness desiredMargin; internal double desiredWidth = double.NaN, desiredHeight = double.NaN; internal IList<AxisModel> axes; public AxisStack(IList<AxisModel> axes) { this.axes = axes; } public bool IsEmpty { get { return this.axes.Count == 0; } } public void Measure(RadSize availableSize) { this.desiredWidth = 0; this.desiredHeight = 0; for (int i = 0; i < this.axes.Count; i++) { AxisModel axis = this.axes[i]; axis.Measure(availableSize); this.desiredWidth = this.desiredWidth + axis.desiredSize.Width; this.desiredHeight = this.desiredHeight + axis.desiredSize.Height; RadThickness margin = axis.desiredMargin; this.desiredMargin.Left = Math.Max(this.desiredMargin.Left, margin.Left); this.desiredMargin.Top = Math.Max(this.desiredMargin.Top, margin.Top); this.desiredMargin.Right = Math.Max(this.desiredMargin.Right, margin.Right); this.desiredMargin.Bottom = Math.Max(this.desiredMargin.Bottom, margin.Bottom); } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql.Models { /// <summary> /// Response containing the list of databases for a given server. /// </summary> public partial class DatabaseListResponse : OperationResponse, IEnumerable<DatabaseListResponse.Database> { private IList<DatabaseListResponse.Database> _databases; /// <summary> /// Gets or sets the SQL Server databases that are housed in a server. /// </summary> public IList<DatabaseListResponse.Database> Databases { get { return this._databases; } set { this._databases = value; } } /// <summary> /// Initializes a new instance of the DatabaseListResponse class. /// </summary> public DatabaseListResponse() { this._databases = new List<DatabaseListResponse.Database>(); } /// <summary> /// Gets the sequence of Databases. /// </summary> public IEnumerator<DatabaseListResponse.Database> GetEnumerator() { return this.Databases.GetEnumerator(); } /// <summary> /// Gets the sequence of Databases. /// </summary> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// SQL Server database. /// </summary> public partial class Database { private string _collationName; /// <summary> /// Gets or sets the database resource's collation name. /// </summary> public string CollationName { get { return this._collationName; } set { this._collationName = value; } } private DateTime _creationDate; /// <summary> /// Gets or sets the date this database was created. /// </summary> public DateTime CreationDate { get { return this._creationDate; } set { this._creationDate = value; } } private string _edition; /// <summary> /// Gets or sets the database resource's edition. /// </summary> public string Edition { get { return this._edition; } set { this._edition = value; } } private int _id; /// <summary> /// Gets or sets the id of the database. /// </summary> public int Id { get { return this._id; } set { this._id = value; } } private bool _isFederationRoot; /// <summary> /// Gets or sets a value indicating whether the database is a /// federation root. /// </summary> public bool IsFederationRoot { get { return this._isFederationRoot; } set { this._isFederationRoot = value; } } private bool _isSystemObject; /// <summary> /// Gets or sets a value indicating whether the database is a /// system object. /// </summary> public bool IsSystemObject { get { return this._isSystemObject; } set { this._isSystemObject = value; } } private long _maximumDatabaseSizeInGB; /// <summary> /// Gets or sets the maximum size of this database, in Gigabytes. /// </summary> public long MaximumDatabaseSizeInGB { get { return this._maximumDatabaseSizeInGB; } set { this._maximumDatabaseSizeInGB = value; } } private string _name; /// <summary> /// Gets or sets the name of the database. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _serviceObjectiveAssignmentErrorCode; /// <summary> /// Gets or sets the error code for this service objective. /// </summary> public string ServiceObjectiveAssignmentErrorCode { get { return this._serviceObjectiveAssignmentErrorCode; } set { this._serviceObjectiveAssignmentErrorCode = value; } } private string _serviceObjectiveAssignmentErrorDescription; /// <summary> /// Gets or sets the error description, if any. /// </summary> public string ServiceObjectiveAssignmentErrorDescription { get { return this._serviceObjectiveAssignmentErrorDescription; } set { this._serviceObjectiveAssignmentErrorDescription = value; } } private string _serviceObjectiveAssignmentState; /// <summary> /// Gets or sets the state of the current assignment. /// </summary> public string ServiceObjectiveAssignmentState { get { return this._serviceObjectiveAssignmentState; } set { this._serviceObjectiveAssignmentState = value; } } private string _serviceObjectiveAssignmentStateDescription; /// <summary> /// Gets or sets the state description. /// </summary> public string ServiceObjectiveAssignmentStateDescription { get { return this._serviceObjectiveAssignmentStateDescription; } set { this._serviceObjectiveAssignmentStateDescription = value; } } private string _serviceObjectiveAssignmentSuccessDate; /// <summary> /// Gets or sets the date the service's assignment succeeded. /// </summary> public string ServiceObjectiveAssignmentSuccessDate { get { return this._serviceObjectiveAssignmentSuccessDate; } set { this._serviceObjectiveAssignmentSuccessDate = value; } } private string _serviceObjectiveId; /// <summary> /// Gets or sets the id of this service objective. /// </summary> public string ServiceObjectiveId { get { return this._serviceObjectiveId; } set { this._serviceObjectiveId = value; } } private string _sizeMB; /// <summary> /// Gets or sets the size of this database in megabytes (MB). /// </summary> public string SizeMB { get { return this._sizeMB; } set { this._sizeMB = value; } } private string _state; /// <summary> /// Gets or sets the state of the database. /// </summary> public string State { get { return this._state; } set { this._state = value; } } private string _type; /// <summary> /// Gets or sets the type of resource. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the Database class. /// </summary> public Database() { } } } }
// GTWeen.cs // // Author: // Atte Vuorinen <AtteVuorinen@gmail.com> // // Copyright (c) 2014 Atte Vuorinen // // 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.Collections.Generic; using System.Collections; using UnityEngine; using System.Text; public abstract class GTween : MonoBehaviour { //TODO: Better ignoreSame system. #region Header /// <summary> /// Tween delay. /// </summary> public float delay = 0; /// <summary> /// Skip play if playback is same. /// </summary> public bool ignoreSame = false; /// <summary> /// Tween curve. /// </summary> public GCurve curve = new GCurve(); /// <summary> /// When tween is finished onFinish delegates are invoked. /// </summary> public List<GEventDelegate> onFinish = new List<GEventDelegate>(); /// <summary> /// Cached Transform. /// </summary> [HideInInspector] public new Transform transform; #region Group //Group// /// <summary> /// Use groups. /// </summary> public bool useGroup = false; /// <summary> /// Group ID. /// </summary> public string groupID = ""; #endregion /// <summary> /// Stored AGUIObject. /// </summary> protected AGUIObject m_aguiObject; /// <summary> /// Is delay waited or it is waiting. /// </summary> private short m_delayWaited = -1; #endregion #region Core /// <summary> /// Update tweem logic. /// </summary> public void UpdateTween() { if(delay > 0) { if(m_delayWaited == -1) { StartCoroutine(WaitDelay(delay)); return; } else if(m_delayWaited == 0) { return; } } m_delayWaited = 1; OnTween(); } /// <summary> /// Play tween. /// </summary> public void Play() { if(!curve.IsFinished) { enabled = true; } else { Reset(); } } /// <summary> /// Play tween forward. /// </summary> public void PlayForward() { if(ignoreSame && curve.playback == GCurve.CurvePlayback.Forward) { return; } curve.playback = GCurve.CurvePlayback.Forward; if(curve.IsFinished) { Reset(); } else { this.enabled = true; } } /// <summary> /// Play tween reversed. /// </summary> public void PlayReversed() { if(ignoreSame && curve.playback == GCurve.CurvePlayback.Reversed) { return; } curve.playback = GCurve.CurvePlayback.Reversed; if(curve.IsFinished) { Reset(); } else { this.enabled = true; } } /// <summary> /// Toggle playback between forward and reversed. /// </summary> public void Toggle() { if(curve.playback == GCurve.CurvePlayback.Forward) { PlayReversed(); } else { PlayForward(); } } /// <summary> /// Reset tween. /// </summary> public void Reset() { m_delayWaited = -1; this.enabled = true; if(curve != null) { curve.Reset(); } } #endregion #region Body /// <summary> /// Tween action. /// </summary> protected abstract void OnTween(); /// <summary> /// Update tween. /// </summary> protected void Update() { if(!curve.fixedUpdate) { UpdateTween(); } } /// <summary> /// Fixed update tween. /// </summary> protected void FixedUpdate() { if(curve.fixedUpdate) { UpdateTween(); } } /// <summary> /// Inits tween. /// </summary> protected virtual void Awake() { transform = GetComponent<Transform>(); if(GetComponent<AGUIObject>()) { m_aguiObject = GetComponent<AGUIObject>(); } } /// <summary> /// Inits onFinish delegate on curve. /// </summary> protected virtual void Start() { curve.OnFinish = delegate() { Reset(); if(curve.mode == GCurve.WrapModeGUI.Once) { this.enabled = false; } onFinish.Invoke(); }; } /// <summary> /// Wait delay. /// </summary> /// <returns>The delay.</returns> /// <param name="delay">Delay.</param> private IEnumerator WaitDelay(float delay) { m_delayWaited = 0; yield return new WaitForSeconds(delay); m_delayWaited = 1; } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Linq; using System.Reactive.Linq; using System.Reflection; using Its.Log.Instrumentation.Extensions; using NUnit.Framework; using Assert = NUnit.Framework.Assert; using StringAssert = NUnit.Framework.StringAssert; namespace Its.Log.Instrumentation.UnitTests { [TestFixture] public class ParameterLoggingTests { [TearDown] [SetUp] public void SetUpAndTearDown() { Extension.EnableAll(); } [Test] public void Log_WithParams_supplies_enclosing_method() { const double one = 2d; const double two = 2d; var currentMethod = MethodBase.GetCurrentMethod().Name; var wasCalled = false; using (Log.Events().Where(e => e.CallingMethod.Contains(currentMethod)).Subscribe( e => wasCalled = true)) { Log.WithParams(() => new { one, two }).Write("message!"); } Assert.IsTrue(wasCalled); } [Test] public void When_WithParams_is_passed_a_null_Func_it_still_logs_the_subject() { var log = ""; Func<object> nullFunc = null; using (Log.Events().Subscribe(e=>log+=e.ToLogString())) { Log.WithParams(nullFunc).Write("hello!"); } Assert.That(log, Is.StringContaining("hello!")); } [NUnit.Framework.Ignore("Perf timing test")] [Test] public void Perf_experiment_for_explicit_int_formatter_registration() { var iterations = 1000000; Timer.TimeOperation(i => i.ToLogString(), iterations, "without"); Log.Formatters.RegisterFormatter<int>(i => i.ToString()); Timer.TimeOperation(i => i.ToLogString(), iterations, "with"); } [NUnit.Framework.Ignore("Perf timing test")] [Test] public void Perf_timing_for_boundary_logging_with_parameters() { Log.EntryPosted += (o, e) => e.ToLogString(); Log.WithParams(() => new { one = 1, two = "2" }).Write("hello"); Timer.TimeOperation(i => Widget.DoStuffStatically(i.ToString()), 1000000, "upgraded"); } [Test] public virtual void Log_with_params_can_be_disabled_globally() { Extension<Params>.Disable(); var writer = new StringWriter(); var someGuid = Guid.NewGuid(); using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) { Log.WithParams(() => new { someGuid }).Write("a message"); } var output = writer.ToString(); StringAssert.DoesNotContain("someGuid", output); StringAssert.DoesNotContain(someGuid.ToLogString(), output); } [Test] public virtual void Log_WithParams_can_be_disabled_per_class() { var writer = new StringWriter(); var someGuid = Guid.NewGuid(); Extension<Params>.DisableFor<ParameterLoggingTests>(); using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) { Log.WithParams(() => new { someGuid }).Write("a message"); } var output = writer.ToString(); Assert.That(output, !Contains.Substring("someGuid")); Assert.That(output, !Contains.Substring(someGuid.ToLogString())); } [Test] public virtual void When_Log_WithParams_is_disabled_for_one_class_it_is_not_disabled_for_others() { var writer = new StringWriter(); var someGuid = Guid.NewGuid(); Extension<Params>.DisableFor<ParameterLoggingTests>(); using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) { Log.WithParams(() => new { someGuid }).Write("a message"); new Widget().DoStuff("widget param"); } var output = writer.ToString(); Assert.That(output, Contains.Substring("widget param")); } [Test] public virtual void Log_WithParams_comment_appears_in_output() { var writer = new StringWriter(); var fortyone = 41; using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) { Log.WithParams(() => new { fortyone }).Write("a message"); } StringAssert.Contains("a message", writer.ToString()); } [Test] public virtual void Log_WithParams_automatically_generates_custom_formatter_for_array() { var writer = new StringWriter(); var myInts = new[] { 2222, 3333, 4444 }; using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) { Log.WithParams(() => new { myInts }).Write("a message"); } var output = writer.ToString(); StringAssert.Contains("2222", output); StringAssert.Contains("3333", output); StringAssert.Contains("4444", output); StringAssert.DoesNotContain(myInts.ToString(), output); } [Test] public virtual void Log_WithParams_automatically_generates_custom_formatter_for_reference_type() { var writer = new StringWriter(); Log.Formatters.RegisterPropertiesFormatter<FileInfo>(); const int anInt = 23; var fileInfo = new FileInfo(@"c:\temp\testfile.txt"); using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) using (TestHelper.LogToConsole()) { Log.WithParams(() => new { anInt, fileInfo }).Write("a message"); } StringAssert.Contains(@"Directory = c:\temp", writer.ToString()); } [Test] public virtual void Log_WithParams_supplies_enclosing_type() { var wasCalled = false; var one = 1f; var two = 2d; using (Log.Events().Where(e => e.CallingType == GetType()).Subscribe(_ => wasCalled = true)) { Log.WithParams(() => new { one, two }) .Write("message!"); } Assert.IsTrue(wasCalled); } [Test] public virtual void Log_WithParams_correctly_outputs_value_types() { var writer = new StringWriter(); var forty = "40"; var fortyone = 41; using (Log.Events().Subscribe(e => writer.Write(e.ToLogString()))) { Log.WithParams(() => new { forty, fortyone }).Write("a message"); } var output = writer.ToString(); StringAssert.Contains("forty", output); StringAssert.Contains("40", output); StringAssert.Contains("fortyone", output); Assert.IsTrue(output.Contains("41")); } [Test] public void Log_WithParams_does_not_throw_when_params_func_is_null() { Func<string> paramAccessor = null; using (Log.Events().LogToConsole()) using (TestHelper.InternalErrors().LogToConsole()) // this displays the resulting exception, which is swallowed { Log.WithParams(paramAccessor).Write("hello"); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using Newtonsoft.Json.Linq; using POESKillTree.SkillTreeFiles; using POESKillTree.Utils; namespace POESKillTree.Model.Builds { /// <summary> /// <see cref="IBuild"/> implementation that represents a single build, a leaf in the build tree. /// Has a dirty flag that is set with every property change and can be reset. Can be reverted to the state of the /// last dirty flag reset. /// </summary> public class PoEBuild : AbstractBuild<PoEBuild> { private string _note; private string _characterName; private string _accountName; private string _league; private int _level = 1; private string _treeUrl = Constants.DefaultTree; private string _itemData; private DateTime _lastUpdated = DateTime.Now; private ObservableCollection<string[]> _customGroups; private BanditSettings _bandits; private ObservableSet<ushort> _checkedNodeIds; private ObservableSet<ushort> _crossedNodeIds; private JObject _additionalData; private bool _isDirty; private IMemento<PoEBuild> _memento; /// <summary> /// Gets or sets a arbitrary note. /// </summary> public string Note { get { return _note; } set { SetProperty(ref _note, value); } } /// <summary> /// Gets or sets the character name this builds represents. /// </summary> public string CharacterName { get { return _characterName; } set { SetProperty(ref _characterName, value); } } /// <summary> /// Gets or sets the account name that owns the represented character. /// </summary> public string AccountName { get { return _accountName; } set { SetProperty(ref _accountName, value); } } /// <summary> /// Gets or sets the league of the represented character. /// </summary> public string League { get { return _league; } set { SetProperty(ref _league, value); } } /// <summary> /// Gets or sets the level of the represented character. /// </summary> public int Level { get { return _level; } set { SetProperty(ref _level, value); } } /// <summary> /// Gets or sets the build defining skill tree URL. /// </summary> public string TreeUrl { get { return _treeUrl; } set { SetProperty(ref _treeUrl, value); } } /// <summary> /// Gets or sets the item data of this build as serialized JSON. /// </summary> public string ItemData { get { return _itemData; } set { SetProperty(ref _itemData, value); } } /// <summary> /// Gets or sets the last time this build was updated and saved. /// </summary> public DateTime LastUpdated { get { return _lastUpdated; } set { SetProperty(ref _lastUpdated, value); } } /// <summary> /// Gets the custom attribute grouping of this build. /// </summary> public ObservableCollection<string[]> CustomGroups { get { return _customGroups; } private set { SetProperty(ref _customGroups, value); } } /// <summary> /// Gets the bandit settings of this build. /// </summary> public BanditSettings Bandits { get { return _bandits; } private set { SetProperty(ref _bandits, value); } } /// <summary> /// Gets a set containing the ids of the nodes check tagged in this build. /// </summary> public ObservableSet<ushort> CheckedNodeIds { get { return _checkedNodeIds; } private set { SetProperty(ref _checkedNodeIds, value); } } /// <summary> /// Gets a set containing the ids of the nodes cross tagged in this build. /// </summary> public ObservableSet<ushort> CrossedNodeIds { get { return _crossedNodeIds; } private set { SetProperty(ref _crossedNodeIds, value); } } /// <summary> /// Gets a JSON object containing arbitrary additional data. /// Changes to the object will not flag this build dirty, <see cref="FlagDirty"/> needs to be called /// explicitly. /// </summary> public JObject AdditionalData { get { return _additionalData; } private set { SetProperty(ref _additionalData, value); } } /// <summary> /// Gets whether this build was changed since the last <see cref="KeepChanges"/> call. /// </summary> public bool IsDirty { get { return _isDirty; } private set { SetProperty(ref _isDirty, value); } } /// <summary> /// Gets whether this build can be reverted to an old state. It can be reverted if /// <see cref="KeepChanges"/> was called at least once. /// </summary> public bool CanRevert { get { return _memento != null; } } public PoEBuild() { PropertyChanged += PropertyChangedHandler; Bandits = new BanditSettings(); CustomGroups = new ObservableCollection<string[]>(); CheckedNodeIds = new ObservableSet<ushort>(); CrossedNodeIds = new ObservableSet<ushort>(); AdditionalData = new JObject(); PropertyChanging += PropertyChangingHandler; } public PoEBuild(BanditSettings bandits, IEnumerable<string[]> customGroups, IEnumerable<ushort> checkedNodeIds, IEnumerable<ushort> crossedNodeIds, string additionalData) { PropertyChanged += PropertyChangedHandler; Bandits = bandits ?? new BanditSettings(); CustomGroups = new ObservableCollection<string[]>(customGroups); CheckedNodeIds = new ObservableSet<ushort>(checkedNodeIds); CrossedNodeIds = new ObservableSet<ushort>(crossedNodeIds); AdditionalData = additionalData == null ? new JObject() : JObject.Parse(additionalData); PropertyChanging += PropertyChangingHandler; } private void PropertyChangingHandler(object sender, PropertyChangingEventArgs args) { switch (args.PropertyName) { case nameof(CustomGroups): CustomGroups.CollectionChanged -= ChangedHandler; break; case nameof(Bandits): Bandits.PropertyChanged -= ChangedHandler; break; case nameof(CheckedNodeIds): CheckedNodeIds.CollectionChanged -= ChangedHandler; break; case nameof(CrossedNodeIds): CrossedNodeIds.CollectionChanged -= ChangedHandler; break; } } private void PropertyChangedHandler(object sender, PropertyChangedEventArgs args) { switch (args.PropertyName) { case nameof(CustomGroups): CustomGroups.CollectionChanged += ChangedHandler; break; case nameof(Bandits): Bandits.PropertyChanged += ChangedHandler; break; case nameof(CheckedNodeIds): CheckedNodeIds.CollectionChanged += ChangedHandler; break; case nameof(CrossedNodeIds): CrossedNodeIds.CollectionChanged += ChangedHandler; break; } if (args.PropertyName != nameof(IsDirty)) IsDirty = true; } private void ChangedHandler(object sender, EventArgs args) { IsDirty = true; } /// <summary> /// Explicitly flags this instance as having unsaved changes. /// </summary> public void FlagDirty() { IsDirty = true; } /// <summary> /// Reverts changes made to this instance since the last <see cref="KeepChanges"/>. /// </summary> /// <exception cref="NullReferenceException">When <see cref="KeepChanges"/> was never called.</exception> public void RevertChanges() { _memento.Restore(this); IsDirty = false; } /// <summary> /// Removes the dirty flag and stores the current change so they can be reverted to. /// </summary> public void KeepChanges() { _memento = new Memento(this); IsDirty = false; } /// <summary> /// Creates a copy of <paramref name="toCopy"/> with the given name that is dirty but can not be reverted. /// </summary> public static PoEBuild CreateNotRevertableCopy(PoEBuild toCopy, string newName) { var copy = toCopy.DeepClone(); copy.Name = newName; copy._memento = null; return copy; } protected override Notifier SafeMemberwiseClone() { var o = (PoEBuild) base.SafeMemberwiseClone(); o.PropertyChanged += o.PropertyChangedHandler; o.PropertyChanging += o.PropertyChangingHandler; return o; } public override PoEBuild DeepClone() { var o = (PoEBuild) SafeMemberwiseClone(); o.CustomGroups = new ObservableCollection<string[]>(CustomGroups.Select(a => (string[])a.Clone())); o.CheckedNodeIds = new ObservableSet<ushort>(CheckedNodeIds); o.CrossedNodeIds = new ObservableSet<ushort>(CrossedNodeIds); o.AdditionalData = new JObject(AdditionalData); o.Bandits = Bandits.DeepClone(); return o; } private class Memento : IMemento<PoEBuild> { private readonly PoEBuild _build; public Memento(PoEBuild build) { _build = build.DeepClone(); } public void Restore(PoEBuild target) { target.Name = _build.Name; target.Note = _build.Note; target.CharacterName = _build.CharacterName; target.AccountName = _build.AccountName; target.League = _build.League; target.Level = _build.Level; target.TreeUrl = _build.TreeUrl; target.ItemData = _build.ItemData; target.LastUpdated = _build.LastUpdated; target.CustomGroups = new ObservableCollection<string[]>(_build.CustomGroups.Select(a => (string[]) a.Clone())); target.CheckedNodeIds = new ObservableSet<ushort>(_build.CheckedNodeIds); target.CrossedNodeIds = new ObservableSet<ushort>(_build.CrossedNodeIds); target.AdditionalData = new JObject(_build.AdditionalData); target.Bandits = _build.Bandits.DeepClone(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Collections.Immutable { /// <summary> /// An immutable sorted set implementation. /// </summary> /// <typeparam name="T">The type of elements in the set.</typeparam> /// <devremarks> /// We implement <see cref="IReadOnlyList{T}"/> because it adds an ordinal indexer. /// We implement <see cref="IList{T}"/> because it gives us <see cref="IList{T}.IndexOf"/>, which is important for some folks. /// </devremarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] public sealed partial class ImmutableSortedSet<T> : IImmutableSet<T>, ISortKeyCollection<T>, IReadOnlyList<T>, IList<T>, ISet<T>, IList, IStrongEnumerable<T, ImmutableSortedSet<T>.Enumerator> { /// <summary> /// This is the factor between the small collection's size and the large collection's size in a bulk operation, /// under which recreating the entire collection using a fast method rather than some incremental update /// (that requires tree rebalancing) is preferable. /// </summary> private const float RefillOverIncrementalThreshold = 0.15f; /// <summary> /// An empty sorted set with the default sort comparer. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableSortedSet<T> Empty = new ImmutableSortedSet<T>(); /// <summary> /// The root node of the AVL tree that stores this set. /// </summary> private readonly Node _root; /// <summary> /// The comparer used to sort elements in this set. /// </summary> private readonly IComparer<T> _comparer; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}"/> class. /// </summary> /// <param name="comparer">The comparer.</param> internal ImmutableSortedSet(IComparer<T> comparer = null) { _root = Node.EmptyNode; _comparer = comparer ?? Comparer<T>.Default; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}"/> class. /// </summary> /// <param name="root">The root of the AVL tree with the contents of this set.</param> /// <param name="comparer">The comparer.</param> private ImmutableSortedSet(Node root, IComparer<T> comparer) { Requires.NotNull(root, nameof(root)); Requires.NotNull(comparer, nameof(comparer)); root.Freeze(); _root = root; _comparer = comparer; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public ImmutableSortedSet<T> Clear() { Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>().IsEmpty); return _root.IsEmpty ? this : Empty.WithComparer(_comparer); } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> public T Max { get { return _root.Max; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> public T Min { get { return _root.Min; } } #region IImmutableSet<T> Properties /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public bool IsEmpty { get { return _root.IsEmpty; } } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public int Count { get { return _root.Count; } } #endregion #region ISortKeyCollection<T> Properties /// <summary> /// See the <see cref="ISortKeyCollection{T}"/> interface. /// </summary> public IComparer<T> KeyComparer { get { return _comparer; } } #endregion /// <summary> /// Gets the root node (for testing purposes). /// </summary> internal IBinaryTree Root { get { return _root; } } #region IReadOnlyList<T> Indexers /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> public T this[int index] { get { #if FEATURE_ITEMREFAPI return _root.ItemRef(index); #else return _root[index]; #endif } } #if FEATURE_ITEMREFAPI /// <summary> /// Gets a read-only reference of the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>A read-only reference of the element at the given position.</returns> public ref readonly T ItemRef(int index) { return ref _root.ItemRef(index); } #endif #endregion #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Add(T value) { Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); bool mutated; return this.Wrap(_root.Add(value, _comparer, out mutated)); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Remove(T value) { Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); bool mutated; return this.Wrap(_root.Remove(value, _comparer, out mutated)); } /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="equalValue">The value to search for.</param> /// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// a value that has more complete data than the value you currently have, although their /// comparer functions indicate they are equal. /// </remarks> [Pure] public bool TryGetValue(T equalValue, out T actualValue) { Node searchResult = _root.Search(equalValue, _comparer); if (searchResult.IsEmpty) { actualValue = equalValue; return false; } else { actualValue = searchResult.Key; return true; } } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); var newSet = this.Clear(); foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { if (this.Contains(item)) { newSet = newSet.Add(item); } } return newSet; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); var result = _root; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { bool mutated; result = result.Remove(item, _comparer, out mutated); } return this.Wrap(result); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [Pure] public ImmutableSortedSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); var otherAsSet = ImmutableSortedSet.CreateRange(_comparer, other); var result = this.Clear(); foreach (T item in this) { if (!otherAsSet.Contains(item)) { result = result.Add(item); } } foreach (T item in otherAsSet) { if (!this.Contains(item)) { result = result.Add(item); } } return result; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); ImmutableSortedSet<T> immutableSortedSet; if (TryCastToImmutableSortedSet(other, out immutableSortedSet) && immutableSortedSet.KeyComparer == this.KeyComparer) // argument is a compatible immutable sorted set { if (immutableSortedSet.IsEmpty) { return this; } else if (this.IsEmpty) { // Adding the argument to this collection is equivalent to returning the argument. return immutableSortedSet; } else if (immutableSortedSet.Count > this.Count) { // We're adding a larger set to a smaller set, so it would be faster to simply // add the smaller set to the larger set. return immutableSortedSet.Union(this); } } int count; if (this.IsEmpty || (other.TryGetCount(out count) && (this.Count + count) * RefillOverIncrementalThreshold > this.Count)) { // The payload being added is so large compared to this collection's current size // that we likely won't see much memory reuse in the node tree by performing an // incremental update. So just recreate the entire node tree since that will // likely be faster. return this.LeafToRootRefill(other); } return this.UnionIncremental(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> WithComparer(IComparer<T> comparer) { Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); if (comparer == null) { comparer = Comparer<T>.Default; } if (comparer == _comparer) { return this; } else { var result = new ImmutableSortedSet<T>(Node.EmptyNode, comparer); result = result.Union(this); return result; } } /// <summary> /// Checks whether a given sequence of items entirely describe the contents of this set. /// </summary> /// <param name="other">The sequence of items to check against this set.</param> /// <returns>A value indicating whether the sets are equal.</returns> [Pure] public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (object.ReferenceEquals(this, other)) { return true; } var otherSet = new SortedSet<T>(other, this.KeyComparer); if (this.Count != otherSet.Count) { return false; } int matches = 0; foreach (T item in otherSet) { if (!this.Contains(item)) { return false; } matches++; } return matches == this.Count; } /// <summary> /// Determines whether the current set is a property (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> [Pure] public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return other.Any(); } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new SortedSet<T>(other, this.KeyComparer); if (this.Count >= otherSet.Count) { return false; } int matches = 0; bool extraFound = false; foreach (T item in otherSet) { if (this.Contains(item)) { matches++; } else { extraFound = true; } if (matches == this.Count && extraFound) { return true; } } return false; } /// <summary> /// Determines whether the current set is a correct superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct superset of other; otherwise, false.</returns> [Pure] public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return false; } int count = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { count++; if (!this.Contains(item)) { return false; } } return this.Count > count; } /// <summary> /// Determines whether a set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> [Pure] public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return true; } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new SortedSet<T>(other, this.KeyComparer); int matches = 0; foreach (T item in otherSet) { if (this.Contains(item)) { matches++; } } return matches == this.Count; } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> [Pure] public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (!this.Contains(item)) { return false; } } return true; } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> [Pure] public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return false; } foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (this.Contains(item)) { return true; } } return false; } /// <summary> /// Returns an <see cref="IEnumerable{T}"/> that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/> /// in reverse order. /// </returns> [Pure] public IEnumerable<T> Reverse() { return new ReverseEnumerable(_root); } /// <summary> /// Gets the position within this set that the specified value does or would appear. /// </summary> /// <param name="item">The value whose position is being sought.</param> /// <returns> /// The index of the specified <paramref name="item"/> in the sorted set, /// if <paramref name="item"/> is found. If <paramref name="item"/> is not /// found and <paramref name="item"/> is less than one or more elements in this set, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If <paramref name="item"/> is not found /// and <paramref name="item"/> is greater than any of the elements in the set, /// a negative number which is the bitwise complement of (the index of the last /// element plus 1). /// </returns> public int IndexOf(T item) { return _root.IndexOf(item, _comparer); } #endregion #region IImmutableSet<T> Members /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public bool Contains(T value) { return _root.Contains(value, _comparer); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Clear() { return this.Clear(); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Add(T value) { return this.Add(value); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Remove(T value) { return this.Remove(value); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return this.Intersect(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return this.Except(other); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return this.SymmetricExcept(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return this.Union(other); } #endregion #region ISet<T> Members /// <summary> /// See <see cref="ISet{T}"/> /// </summary> bool ISet<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } #endregion #region ICollection<T> members /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { _root.CopyTo(array, arrayIndex); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void ICollection<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.Clear() { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region IList<T> methods /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> T IList<T>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } #endregion #region IList properties /// <summary> /// Gets a value indicating whether the <see cref="IList"/> has a fixed size. /// </summary> /// <returns>true if the <see cref="IList"/> has a fixed size; otherwise, false.</returns> bool IList.IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IList.IsReadOnly { get { return true; } } #endregion #region ICollection Properties /// <summary> /// See <see cref="ICollection"/>. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// See the <see cref="ICollection"/> interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion #region IList methods /// <summary> /// Adds an item to the <see cref="IList"/>. /// </summary> /// <param name="value">The object to add to the <see cref="IList"/>.</param> /// <returns> /// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection, /// </returns> /// <exception cref="System.NotSupportedException"></exception> int IList.Add(object value) { throw new NotSupportedException(); } /// <summary> /// Clears this instance. /// </summary> /// <exception cref="System.NotSupportedException"></exception> void IList.Clear() { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="IList"/> contains a specific value. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// true if the <see cref="object"/> is found in the <see cref="IList"/>; otherwise, false. /// </returns> bool IList.Contains(object value) { return this.Contains((T)value); } /// <summary> /// Determines the index of a specific item in the <see cref="IList"/>. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> int IList.IndexOf(object value) { return this.IndexOf((T)value); } /// <summary> /// Inserts an item to the <see cref="IList"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value">The object to insert into the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Insert(int index, object value) { throw new NotSupportedException(); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="IList"/>. /// </summary> /// <param name="value">The object to remove from the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Remove(object value) { throw new NotSupportedException(); } /// <summary> /// Removes at. /// </summary> /// <param name="index">The index.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// Gets or sets the <see cref="System.Object"/> at the specified index. /// </summary> /// <value> /// The <see cref="System.Object"/>. /// </value> /// <param name="index">The index.</param> /// <exception cref="System.NotSupportedException"></exception> object IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int index) { _root.CopyTo(array, index); } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.IsEmpty ? Enumerable.Empty<T>().GetEnumerator() : this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> /// <remarks> /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> public Enumerator GetEnumerator() { return _root.GetEnumerator(); } /// <summary> /// Discovers an immutable sorted set for a given value, if possible. /// </summary> private static bool TryCastToImmutableSortedSet(IEnumerable<T> sequence, out ImmutableSortedSet<T> other) { other = sequence as ImmutableSortedSet<T>; if (other != null) { return true; } var builder = sequence as Builder; if (builder != null) { other = builder.ToImmutable(); return true; } return false; } /// <summary> /// Creates a new sorted set wrapper for a node tree. /// </summary> /// <param name="root">The root of the collection.</param> /// <param name="comparer">The comparer used to build the tree.</param> /// <returns>The immutable sorted set instance.</returns> [Pure] private static ImmutableSortedSet<T> Wrap(Node root, IComparer<T> comparer) { return root.IsEmpty ? ImmutableSortedSet<T>.Empty.WithComparer(comparer) : new ImmutableSortedSet<T>(root, comparer); } /// <summary> /// Adds items to this collection using the standard spine rewrite and tree rebalance technique. /// </summary> /// <param name="items">The items to add.</param> /// <returns>The new collection.</returns> /// <remarks> /// This method is least demanding on memory, providing the great chance of memory reuse /// and does not require allocating memory large enough to store all items contiguously. /// It's performance is optimal for additions that do not significantly dwarf the existing /// size of this collection. /// </remarks> [Pure] private ImmutableSortedSet<T> UnionIncremental(IEnumerable<T> items) { Requires.NotNull(items, nameof(items)); Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); // Let's not implement in terms of ImmutableSortedSet.Add so that we're // not unnecessarily generating a new wrapping set object for each item. var result = _root; foreach (var item in items.GetEnumerableDisposable<T, Enumerator>()) { bool mutated; result = result.Add(item, _comparer, out mutated); } return this.Wrap(result); } /// <summary> /// Creates a wrapping collection type around a root node. /// </summary> /// <param name="root">The root node to wrap.</param> /// <returns>A wrapping collection type for the new tree.</returns> [Pure] private ImmutableSortedSet<T> Wrap(Node root) { if (root != _root) { return root.IsEmpty ? this.Clear() : new ImmutableSortedSet<T>(root, _comparer); } else { return this; } } /// <summary> /// Creates an immutable sorted set with the contents from this collection and a sequence of elements. /// </summary> /// <param name="addedItems">The sequence of elements to add to this set.</param> /// <returns>The immutable sorted set.</returns> [Pure] private ImmutableSortedSet<T> LeafToRootRefill(IEnumerable<T> addedItems) { Requires.NotNull(addedItems, nameof(addedItems)); Contract.Ensures(Contract.Result<ImmutableSortedSet<T>>() != null); // Rather than build up the immutable structure in the incremental way, // build it in such a way as to generate minimal garbage, by assembling // the immutable binary tree from leaf to root. This requires // that we know the length of the item sequence in advance, sort it, // and can index into that sequence like a list, so the limited // garbage produced is a temporary mutable data structure we use // as a reference when creating the immutable one. // Produce the initial list containing all elements, including any duplicates. List<T> list; if (this.IsEmpty) { // If the additional items enumerable list is known to be empty, too, // then just return this empty instance. int count; if (addedItems.TryGetCount(out count) && count == 0) { return this; } // Otherwise, construct a list from the items. The Count could still // be zero, in which case, again, just return this empty instance. list = new List<T>(addedItems); if (list.Count == 0) { return this; } } else { // Build the list from this set and then add the additional items. // Even if the additional items is empty, this set isn't, so we know // the resulting list will not be empty. list = new List<T>(this); list.AddRange(addedItems); } Debug.Assert(list.Count > 0); // Sort the list and remove duplicate entries. IComparer<T> comparer = this.KeyComparer; list.Sort(comparer); int index = 1; for (int i = 1; i < list.Count; i++) { if (comparer.Compare(list[i], list[i - 1]) != 0) { list[index++] = list[i]; } } list.RemoveRange(index, list.Count - index); // Use the now sorted list of unique items to construct a new sorted set. Node root = Node.NodeTreeFromList(list.AsOrderedCollection(), 0, list.Count); return this.Wrap(root); } /// <summary> /// An reverse enumerable of a sorted set. /// </summary> private class ReverseEnumerable : IEnumerable<T> { /// <summary> /// The root node to enumerate. /// </summary> private readonly Node _root; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.ReverseEnumerable"/> class. /// </summary> /// <param name="root">The root of the data structure to reverse enumerate.</param> internal ReverseEnumerable(Node root) { Requires.NotNull(root, nameof(root)); _root = root; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return _root.Reverse(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } }
/* * Anarres C Preprocessor * Copyright (c) 2007-2008, Shevek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; namespace CppNet { /** * A macro object. * * This encapsulates a name, an argument count, and a token stream * for replacement. The replacement token stream may contain the * extra tokens {@link Token#M_ARG} and {@link Token#M_STRING}. */ public class Macro { private Source source; private String name; /* It's an explicit decision to keep these around here. We don't * need to; the argument token type is M_ARG and the value * is the index. The strings themselves are only used in * stringification of the macro, for debugging. */ private List<String> args; private bool variadic; private List<Token> tokens; public Macro(Source source, String name) { this.source = source; this.name = name; this.args = null; this.variadic = false; this.tokens = new List<Token>(); } public Macro(String name) : this(null, name) { } /** * Sets the Source from which this macro was parsed. */ public void setSource(Source s) { this.source = s; } /** * Returns the Source from which this macro was parsed. * * This method may return null if the macro was not parsed * from a regular file. */ public Source getSource() { return source; } /** * Returns the name of this macro. */ public String getName() { return name; } /** * Sets the arguments to this macro. */ public void setArgs(List<String> args) { this.args = args; } /** * Returns true if this is a function-like macro. */ public bool isFunctionLike() { return args != null; } /** * Returns the number of arguments to this macro. */ public int getArgs() { return args.Count; } /** * Sets the variadic flag on this Macro. */ public void setVariadic(bool b) { this.variadic = b; } /** * Returns true if this is a variadic function-like macro. */ public bool isVariadic() { return variadic; } /** * Adds a token to the expansion of this macro. */ public void addToken(Token tok) { this.tokens.Add(tok); } /** * Adds a "paste" operator to the expansion of this macro. * * A paste operator causes the next token added to be pasted * to the previous token when the macro is expanded. * It is an error for a macro to end with a paste token. */ public void addPaste(Token tok) { /* * Given: tok0 ## tok1 * We generate: M_PASTE, tok0, tok1 * This extends as per a stack language: * tok0 ## tok1 ## tok2 -> * M_PASTE, tok0, M_PASTE, tok1, tok2 */ this.tokens.Insert(tokens.Count - 1, tok); } internal List<Token> getTokens() { return tokens; } /* Paste tokens are inserted before the first of the two pasted * tokens, so it's a kind of bytecode notation. This method * swaps them around again. We know that there will never be two * sequential paste tokens, so a bool is sufficient. */ public String getText() { StringBuilder buf = new StringBuilder(); bool paste = false; for (int i = 0; i < tokens.Count; i++) { Token tok = tokens[i]; if (tok.getType() == Token.M_PASTE) { System.Diagnostics.Debug.Assert(paste == false, "Two sequential pastes."); paste = true; continue; } else { buf.Append(tok.getText()); } if (paste) { buf.Append(" #" + "# "); paste = false; } // buf.Append(tokens.get(i)); } return buf.ToString(); } override public String ToString() { StringBuilder buf = new StringBuilder(name); if(args != null) { buf.Append('('); bool first = true; foreach(String str in args) { if(!first) { buf.Append(", "); } else { first = false; } buf.Append(str); } if(isVariadic()) { buf.Append("..."); } buf.Append(')'); } if(tokens.Count != 0) { buf.Append(" => ").Append(getText()); } return buf.ToString(); } } }
/* Copyright (c) 2006 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. */ #region Using directives #define USE_TRACING using System; using System.Xml; using System.IO; using System.Globalization; using System.ComponentModel; using System.Runtime.InteropServices; #endregion // <summary>Contains AtomSource, an object to represent the atom:source // element.</summary> namespace Google.GData.Client { /// <summary>TypeConverter, so that AtomHead shows up in the property pages /// </summary> [ComVisible(false)] public class AtomSourceConverter : ExpandableObjectConverter { ///<summary>Standard type converter method</summary> public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType) { if (destinationType == typeof(AtomSource) || destinationType == typeof(AtomFeed)) { return true; } return base.CanConvertTo(context, destinationType); } ///<summary>Standard type converter method</summary> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, System.Type destinationType) { AtomSource atomSource = value as AtomSource; if (destinationType == typeof(System.String) && atomSource != null) { return "Feed: " + atomSource.Title; } return base.ConvertTo(context, culture, value, destinationType); } } /// <summary>Represents the AtomSource object. If an atom:entry is copied from one feed /// into another feed, then the source atom:feed's metadata (all child elements of atom:feed other /// than the atom:entry elements) MAY be preserved within the copied entry by adding an atom:source /// child element, if it is not already present in the entry, and including some or all of the source /// feed's Metadata elements as the atom:source element's children. Such metadata SHOULD be preserved /// if the source atom:feed contains any of the child elements atom:author, atom:contributor, /// atom:rights, or atom:category and those child elements are not present in the source atom:entry. /// </summary> /* atomSource = element atom:source { atomCommonAttributes, (atomAuthor? & atomCategory* & atomContributor* & atomGenerator? & atomIcon? & atomId? & atomLink* & atomLogo? & atomRights? & atomSubtitle? & atomTitle? & atomUpdated? & extensionElement*) } */ [TypeConverterAttribute(typeof(AtomSourceConverter)), DescriptionAttribute("Expand to see the options for the feed")] public class AtomSource : AtomBase { /// <summary>author collection</summary> private AtomPersonCollection authors; /// <summary>contributors collection</summary> private AtomPersonCollection contributors; /// <summary>category collection</summary> private AtomCategoryCollection categories; /// <summary>the generator</summary> private AtomGenerator generator; /// <summary>icon, essentially an atom link</summary> private AtomIcon icon; /// <summary>ID</summary> private AtomId id; /// <summary>link collection</summary> private AtomLinkCollection links; /// <summary>logo, essentially an image link</summary> private AtomLogo logo; /// <summary>rights, former copyrights</summary> private AtomTextConstruct rights; /// <summary>subtitle as string</summary> private AtomTextConstruct subTitle; /// <summary>title property as string</summary> private AtomTextConstruct title; /// <summary>updated time stamp</summary> private DateTime updated; /// <summary>public void AtomSource()</summary> public AtomSource() { } /// <summary>public AtomSource(AtomFeed feed)</summary> public AtomSource(AtomFeed feed) : this() { Tracing.Assert(feed != null, "feed should not be null"); if (feed == null) { throw new ArgumentNullException("feed"); } // now copy them this.authors = feed.Authors; this.contributors = feed.Contributors; this.categories = feed.Categories; this.Generator = feed.Generator; this.Icon = feed.Icon; this.Logo = feed.Logo; this.Id = feed.Id; this.links = feed.Links; this.Rights = feed.Rights; this.Subtitle = feed.Subtitle; this.Title = feed.Title; this.Updated = feed.Updated; } /// <summary>accessor method public Authors AtomPersonCollection</summary> /// <returns> </returns> public AtomPersonCollection Authors { get { if (this.authors == null) { this.authors = new AtomPersonCollection(); } return this.authors; } } /// <summary>accessor method public Contributors AtomPersonCollection</summary> /// <returns> </returns> public AtomPersonCollection Contributors { get { if (this.contributors == null) { this.contributors = new AtomPersonCollection(); } return this.contributors; } } /// <summary>accessor method public Links AtomLinkCollection</summary> /// <returns> </returns> public AtomLinkCollection Links { get { if (this.links == null) { this.links = new AtomLinkCollection(); } return this.links; } } /// <summary>returns the category collection</summary> public AtomCategoryCollection Categories { get { if (this.categories == null) { this.categories = new AtomCategoryCollection(); } return this.categories; } } /// <summary>accessor method public FeedGenerator Generator</summary> /// <returns> </returns> public AtomGenerator Generator { get { return this.generator; } set { this.Dirty = true; this.generator = value; } } /// <summary>accessor method public AtomIcon Icon</summary> /// <returns> </returns> public AtomIcon Icon { get { return this.icon; } set { this.Dirty = true; this.icon = value; } } /// <summary>accessor method public AtomLogo Logo</summary> /// <returns> </returns> public AtomLogo Logo { get { return this.logo; } set { this.Dirty = true; this.logo = value; } } /// <summary>accessor method public DateTime LastUpdated</summary> /// <returns> </returns> public DateTime Updated { get { return this.updated; } set { this.Dirty = true; this.updated = value; } } /// <summary>accessor method public string Title</summary> /// <returns> </returns> public AtomTextConstruct Title { get { return this.title; } set { this.Dirty = true; this.title = value; } } /// <summary>accessor method public string Subtitle</summary> /// <returns> </returns> public AtomTextConstruct Subtitle { get { return this.subTitle; } set { this.Dirty = true; this.subTitle = value; } } /// <summary>accessor method public string Id</summary> /// <returns> </returns> public AtomId Id { get { return this.id; } set { this.Dirty = true; this.id = value; } } /// <summary>accessor method public string Rights</summary> /// <returns> </returns> public AtomTextConstruct Rights { get { return this.rights; } set { this.Dirty = true; this.rights = value; } } #region Persistence overloads /// <summary>Returns the constant representing this XML element.</summary> public override string XmlName { get { return AtomParserNameTable.XmlSourceElement; } } /// <summary>saves the inner state of the element</summary> /// <param name="writer">the xmlWriter to save into </param> protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); // saving Authors foreach (AtomPerson person in this.Authors) { person.SaveToXml(writer); } // saving Contributors foreach (AtomPerson person in this.Contributors) { person.SaveToXml(writer); } // saving Categories foreach (AtomCategory category in this.Categories) { category.SaveToXml(writer); } // saving the generator if (this.Generator != null) { this.Generator.SaveToXml(writer); } // save the icon if (this.Icon != null) { this.Icon.SaveToXml(writer); } // save the logo if (this.Logo != null) { this.Logo.SaveToXml(writer); } // save the ID if (this.Id != null) { this.Id.SaveToXml(writer); } // save the Links foreach (AtomLink link in this.Links) { link.SaveToXml(writer); } if (this.Rights != null) { this.Rights.SaveToXml(writer); } if (this.Subtitle != null) { this.Subtitle.SaveToXml(writer); } if (this.Title != null) { this.Title.SaveToXml(writer); } // date time construct, save here. WriteLocalDateTimeElement(writer, AtomParserNameTable.XmlUpdatedElement, this.Updated); } #endregion #region overloaded for property changes, xml:base /// <summary>just go down the child collections</summary> /// <param name="uriBase"> as currently calculated</param> internal override void BaseUriChanged(AtomUri uriBase) { base.BaseUriChanged(uriBase); foreach (AtomPerson person in this.Authors) { person.BaseUriChanged(uriBase); } // saving Contributors foreach (AtomPerson person in this.Contributors) { person.BaseUriChanged(uriBase); } // saving Categories foreach (AtomCategory category in this.Categories) { category.BaseUriChanged(uriBase); } // saving the generator if (this.Generator != null) { this.Generator.BaseUriChanged(uriBase); } // save the icon if (this.Icon != null) { this.Icon.BaseUriChanged(uriBase); } // save the logo if (this.Logo != null) { this.Logo.BaseUriChanged(uriBase); } // save the ID if (this.Id != null) { this.Id.BaseUriChanged(uriBase); } // save the Links foreach (AtomLink link in this.Links) { link.BaseUriChanged(uriBase); } if (this.Rights != null) { this.Rights.BaseUriChanged(uriBase); } if (this.Subtitle != null) { this.Subtitle.BaseUriChanged(uriBase); } if (this.Title != null) { this.Title.BaseUriChanged(uriBase); } } /// <summary>calls the action on this object and all children</summary> /// <param name="action">an IAtomBaseAction interface to call </param> /// <returns>true or false, pending outcome</returns> public override bool WalkTree(IBaseWalkerAction action) { if (base.WalkTree(action)) { return true; } foreach (AtomPerson person in this.Authors) { if (person.WalkTree(action)) { return true; } } // saving Contributors foreach (AtomPerson person in this.Contributors) { if (person.WalkTree(action)) { return true; } } // saving Categories foreach (AtomCategory category in this.Categories) { if (category.WalkTree(action)) { return true; } } // saving the generator if (this.Generator != null) { if (this.Generator.WalkTree(action)) { return true; } } // save the icon if (this.Icon != null) { if (this.Icon.WalkTree(action)) { return true; } } // save the logo if (this.Logo != null) { if (this.Logo.WalkTree(action)) { return true; } } // save the ID if (this.Id != null) { if (this.Id.WalkTree(action)) { return true; } } // save the Links foreach (AtomLink link in this.Links) { if (link.WalkTree(action)) { return true; } } if (this.Rights != null) { if (this.Rights.WalkTree(action)) { return true; } } if (this.Subtitle != null) { if (this.Subtitle.WalkTree(action)) { return true; } } if (this.Title != null) { if (this.Title.WalkTree(action)) { return true; } } return false; } #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.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using Microsoft.Win32; namespace System.Security { public sealed partial class SecureString { internal SecureString(SecureString str) { Debug.Assert(str != null, "Expected non-null SecureString"); Debug.Assert(str._buffer != null, "Expected other SecureString's buffer to be non-null"); Debug.Assert(str._encrypted, "Expected to be used only on encrypted SecureStrings"); AllocateBuffer(str._buffer.Length); SafeBSTRHandle.Copy(str._buffer, _buffer, str._buffer.Length * sizeof(char)); _decryptedLength = str._decryptedLength; _encrypted = str._encrypted; } private unsafe void InitializeSecureString(char* value, int length) { Debug.Assert(length >= 0, $"Expected non-negative length, got {length}"); AllocateBuffer((uint)length); _decryptedLength = length; byte* bufferPtr = null; try { _buffer.AcquirePointer(ref bufferPtr); Buffer.MemoryCopy((byte*)value, bufferPtr, (long)_buffer.ByteLength, length * sizeof(char)); } finally { if (bufferPtr != null) { _buffer.ReleasePointer(); } } ProtectMemory(); } private void AppendCharCore(char c) { UnprotectMemory(); try { EnsureCapacity(_decryptedLength + 1); _buffer.Write<char>((uint)_decryptedLength * sizeof(char), c); _decryptedLength++; } finally { ProtectMemory(); } } private void ClearCore() { _decryptedLength = 0; _buffer.ClearBuffer(); } private void DisposeCore() { if (_buffer != null) { _buffer.Dispose(); _buffer = null; } } private unsafe void InsertAtCore(int index, char c) { byte* bufferPtr = null; UnprotectMemory(); try { EnsureCapacity(_decryptedLength + 1); _buffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = _decryptedLength; i > index; i--) { pBuffer[i] = pBuffer[i - 1]; } pBuffer[index] = c; ++_decryptedLength; } finally { ProtectMemory(); if (bufferPtr != null) { _buffer.ReleasePointer(); } } } private unsafe void RemoveAtCore(int index) { byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); char* pBuffer = (char*)bufferPtr; for (int i = index; i < _decryptedLength - 1; i++) { pBuffer[i] = pBuffer[i + 1]; } pBuffer[--_decryptedLength] = (char)0; } finally { ProtectMemory(); if (bufferPtr != null) { _buffer.ReleasePointer(); } } } private void SetAtCore(int index, char c) { UnprotectMemory(); try { _buffer.Write<char>((uint)index * sizeof(char), c); } finally { ProtectMemory(); } } internal unsafe IntPtr MarshalToBSTR() { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); int resultByteLength = (length + 1) * sizeof(char); ptr = Win32Native.SysAllocStringLen(null, length); if (ptr == IntPtr.Zero) { throw new OutOfMemoryException(); } Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); result = ptr; } finally { ProtectMemory(); // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); Win32Native.SysFreeString(ptr); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } internal unsafe IntPtr MarshalToStringCore(bool globalAlloc, bool unicode) { int length = _decryptedLength; IntPtr ptr = IntPtr.Zero; IntPtr result = IntPtr.Zero; byte* bufferPtr = null; UnprotectMemory(); try { _buffer.AcquirePointer(ref bufferPtr); if (unicode) { int resultByteLength = (length + 1) * sizeof(char); ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength); Buffer.MemoryCopy(bufferPtr, (byte*)ptr, resultByteLength, length * sizeof(char)); *(length + (char*)ptr) = '\0'; } else { uint defaultChar = '?'; int resultByteLength = 1 + Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, null, 0, (IntPtr)(&defaultChar), IntPtr.Zero); ptr = globalAlloc ? Marshal.AllocHGlobal(resultByteLength) : Marshal.AllocCoTaskMem(resultByteLength); Interop.Kernel32.WideCharToMultiByte( Interop.Kernel32.CP_ACP, Interop.Kernel32.WC_NO_BEST_FIT_CHARS, (char*)bufferPtr, length, (byte*)ptr, resultByteLength - 1, (IntPtr)(&defaultChar), IntPtr.Zero); *(resultByteLength - 1 + (byte*)ptr) = 0; } result = ptr; } finally { ProtectMemory(); // If we failed for any reason, free the new buffer if (result == IntPtr.Zero && ptr != IntPtr.Zero) { Interop.NtDll.ZeroMemory(ptr, (UIntPtr)(length * sizeof(char))); MarshalFree(ptr, globalAlloc); } if (bufferPtr != null) { _buffer.ReleasePointer(); } } return result; } private void EnsureNotDisposed() { if (_buffer == null) { throw new ObjectDisposedException(GetType().Name); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private const int BlockSize = (int)Interop.Crypt32.CRYPTPROTECTMEMORY_BLOCK_SIZE / sizeof(char); private SafeBSTRHandle _buffer; private bool _encrypted; private void AllocateBuffer(uint size) { _buffer = SafeBSTRHandle.Allocate(GetAlignedSize(size)); } private static uint GetAlignedSize(uint size) => size == 0 || size % BlockSize != 0 ? BlockSize + ((size / BlockSize) * BlockSize) : size; private void EnsureCapacity(int capacity) { if (capacity > MaxLength) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_Capacity); } if (((uint)capacity * sizeof(char)) <= _buffer.ByteLength) { return; } var oldBuffer = _buffer; SafeBSTRHandle newBuffer = SafeBSTRHandle.Allocate(GetAlignedSize((uint)capacity)); SafeBSTRHandle.Copy(oldBuffer, newBuffer, (uint)_decryptedLength * sizeof(char)); _buffer = newBuffer; oldBuffer.Dispose(); } private void ProtectMemory() { Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength != 0 && !_encrypted && !Interop.Crypt32.CryptProtectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } _encrypted = true; } private void UnprotectMemory() { Debug.Assert(!_buffer.IsInvalid, "Invalid buffer!"); if (_decryptedLength != 0 && _encrypted && !Interop.Crypt32.CryptUnprotectMemory(_buffer, _buffer.Length * sizeof(char), Interop.Crypt32.CRYPTPROTECTMEMORY_SAME_PROCESS)) { throw new CryptographicException(Marshal.GetLastWin32Error()); } _encrypted = false; } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections; using System.Collections.Generic; using MindTouch.Dream; using MindTouch.Tasking; using MindTouch.Xml; namespace MindTouch.Deki.Services { using Yield = IEnumerator<IYield>; [DreamService("MindTouch Dapper Extension", "Copyright (c) 2006-2010 MindTouch Inc.", Info = "http://developer.mindtouch.com/App_Catalog/Dapper", SID = new string[] { "sid://mindtouch.com/2007/12/dapper", "http://services.mindtouch.com/deki/draft/2007/12/dapper" } )] [DreamServiceBlueprint("deki/service-type", "extension")] [DekiExtLibrary( Label = "Dapper", Namespace = "dapp", Description = "This extension contains functions for embedding Dapps from Dapper.net.", Logo = "$files/dapper-logo.png" )] [DekiExtLibraryFiles(Prefix = "MindTouch.Deki.Services.Resources", Filenames = new string[] { "sorttable.js", "dapper-logo.png" })] public class DapperService : DekiExtService { //--- Constants --- public const double CACHE_TTL = 30; public const string VARIABLE_PREFIX = "variableArg_"; //--- Fields --- private Dictionary<string, XDoc> _cache = new Dictionary<string, XDoc>(); //--- Functions --- [DekiExtFunction(Description = "Retrieve the XML for a Dapp.")] public Yield Xml( [DekiExtParam("name of Dapp to invoke")] string name, [DekiExtParam("input uri (default: as defined by the Dapp)", true)] XUri input, [DekiExtParam("dapp arguments (default: none)", true)] Hashtable args, Result<XDoc> response ) { Result<XDoc> res; yield return res = Coroutine.Invoke(FetchResult, name, input, args, new Result<XDoc>()); response.Return(res.Value); } [DekiExtFunction(Description = "Show a single value from a Dapp.")] public Yield Value( [DekiExtParam("name of Dapp to invoke")] string name, [DekiExtParam("xpath to select value (default: first field in Dapp)", true)] string xpath, [DekiExtParam("input uri (default: as defined by the Dapp)", true)] XUri input, [DekiExtParam("dapp arguments (default: none)", true)] Hashtable args, Result<object> response ) { Result<XDoc> res; yield return res = Coroutine.Invoke(FetchResult, name, input, args, new Result<XDoc>()); XDoc doc = res.Value; // fetch value from document XDoc value = doc[xpath ?? ".//*[@type='field']"]; response.Return(ConvertDocToValue(value, false)); yield break; } [DekiExtFunction(Description = "Show a single HTML value from a Dapp.")] public Yield Html( [DekiExtParam("name of Dapp to invoke")] string name, [DekiExtParam("xpath to select value (default: first field in Dapp)", true)] string xpath, [DekiExtParam("input uri (default: as defined by the Dapp)", true)] XUri input, [DekiExtParam("dapp arguments (default: none)", true)] Hashtable args, Result<object> response ) { Result<XDoc> res; yield return res = Coroutine.Invoke(FetchResult, name, input, args, new Result<XDoc>()); XDoc doc = res.Value; // fetch value from document XDoc value = doc[xpath ?? ".//*[@type='field']"]; response.Return(ConvertDocToValue(value, true)); yield break; } [DekiExtFunction(Description = "Collect values as a list from a Dapp.")] public Yield List( [DekiExtParam("name of Dapp to invoke")] string name, [DekiExtParam("xpath for collecting values (default: all groups in Dapp)", true)] string xpath, [DekiExtParam("input uri (default: as defined by the Dapp)", true)] XUri input, [DekiExtParam("dapp arguments (default: none)", true)] Hashtable args, Result<ArrayList> response ) { Result<XDoc> res; yield return res = Coroutine.Invoke(FetchResult, name, input, args, new Result<XDoc>()); XDoc doc = res.Value; // fetch values from document ArrayList result = new ArrayList(); foreach(XDoc value in doc[xpath ?? ".//*[@type='group']"]) { result.Add(ConvertDocToValue(value, false)); } response.Return(result); yield break; } [DekiExtFunction(Description = "Show results from a Dapp as a table.")] public Yield Table( [DekiExtParam("name of Dapp to invoke")] string name, [DekiExtParam("xpath for collecting values (default: all groups in Dapp)", true)] string xpath, [DekiExtParam("input uri (default: as defined by the Dapp)", true)] XUri input, [DekiExtParam("dapp arguments (default: none)", true)] Hashtable args, Result<XDoc> response ) { Result<XDoc> res; yield return res = Coroutine.Invoke(FetchResult, name, input, args, new Result<XDoc>()); XDoc doc = res.Value; // fetch value from document XDoc result = new XDoc("html") .Start("head") .Start("script").Attr("type", "text/javascript").Attr("src", Files.At("sorttable.js")).End() .Start("style").Attr("type", "text/css").Value(@".feedtable { border:1px solid #999; line-height:1.5em; overflow:hidden; width:100%; } .feedtable th { background-color:#ddd; border-bottom:1px solid #999; font-size:14px; } .feedtable tr { background-color:#FFFFFF; } .feedtable tr.feedroweven td { background-color:#ededed; }").End() .End() .Start("body"); result.Start("table").Attr("border", 0).Attr("cellpadding", 0).Attr("cellspacing", 0).Attr("class", "feedtable sortable"); XDoc rows = doc[xpath ?? ".//*[@type='group']"]; // create header row result.Start("thead").Start("tr"); foreach(XDoc cell in rows.Elements) { result.Start("th").Elem("strong", cell.Name).End(); } result.End().End(); // create data rows int rowcount = 0; result.Start("tbody"); foreach(XDoc row in rows) { result.Start("tr"); result.Attr("class", ((rowcount++ & 1) == 0) ? "feedroweven" : "feedrowodd"); foreach(XDoc cell in row.Elements) { result.Elem("td", ConvertDocToValue(cell, true)); } result.End(); } result.End(); // close table & body tags result.End().End(); response.Return(result); yield break; } [DekiExtFunction(Description = "Run a Dapp and publish its results.")] [DekiExtFunctionScript("MindTouch.Deki.Services.Resources", "dapper-run.xml")] public XDoc Run( [DekiExtParam("name of Dapp to invoke")] string name, [DekiExtParam("xpath for collecting values (default: all groups in Dapp)", true)] string xpath, [DekiExtParam("input uri (default: as defined by the Dapp)", true)] XUri input, [DekiExtParam("dapp arguments (default: none)", true)] Hashtable args, [DekiExtParam("publish on channel (default: \"default\")", true)] string publish, [DekiExtParam("subscribe to channel (default: nil)", true)] string subscribe ) { throw new InvalidOperationException("this function is implemented as a script"); } //--- Features --- [DreamFeature("POST:proxy/run", "Run Dapp service.")] public Yield PostRun(DreamContext context, DreamMessage request, Result<DreamMessage> response) { XDoc doc = request.ToDocument(); string name = doc["dappName"].AsText; XUri input = doc["applyToUrl"].AsUri; string xpath = doc["xpath"].AsText; // convert args Hashtable args = new Hashtable(); foreach(XDoc item in doc.Elements) { if(StringUtil.StartsWithInvariant(item.Name, VARIABLE_PREFIX)) { args[item.Name.Substring(VARIABLE_PREFIX.Length)] = item.AsText; } } // invoke dapper Result<XDoc> res; yield return res = Coroutine.Invoke(FetchResult, name, input, args, new Result<XDoc>()); // create result document XDoc rows = res.Value[xpath ?? ".//*[@type='group']"]; XDoc result = new XDoc("results"); foreach(XDoc row in rows) { result.Start("result"); foreach(XDoc cell in row.Elements) { result.Elem(cell.Name, cell.AsText); } result.End(); } string json = JsonUtil.ToJson(result); response.Return(DreamMessage.Ok(MimeType.JSON, json)); yield break; } //--- Methods --- private Yield FetchResult(string name, XUri input, Hashtable args, Result<XDoc> response) { // build uri XUri uri = new XUri("http://www.dapper.net/RunDapp?v=1").With("dappName", name); if(input != null) { uri = uri.With("applyToUrl", input.ToString()); } if(args != null) { foreach(DictionaryEntry entry in args) { uri = uri.With(VARIABLE_PREFIX + SysUtil.ChangeType<string>(entry.Key), SysUtil.ChangeType<string>(entry.Value)); } } // check if we have a cached result XDoc result; string key = uri.ToString(); lock(_cache) { if(_cache.TryGetValue(key, out result)) { response.Return(result); yield break; } } // fetch result Result<DreamMessage> res; yield return res = Plug.New(uri).GetAsync(); if(!res.Value.IsSuccessful) { throw new DreamInternalErrorException(string.Format("Unable to process Dapp: ", input)); } if(!res.Value.HasDocument) { throw new DreamInternalErrorException(string.Format("Dapp response is not XML: ", input)); } // add result to cache and start a clean-up timer lock(_cache) { _cache[key] = res.Value.ToDocument(); } TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), RemoveCachedEntry, key, TaskEnv.None); response.Return(res.Value.ToDocument()); yield break; } private object ConvertDocToValue(XDoc value, bool allowxml) { if(value.IsEmpty) { // no value for element return null; } else if(StringUtil.EqualsInvariant(value["@type"].AsText, "group")) { // value is a group Hashtable result = new Hashtable(); foreach(XDoc child in value.Elements) { result[child.Name] = ConvertDocToValue(child, allowxml); } return result; } else { // value is field, determine if the field needs special treatment switch(value["@originalElement"].AsText) { case "a": if(allowxml) { return new XDoc("html").Start("body").Start("a").Attr("href", value["@href"].AsText).Value(value.AsText).End().End(); } else { return value.AsText; } case "img": if(allowxml) { return new XDoc("html").Start("body").Start("img").Attr("src", value["@src"].AsText).Attr("href", value["@href"].AsText).End().End(); } else { return value["@src"].AsText; } default: return value.AsText; } } } private void RemoveCachedEntry(TaskTimer timer) { lock(_cache) { _cache.Remove((string)timer.State); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.SS.Formula; using NPOI.XSSF.UserModel; using System; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.Udf; using System.Collections.Generic; namespace NPOI.XSSF.UserModel { /** * Evaluates formula cells.<p/> * * For performance reasons, this class keeps a cache of all previously calculated intermediate * cell values. Be sure to call {@link #ClearAllCachedResultValues()} if any workbook cells are Changed between * calls to Evaluate~ methods on this class. * * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * @author Josh Micich */ public class XSSFFormulaEvaluator : IFormulaEvaluator, IWorkbookEvaluatorProvider { private WorkbookEvaluator _bookEvaluator; private XSSFWorkbook _book; public XSSFFormulaEvaluator(IWorkbook workbook) : this(workbook as XSSFWorkbook, null, null) { } public XSSFFormulaEvaluator(XSSFWorkbook workbook) : this(workbook, null, null) { } //TODO; will need testing added for streaming public XSSFFormulaEvaluator(WorkbookEvaluator bookEvaluator) { _bookEvaluator = bookEvaluator; } /** * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code> * for the (conservative) assumption that any cell may have its defInition Changed After * Evaluation begins. * @deprecated (Sep 2009) (reduce overloading) use {@link #Create(XSSFWorkbook, NPOI.ss.formula.IStabilityClassifier, NPOI.ss.formula.udf.UDFFinder)} */ public XSSFFormulaEvaluator(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier) { _bookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.Create(workbook), stabilityClassifier, null); _book = workbook; } private XSSFFormulaEvaluator(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { _bookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.Create(workbook), stabilityClassifier, udfFinder); _book = workbook; } /** * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code> * for the (conservative) assumption that any cell may have its defInition Changed After * Evaluation begins. * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only) */ public static XSSFFormulaEvaluator Create(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { return new XSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder); } /** * Should be called whenever there are major Changes (e.g. moving sheets) to input cells * in the Evaluated workbook. * Failure to call this method After changing cell values will cause incorrect behaviour * of the Evaluate~ methods of this class */ public void ClearAllCachedResultValues() { _bookEvaluator.ClearAllCachedResultValues(); } public void NotifySetFormula(ICell cell) { _bookEvaluator.NotifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); } public void NotifyDeleteCell(ICell cell) { _bookEvaluator.NotifyDeleteCell(new XSSFEvaluationCell((XSSFCell)cell)); } public void NotifyUpdateCell(ICell cell) { _bookEvaluator.NotifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); } /** * If cell Contains a formula, the formula is Evaluated and returned, * else the CellValue simply copies the appropriate cell value from * the cell and also its cell type. This method should be preferred over * EvaluateInCell() when the call should not modify the contents of the * original cell. * @param cell */ public CellValue Evaluate(ICell cell) { if (cell == null) { return null; } switch (cell.CellType) { case CellType.Boolean: return CellValue.ValueOf(cell.BooleanCellValue); case CellType.Error: return CellValue.GetError(cell.ErrorCellValue); case CellType.Formula: return EvaluateFormulaCellValue(cell); case CellType.Numeric: return new CellValue(cell.NumericCellValue); case CellType.String: return new CellValue(cell.RichStringCellValue.String); case CellType.Blank: return null; } throw new InvalidOperationException("Bad cell type (" + cell.CellType + ")"); } /** * If cell Contains formula, it Evaluates the formula, * and saves the result of the formula. The cell * remains as a formula cell. * Else if cell does not contain formula, this method leaves * the cell unChanged. * Note that the type of the formula result is returned, * so you know what kind of value is also stored with * the formula. * <pre> * int EvaluatedCellType = Evaluator.EvaluateFormulaCell(cell); * </pre> * Be aware that your cell will hold both the formula, * and the result. If you want the cell Replaced with * the result of the formula, use {@link #Evaluate(NPOI.ss.usermodel.Cell)} } * @param cell The cell to Evaluate * @return The type of the formula result (the cell's type remains as HSSFCell.CELL_TYPE_FORMULA however) */ public CellType EvaluateFormulaCell(ICell cell) { if (cell == null || cell.CellType != CellType.Formula) { return CellType.Unknown; } CellValue cv = EvaluateFormulaCellValue(cell); // cell remains a formula cell, but the cached value is Changed SetCellValue(cell, cv); return cv.CellType; } /** * If cell Contains formula, it Evaluates the formula, and * Puts the formula result back into the cell, in place * of the old formula. * Else if cell does not contain formula, this method leaves * the cell unChanged. * Note that the same instance of HSSFCell is returned to * allow chained calls like: * <pre> * int EvaluatedCellType = Evaluator.EvaluateInCell(cell).CellType; * </pre> * Be aware that your cell value will be Changed to hold the * result of the formula. If you simply want the formula * value computed for you, use {@link #EvaluateFormulaCell(NPOI.ss.usermodel.Cell)} } * @param cell */ public ICell EvaluateInCell(ICell cell) { if (cell == null) { return null; } XSSFCell result = (XSSFCell)cell; if (cell.CellType == CellType.Formula) { CellValue cv = EvaluateFormulaCellValue(cell); SetCellType(cell, cv); // cell will no longer be a formula cell SetCellValue(cell, cv); } return result; } private static void SetCellType(ICell cell, CellValue cv) { CellType cellType = cv.CellType; switch (cellType) { case CellType.Boolean: case CellType.Error: case CellType.Numeric: case CellType.String: cell.SetCellType(cellType); return; case CellType.Blank: // never happens - blanks eventually Get translated to zero case CellType.Formula: // this will never happen, we have already Evaluated the formula break; } throw new InvalidOperationException("Unexpected cell value type (" + cellType + ")"); } private static void SetCellValue(ICell cell, CellValue cv) { CellType cellType = cv.CellType; switch (cellType) { case CellType.Boolean: cell.SetCellValue(cv.BooleanValue); break; case CellType.Error: cell.SetCellErrorValue((byte)cv.ErrorValue); break; case CellType.Numeric: cell.SetCellValue(cv.NumberValue); break; case CellType.String: cell.SetCellValue(new XSSFRichTextString(cv.StringValue)); break; case CellType.Blank: // never happens - blanks eventually Get translated to zero case CellType.Formula: // this will never happen, we have already Evaluated the formula default: throw new InvalidOperationException("Unexpected cell value type (" + cellType + ")"); } } /** * Loops over all cells in all sheets of the supplied * workbook. * For cells that contain formulas, their formulas are * Evaluated, and the results are saved. These cells * remain as formula cells. * For cells that do not contain formulas, no Changes * are made. * This is a helpful wrapper around looping over all * cells, and calling EvaluateFormulaCell on each one. */ public static void EvaluateAllFormulaCells(IWorkbook wb) { HSSFFormulaEvaluator.EvaluateAllFormulaCells(wb); } /** * Loops over all cells in all sheets of the supplied * workbook. * For cells that contain formulas, their formulas are * Evaluated, and the results are saved. These cells * remain as formula cells. * For cells that do not contain formulas, no Changes * are made. * This is a helpful wrapper around looping over all * cells, and calling EvaluateFormulaCell on each one. */ public void EvaluateAll() { HSSFFormulaEvaluator.EvaluateAllFormulaCells(_book); } /** * Returns a CellValue wrapper around the supplied ValueEval instance. */ private CellValue EvaluateFormulaCellValue(ICell cell) { if (!(cell is XSSFCell)) { throw new ArgumentException("Unexpected type of cell: " + cell.GetType() + "." + " Only XSSFCells can be Evaluated."); } ValueEval eval = _bookEvaluator.Evaluate(new XSSFEvaluationCell((XSSFCell)cell)); if (eval is NumberEval) { NumberEval ne = (NumberEval)eval; return new CellValue(ne.NumberValue); } if (eval is BoolEval) { BoolEval be = (BoolEval)eval; return CellValue.ValueOf(be.BooleanValue); } if (eval is StringEval) { StringEval ne = (StringEval)eval; return new CellValue(ne.StringValue); } if (eval is ErrorEval) { return CellValue.GetError(((ErrorEval)eval).ErrorCode); } throw new Exception("Unexpected eval class (" + eval.GetType().Name + ")"); } public void SetupReferencedWorkbooks(Dictionary<String, IFormulaEvaluator> evaluators) { CollaboratingWorkbooksEnvironment.SetupFormulaEvaluator(evaluators); } public WorkbookEvaluator GetWorkbookEvaluator() { return _bookEvaluator; } public bool IgnoreMissingWorkbooks { get { return _bookEvaluator.IgnoreMissingWorkbooks; } set { _bookEvaluator.IgnoreMissingWorkbooks = value; } } public bool DebugEvaluationOutputForNextEval { get { return _bookEvaluator.DebugEvaluationOutputForNextEval; } set { _bookEvaluator.DebugEvaluationOutputForNextEval = (value); } } } }
#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; using System.Collections.Generic; using System.ComponentModel; #if !(NET35 || NET20 || PORTABLE40) using System.Dynamic; #endif using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Serialization { internal class JsonSerializerInternalWriter : JsonSerializerInternalBase { private JsonContract _rootContract; private int _rootLevel; private readonly List<object> _serializeStack = new List<object>(); private JsonSerializerProxy _internalSerializer; public JsonSerializerInternalWriter(JsonSerializer serializer) : base(serializer) { } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { if (jsonWriter == null) throw new ArgumentNullException("jsonWriter"); _rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null; _rootLevel = _serializeStack.Count + 1; JsonContract contract = GetContractSafe(value); try { SerializeValue(jsonWriter, value, contract, null, null, null); } catch (Exception ex) { if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex)) { HandleError(jsonWriter, 0); } else { // clear context in case serializer is being used inside a converter // if the converter wraps the error then not clearing the context will cause this error: // "Current error context error is different to requested error." ClearErrorContext(); throw; } } finally { // clear root contract to ensure that if level was > 1 then it won't // accidently be used for non root values _rootContract = null; } } private JsonSerializerProxy GetInternalSerializer() { if (_internalSerializer == null) _internalSerializer = new JsonSerializerProxy(this); return _internalSerializer; } private JsonContract GetContractSafe(object value) { if (value == null) return null; return Serializer._contractResolver.ResolveContract(value.GetType()); } private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (contract.TypeCode == PrimitiveTypeCode.Bytes) { // if type name handling is enabled then wrap the base64 byte string in an object with the type name bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty); if (includeTypeDetails) { writer.WriteStartObject(); WriteTypeProperty(writer, contract.CreatedType); writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false); JsonWriter.WriteValue(writer, contract.TypeCode, value); writer.WriteEndObject(); return; } } JsonWriter.WriteValue(writer, contract.TypeCode, value); } private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null) { writer.WriteNull(); return; } JsonConverter converter = ((member != null) ? member.Converter : null) ?? ((containerProperty != null) ? containerProperty.ItemConverter : null) ?? ((containerContract != null) ? containerContract.ItemConverter : null) ?? valueContract.Converter ?? Serializer.GetMatchingConverter(valueContract.UnderlyingType) ?? valueContract.InternalConverter; if (converter != null && converter.CanWrite) { SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty); return; } switch (valueContract.ContractType) { case JsonContractType.Object: SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.Array: JsonArrayContract arrayContract = (JsonArrayContract)valueContract; if (!arrayContract.IsMultidimensionalArray) SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty); else SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty); break; case JsonContractType.Primitive: SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty); break; case JsonContractType.String: SerializeString(writer, value, (JsonStringContract)valueContract); break; case JsonContractType.Dictionary: JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract; SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty); break; #if !(NET35 || NET20 || PORTABLE40) case JsonContractType.Dynamic: SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty); break; #endif #if !(NETFX_CORE || PORTABLE40 || PORTABLE) case JsonContractType.Serializable: SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty); break; #endif case JsonContractType.Linq: ((JToken)value).WriteTo(writer, Serializer.Converters.ToArray()); break; } } private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty) { bool? isReference = null; // value could be coming from a dictionary or array and not have a property if (property != null) isReference = property.IsReference; if (isReference == null && containerProperty != null) isReference = containerProperty.ItemIsReference; if (isReference == null && collectionContract != null) isReference = collectionContract.ItemIsReference; if (isReference == null) isReference = contract.IsReference; return isReference; } private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (value == null) return false; if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String) return false; bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty); if (isReference == null) { if (valueContract.ContractType == JsonContractType.Array) isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); else isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); } if (!isReference.Value) return false; return Serializer.GetReferenceResolver().IsReferenced(this, value); } private bool ShouldWriteProperty(object memberValue, JsonProperty property) { if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore && memberValue == null) return false; if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore) && MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue())) return false; return true; } private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty) { if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String) return true; ReferenceLoopHandling? referenceLoopHandling = null; if (property != null) referenceLoopHandling = property.ReferenceLoopHandling; if (referenceLoopHandling == null && containerProperty != null) referenceLoopHandling = containerProperty.ItemReferenceLoopHandling; if (referenceLoopHandling == null && containerContract != null) referenceLoopHandling = containerContract.ItemReferenceLoopHandling; if (_serializeStack.IndexOf(value) != -1) { string message = "Self referencing loop detected"; if (property != null) message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName); message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()); switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling)) { case ReferenceLoopHandling.Error: throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); case ReferenceLoopHandling.Ignore: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null); return false; case ReferenceLoopHandling.Serialize: if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null); return true; } } return true; } private void WriteReference(JsonWriter writer, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null); writer.WriteStartObject(); writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false); writer.WriteValue(reference); writer.WriteEndObject(); } private string GetReference(JsonWriter writer, object value) { try { string reference = Serializer.GetReferenceResolver().GetReference(this, value); return reference; } catch (Exception ex) { throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex); } } internal static bool TryConvertToString(object value, Type type, out string s) { #if !(NETFX_CORE || PORTABLE40 || PORTABLE) TypeConverter converter = ConvertUtils.GetConverter(type); // use the objectType's TypeConverter if it has one and can convert to a string if (converter != null && !(converter is ComponentConverter) && converter.GetType() != typeof(TypeConverter)) { if (converter.CanConvertTo(typeof(string))) { s = converter.ConvertToInvariantString(value); return true; } } #endif #if NETFX_CORE || PORTABLE if (value is Guid || value is Uri || value is TimeSpan) { s = value.ToString(); return true; } #endif if (value is Type) { s = ((Type)value).AssemblyQualifiedName; return true; } s = null; return false; } private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) { OnSerializing(writer, contract, value); string s; TryConvertToString(value, contract.UnderlyingType, out s); writer.WriteValue(s); OnSerialized(writer, contract, value); } private void OnSerializing(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); contract.InvokeOnSerializing(value, Serializer._context); } private void OnSerialized(JsonWriter writer, JsonContract contract, object value) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null); contract.InvokeOnSerialized(value, Serializer._context); } private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; try { object memberValue; JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) continue; property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } if (contract.ExtensionDataGetter != null) { IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value); if (extensionData != null) { foreach (KeyValuePair<object, object> e in extensionData) { JsonContract keyContract = GetContractSafe(e.Key); JsonContract valueContract = GetContractSafe(e.Value); bool escape; string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape); if (ShouldWriteReference(e.Value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName); WriteReference(writer, e.Value); } else { if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member)) continue; writer.WritePropertyName(propertyName); SerializeValue(writer, e.Value, valueContract, null, contract, member); } } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue) { if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value)) { if (property.PropertyContract == null) property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType); memberValue = property.ValueProvider.GetValue(value); memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue); if (ShouldWriteProperty(memberValue, property)) { if (ShouldWriteReference(memberValue, property, memberContract, contract, member)) { property.WritePropertyName(writer); WriteReference(writer, memberValue); return false; } if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member)) return false; if (memberValue == null) { JsonObjectContract objectContract = contract as JsonObjectContract; Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default; if (resolvedRequired == Required.Always) throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null); } return true; } } memberContract = null; memberValue = null; return false; } private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { writer.WriteStartObject(); bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects); // don't make readonly fields the referenced value because they can't be deserialized to if (isReference && (member == null || member.Writable)) { WriteReferenceIdProperty(writer, contract.UnderlyingType, value); } if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty)) { WriteTypeProperty(writer, contract.UnderlyingType); } } private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value) { string reference = GetReference(writer, value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null); writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false); writer.WriteValue(reference); } private void WriteTypeProperty(JsonWriter writer, Type type) { string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null); writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false); writer.WriteValue(typeName); } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag) { return ((value & flag) == flag); } private bool HasFlag(TypeNameHandling value, TypeNameHandling flag) { return ((value & flag) == flag); } private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) { WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty)) return; _serializeStack.Add(value); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); converter.WriteJson(writer, value, GetInternalSerializer()); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null); _serializeStack.RemoveAt(_serializeStack.Count - 1); } } private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { IWrappedCollection wrappedCollection = values as IWrappedCollection; object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values; OnSerializing(writer, contract, underlyingList); _serializeStack.Add(underlyingList); bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty); writer.WriteStartArray(); int initialDepth = writer.Top; int index = 0; // note that an error in the IEnumerable won't be caught foreach (object value in values) { try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } finally { index++; } } writer.WriteEndArray(); if (hasWrittenMetadataObject) writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingList); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, values); _serializeStack.Add(values); bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty); SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]); if (hasWrittenMetadataObject) writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, values); } private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices) { int dimension = indices.Length; int[] newIndices = new int[dimension + 1]; for (int i = 0; i < dimension; i++) { newIndices[i] = indices[i]; } writer.WriteStartArray(); for (int i = 0; i < values.GetLength(dimension); i++) { newIndices[dimension] = i; bool isTopLevel = (newIndices.Length == values.Rank); if (isTopLevel) { object value = values.GetValue(newIndices); try { JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { WriteReference(writer, value); } else { if (CheckForCircularReference(writer, value, null, valueContract, contract, member)) { SerializeValue(writer, value, valueContract, null, contract, member); } } } catch (Exception ex) { if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth + 1); else throw; } } else { SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices); } } writer.WriteEndArray(); } private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays); // don't make readonly fields the referenced value because they can't be deserialized to isReference = (isReference && (member == null || member.Writable)); bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty); bool writeMetadataObject = isReference || includeTypeDetails; if (writeMetadataObject) { writer.WriteStartObject(); if (isReference) { WriteReferenceIdProperty(writer, contract.UnderlyingType, values); } if (includeTypeDetails) { WriteTypeProperty(writer, values.GetType()); } writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false); } if (contract.ItemContract == null) contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object)); return writeMetadataObject; } #if !(NETFX_CORE || PORTABLE40 || PORTABLE) #if !(NET20 || NET35) [SecuritySafeCritical] #endif private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { if (!JsonTypeReflector.FullyTrusted) { string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine + @"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine; message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType()); throw JsonSerializationException.Create(null, writer.ContainerPath, message, null); } OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter()); value.GetObjectData(serializationInfo, Serializer._context); foreach (SerializationEntry serializationEntry in serializationInfo) { JsonContract valueContract = GetContractSafe(serializationEntry.Value); if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); WriteReference(writer, serializationEntry.Value); } else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member)) { writer.WritePropertyName(serializationEntry.Name); SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member); } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } #endif #if !(NET35 || NET20 || PORTABLE40) private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { OnSerializing(writer, contract, value); _serializeStack.Add(value); WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty); int initialDepth = writer.Top; for (int index = 0; index < contract.Properties.Count; index++) { JsonProperty property = contract.Properties[index]; // only write non-dynamic properties that have an explicit attribute if (property.HasMemberAttribute) { try { object memberValue; JsonContract memberContract; if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue)) continue; property.WritePropertyName(writer); SerializeValue(writer, memberValue, memberContract, property, contract, member); } catch (Exception ex) { if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } } foreach (string memberName in value.GetDynamicMemberNames()) { object memberValue; if (contract.TryGetMember(value, memberName, out memberValue)) { try { JsonContract valueContract = GetContractSafe(memberValue); if (!ShouldWriteDynamicProperty(memberValue)) continue; if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member)) { string resolvedPropertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(memberName) : memberName; writer.WritePropertyName(resolvedPropertyName); SerializeValue(writer, memberValue, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, value); } #endif private bool ShouldWriteDynamicProperty(object memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) return false; if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) && (memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType())))) return false; return true; } private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) { TypeNameHandling resolvedTypeNameHandling = ((member != null) ? member.TypeNameHandling : null) ?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null) ?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null) ?? Serializer._typeNameHandling; if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag)) return true; // instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default) if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto)) { if (member != null) { if (contract.UnderlyingType != member.PropertyContract.CreatedType) return true; } else if (containerContract != null) { if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType) return true; } else if (_rootContract != null && _serializeStack.Count == _rootLevel) { if (contract.UnderlyingType != _rootContract.CreatedType) return true; } } return false; } private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) { IWrappedDictionary wrappedDictionary = values as IWrappedDictionary; object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values; OnSerializing(writer, contract, underlyingDictionary); _serializeStack.Add(underlyingDictionary); WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty); if (contract.ItemContract == null) contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object)); if (contract.KeyContract == null) contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object)); int initialDepth = writer.Top; foreach (DictionaryEntry entry in values) { bool escape; string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape); propertyName = (contract.PropertyNameResolver != null) ? contract.PropertyNameResolver(propertyName) : propertyName; try { object value = entry.Value; JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value); if (ShouldWriteReference(value, null, valueContract, contract, member)) { writer.WritePropertyName(propertyName, escape); WriteReference(writer, value); } else { if (!CheckForCircularReference(writer, value, null, valueContract, contract, member)) continue; writer.WritePropertyName(propertyName, escape); SerializeValue(writer, value, valueContract, null, contract, member); } } catch (Exception ex) { if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex)) HandleError(writer, initialDepth); else throw; } } writer.WriteEndObject(); _serializeStack.RemoveAt(_serializeStack.Count - 1); OnSerialized(writer, contract, underlyingDictionary); } private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) { string propertyName; if (contract.ContractType == JsonContractType.Primitive) { JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract; if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable) { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } #if !NET20 else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable) { escape = false; StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture); return sw.ToString(); } #endif else { escape = true; return Convert.ToString(name, CultureInfo.InvariantCulture); } } else if (TryConvertToString(name, name.GetType(), out propertyName)) { escape = true; return propertyName; } else { escape = true; return name.ToString(); } } private void HandleError(JsonWriter writer, int initialDepth) { ClearErrorContext(); if (writer.WriteState == WriteState.Property) writer.WriteNull(); while (writer.Top > initialDepth) { writer.WriteEnd(); } } private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target) { if (property.ShouldSerialize == null) return true; bool shouldSerialize = property.ShouldSerialize(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null); return shouldSerialize; } private bool IsSpecified(JsonWriter writer, JsonProperty property, object target) { if (property.GetIsSpecified == null) return true; bool isSpecified = property.GetIsSpecified(target); if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null); return isSpecified; } } }
// // 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. // #if !WINDOWS_PHONE_7 namespace NLog.UnitTests.Internal.NetworkSenders { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif using NLog.Internal.NetworkSenders; [TestFixture] public class TcpNetworkSenderTests : NLogTestBase { [Test] public void TcpHappyPathTest() { foreach (bool async in new[] { false, true }) { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { Async = async, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new List<Exception>(); for (int i = 1; i < 8; i *= 2) { sender.Send( buffer, 0, i, ex => { lock (exceptions) exceptions.Add(ex); }); } var mre = new ManualResetEvent(false); sender.FlushAsync(ex => { lock (exceptions) { exceptions.Add(ex); } mre.Set(); }); mre.WaitOne(); string expectedLog = @"Parse endpoint address tcp://hostname:123/ Unspecified create socket 10000 Stream Tcp connect async to {mock end point: tcp://hostname:123/} send async 0 1 'q' send async 0 2 'qu' send async 0 4 'quic' "; Assert.AreEqual(expectedLog, sender.Log.ToString()); mre.Reset(); for (int i = 1; i < 8; i *= 2) { sender.Send( buffer, 0, i, ex => { lock (exceptions) exceptions.Add(ex); }); } sender.Close(ex => { lock (exceptions) { exceptions.Add(ex); } mre.Set(); }); mre.WaitOne(); expectedLog = @"Parse endpoint address tcp://hostname:123/ Unspecified create socket 10000 Stream Tcp connect async to {mock end point: tcp://hostname:123/} send async 0 1 'q' send async 0 2 'qu' send async 0 4 'quic' send async 0 1 'q' send async 0 2 'qu' send async 0 4 'quic' close "; Assert.AreEqual(expectedLog, sender.Log.ToString()); foreach (var ex in exceptions) { Assert.IsNull(ex); } } } [Test] public void TcpProxyTest() { var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified); var socket = sender.CreateSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.IsInstanceOfType(typeof(SocketProxy), socket); } [Test] public void TcpConnectFailureTest() { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { ConnectFailure = 1, Async = true, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new List<Exception>(); var allSent = new ManualResetEvent(false); for (int i = 1; i < 8; i++) { sender.Send( buffer, 0, i, ex => { lock (exceptions) { exceptions.Add(ex); if (exceptions.Count == 7) { allSent.Set(); } } }); } #if SILVERLIGHT Assert.IsTrue(allSent.WaitOne(3000)); #else Assert.IsTrue(allSent.WaitOne(3000, false)); #endif var mre = new ManualResetEvent(false); sender.FlushAsync(ex => mre.Set()); #if SILVERLIGHT mre.WaitOne(3000); #else mre.WaitOne(3000, false); #endif string expectedLog = @"Parse endpoint address tcp://hostname:123/ Unspecified create socket 10000 Stream Tcp connect async to {mock end point: tcp://hostname:123/} failed "; Assert.AreEqual(expectedLog, sender.Log.ToString()); foreach (var ex in exceptions) { Assert.IsNotNull(ex); } } [Test] public void TcpSendFailureTest() { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { SendFailureIn = 3, // will cause failure on 3rd send Async = true, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new Exception[9]; var writeFinished = new ManualResetEvent(false); int remaining = exceptions.Length; for (int i = 1; i < 10; i++) { int pos = i - 1; sender.Send( buffer, 0, i, ex => { lock (exceptions) { exceptions[pos] = ex; if (--remaining == 0) { writeFinished.Set(); } } }); } var mre = new ManualResetEvent(false); writeFinished.WaitOne(); sender.Close(ex => mre.Set()); mre.WaitOne(); string expectedLog = @"Parse endpoint address tcp://hostname:123/ Unspecified create socket 10000 Stream Tcp connect async to {mock end point: tcp://hostname:123/} send async 0 1 'q' send async 0 2 'qu' send async 0 3 'qui' failed close "; Assert.AreEqual(expectedLog, sender.Log.ToString()); for (int i = 0; i < exceptions.Length; ++i) { if (i < 2) { Assert.IsNull(exceptions[i], "EXCEPTION: " + exceptions[i]); } else { Assert.IsNotNull(exceptions[i]); } } } internal class MyTcpNetworkSender : TcpNetworkSender { public StringWriter Log { get; set; } public MyTcpNetworkSender(string url, AddressFamily addressFamily) : base(url, addressFamily) { this.Log = new StringWriter(); } protected internal override ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return new MockSocket(addressFamily, socketType, protocolType, this); } protected override EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily) { this.Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily); return new MockEndPoint(uri); } public int ConnectFailure { get; set; } public bool Async { get; set; } public int SendFailureIn { get; set; } } internal class MockSocket : ISocket { private readonly MyTcpNetworkSender sender; private readonly StringWriter log; private bool faulted = false; public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender) { this.sender = sender; this.log = sender.Log; this.log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType); } public bool ConnectAsync(SocketAsyncEventArgs args) { this.log.WriteLine("connect async to {0}", args.RemoteEndPoint); lock (this) { if (this.sender.ConnectFailure > 0) { this.sender.ConnectFailure--; this.faulted = true; args.SocketError = SocketError.SocketError; this.log.WriteLine("failed"); } } return InvokeCallback(args); } private bool InvokeCallback(SocketAsyncEventArgs args) { lock (this) { var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs; if (this.sender.Async) { ThreadPool.QueueUserWorkItem(s => { Thread.Sleep(10); args2.RaiseCompleted(); }); return true; } else { return false; } } } public void Close() { lock (this) { this.log.WriteLine("close"); } } public bool SendAsync(SocketAsyncEventArgs args) { lock (this) { this.log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count)); if (this.sender.SendFailureIn > 0) { this.sender.SendFailureIn--; if (this.sender.SendFailureIn == 0) { this.faulted = true; } } if (this.faulted) { this.log.WriteLine("failed"); args.SocketError = SocketError.SocketError; } } return InvokeCallback(args); } public bool SendToAsync(SocketAsyncEventArgs args) { lock (this) { this.log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint); return InvokeCallback(args); } } } internal class MockEndPoint : EndPoint { private readonly Uri uri; public MockEndPoint(Uri uri) { this.uri = uri; } public override AddressFamily AddressFamily { get { return (System.Net.Sockets.AddressFamily)10000; } } public override string ToString() { return "{mock end point: " + this.uri + "}"; } } } } #endif
// // System.Diagnostics.EventLogImpl.cs // // Authors: // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // Atsushi Enomoto <atsushi@ximian.com> // Gert Driesen (drieseng@users.sourceforge.net) // // (C) 2003 Andreas Nahr // (C) 2006 Novell, Inc. // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using Microsoft.Win32; namespace System.Diagnostics { internal abstract class EventLogImpl { readonly EventLog _coreEventLog; protected EventLogImpl (EventLog coreEventLog) { _coreEventLog = coreEventLog; } protected EventLog CoreEventLog { get { return _coreEventLog; } } public int EntryCount { get { if (_coreEventLog.Log == null || _coreEventLog.Log.Length == 0) { throw new ArgumentException ("Log property is not set."); } if (!EventLog.Exists (_coreEventLog.Log, _coreEventLog.MachineName)) { throw new InvalidOperationException (string.Format ( CultureInfo.InvariantCulture, "The event log '{0}' on " + " computer '{1}' does not exist.", _coreEventLog.Log, _coreEventLog.MachineName)); } return GetEntryCount (); } } public EventLogEntry this[int index] { get { if (_coreEventLog.Log == null || _coreEventLog.Log.Length == 0) { throw new ArgumentException ("Log property is not set."); } if (!EventLog.Exists (_coreEventLog.Log, _coreEventLog.MachineName)) { throw new InvalidOperationException (string.Format ( CultureInfo.InvariantCulture, "The event log '{0}' on " + " computer '{1}' does not exist.", _coreEventLog.Log, _coreEventLog.MachineName)); } if (index < 0 || index >= EntryCount) throw new ArgumentException ("Index out of range"); return GetEntry (index); } } public string LogDisplayName { get { // to-do perform valid character checks if (_coreEventLog.Log != null && _coreEventLog.Log.Length == 0) { throw new InvalidOperationException ("Event log names must" + " consist of printable characters and cannot contain" + " \\, *, ?, or spaces."); } if (_coreEventLog.Log != null) { if (_coreEventLog.Log.Length == 0) return string.Empty; if (!EventLog.Exists (_coreEventLog.Log, _coreEventLog.MachineName)) { throw new InvalidOperationException (string.Format ( CultureInfo.InvariantCulture, "Cannot find Log {0}" + " on computer {1}.", _coreEventLog.Log, _coreEventLog.MachineName)); } } return GetLogDisplayName (); } } public EventLogEntry [] GetEntries () { string logName = CoreEventLog.Log; if (logName == null || logName.Length == 0) throw new ArgumentException ("Log property value has not been specified."); if (!EventLog.Exists (logName)) throw new InvalidOperationException (string.Format ( CultureInfo.InvariantCulture, "The event log '{0}' on " + " computer '{1}' does not exist.", logName, _coreEventLog.MachineName)); int entryCount = GetEntryCount (); EventLogEntry [] entries = new EventLogEntry [entryCount]; for (int i = 0; i < entryCount; i++) { entries [i] = GetEntry (i); } return entries; } public abstract void DisableNotification (); public abstract void EnableNotification (); public abstract void BeginInit (); public abstract void Clear (); public abstract void Close (); public abstract void CreateEventSource (EventSourceCreationData sourceData); public abstract void Delete (string logName, string machineName); public abstract void DeleteEventSource (string source, string machineName); public abstract void Dispose (bool disposing); public abstract void EndInit (); public abstract bool Exists (string logName, string machineName); protected abstract int GetEntryCount (); protected abstract EventLogEntry GetEntry (int index); public EventLog [] GetEventLogs (string machineName) { string [] logNames = GetLogNames (machineName); EventLog [] eventLogs = new EventLog [logNames.Length]; for (int i = 0; i < logNames.Length; i++) { EventLog eventLog = new EventLog (logNames [i], machineName); eventLogs [i] = eventLog; } return eventLogs; } protected abstract string GetLogDisplayName (); public abstract string LogNameFromSourceName (string source, string machineName); public abstract bool SourceExists (string source, string machineName); public abstract void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte[] rawData); protected abstract string FormatMessage (string source, uint messageID, string [] replacementStrings); protected abstract string [] GetLogNames (string machineName); protected void ValidateCustomerLogName (string logName, string machineName) { if (logName.Length >= 8) { string significantName = logName.Substring (0, 8); if (string.Compare (significantName, "AppEvent", true) == 0 || string.Compare (significantName, "SysEvent", true) == 0 || string.Compare (significantName, "SecEvent", true) == 0) throw new ArgumentException (string.Format ( CultureInfo.InvariantCulture, "The log name: '{0}' is" + " invalid for customer log creation.", logName)); // the first 8 characters of the log name are used as filename // for .evt file and as such no two logs with 8 characters or // more should have the same first 8 characters (or the .evt // would be overwritten) // // this check is not strictly necessary on unix string [] logs = GetLogNames (machineName); for (int i = 0; i < logs.Length; i++) { string log = logs [i]; if (log.Length >= 8 && string.Compare (log, 0, significantName, 0, 8, true) == 0) throw new ArgumentException (string.Format ( CultureInfo.InvariantCulture, "Only the first eight" + " characters of a custom log name are significant," + " and there is already another log on the system" + " using the first eight characters of the name given." + " Name given: '{0}', name of existing log: '{1}'.", logName, log)); } } // LAMESPEC: check if the log name matches an existing source // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=186552 if (SourceExists (logName, machineName)) { if (machineName == ".") throw new ArgumentException (string.Format ( CultureInfo.InvariantCulture, "Log {0} has already been" + " registered as a source on the local computer.", logName)); else throw new ArgumentException (string.Format ( CultureInfo.InvariantCulture, "Log {0} has already been" + " registered as a source on the computer {1}.", logName, machineName)); } } public abstract OverflowAction OverflowAction { get; } public abstract int MinimumRetentionDays { get; } public abstract long MaximumKilobytes { get; set; } public abstract void ModifyOverflowPolicy (OverflowAction action, int retentionDays); public abstract void RegisterDisplayName (string resourceFile, long resourceId); } }
using System; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Diagnostics; using System.IO; namespace McBits.LibNutrition { public class DatabaseCreator { private string _connectionString; public DatabaseCreator(string connectionString) { _connectionString = connectionString; } public void CreateDatabaseSchema(string sqlFileName) { try { var sql = File.ReadAllText(sqlFileName); using (var conn = new SqlConnection(_connectionString)) { var cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } catch (IOException ex) { Debug.WriteLine($"Failed to read SQL file '{sqlFileName}': {ex.ToString()}"); } } public void PopulateFoodGroups() { var reader = new UsdaReader(); reader.ReadData("FD_GROUP.txt.gz", PopulateFoodGroupsCallback); } public void PopulateSourceCodes() { var reader = new UsdaReader(); reader.ReadData("SRC_CD.txt.gz", PopulateSourceCodesCallback); } public void PopulateDerivationCodes() { var reader = new UsdaReader(); reader.ReadData("DERIV_CD.txt.gz", PopulateDerivationCodesCallback); } public void PopulateFoods() { var reader = new UsdaReader(); reader.ReadData("FOOD_DES.txt.gz", PopulateFoodsCallback); } public void PopulateNutrients() { var reader = new UsdaReader(); reader.ReadData("NUTR_DEF.txt.gz", PopulateNutrientsCallback); } public void PopulateNutrientDataPoints() { var reader = new UsdaReader(); reader.ReadData("NUT_DATA.txt.gz", PopulateNutrientDataPointsCallback); } public void PopulateFoodWeights() { var reader = new UsdaReader(); reader.ReadData("WEIGHT.txt.gz", PopulateFoodWeightsCallback); } public void PopulateLanguaLFactors() { var reader = new UsdaReader(); reader.ReadData("LANGDESC.txt.gz", PopulateLanguaLFactorsCallback); } public void PopulateFoods_LanguaLFactors() { var reader = new UsdaReader(); reader.ReadData("LANGUAL.txt.gz", PopulateFoods_LanguaLFactorsCallback); } public void PopulateDataSources() { var reader = new UsdaReader(); reader.ReadData("DATA_SRC.txt.gz", PopulateDataSourcesCallback); } public void PopulateFoods_Nutrients_DataSources() { var reader = new UsdaReader(); reader.ReadData("DATSRCLN.txt.gz", PopulateFoods_Nutrients_DataSourcesCallback); } public void PopulateFootnotes() { var reader = new UsdaReader(); reader.ReadData("FOOTNOTE.txt.gz", PopulateFootnotesCallback); } public void PopulateFootnotesCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [Footnotes] ([FoodId], [FootnoteId], [FootnoteType], [NutrientId], [FootnoteText]) VALUES (@FoodId, @FootnoteId, @FootnoteType, @NutrientId, @FootnoteText);"; cmd.Parameters.Add("@FoodId", SqlDbType.Char); cmd.Parameters["@FoodId"].Value = parts[0]; cmd.Parameters.Add("@FootnoteId", SqlDbType.Char); cmd.Parameters["@FootnoteId"].Value = parts[1]; cmd.Parameters.Add("@FootnoteType", SqlDbType.Char); cmd.Parameters["@FootnoteType"].Value = parts[2]; cmd.Parameters.Add("@NutrientId", SqlDbType.Char); cmd.Parameters["@NutrientId"].Value = string.IsNullOrEmpty(parts[4]) ? DBNull.Value : (object)parts[3]; cmd.Parameters.Add("@FootnoteText", SqlDbType.NVarChar); cmd.Parameters["@FootnoteText"].Value = parts[4]; cmd.ExecuteNonQuery(); } } public void PopulateFoods_Nutrients_DataSourcesCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [Foods_Nutrients_DataSources] ([FoodId], [NutrientId], [DataSourceId]) VALUES (@FoodId, @NutrientId, @DataSourceId);"; cmd.Parameters.Add("@FoodId", SqlDbType.Char); cmd.Parameters["@FoodId"].Value = parts[0]; cmd.Parameters.Add("@NutrientId", SqlDbType.Char); cmd.Parameters["@NutrientId"].Value = parts[1]; cmd.Parameters.Add("@DataSourceId", SqlDbType.Char); cmd.Parameters["@DataSourceId"].Value = parts[2]; cmd.ExecuteNonQuery(); } } public void PopulateDataSourcesCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [DataSources] ([Id], [Authors], [Title], [Year], [Journal], [VolumeCity], [IssueState], [StartPage], [EndPage]) VALUES (@Id, @Authors, @Title, @Year, @Journal, @VolumeCity, @IssueState, @StartPage, @EndPage);"; cmd.Parameters.Add("@Id", SqlDbType.Char); cmd.Parameters["@Id"].Value = parts[0]; cmd.Parameters.Add("@Authors", SqlDbType.NVarChar); cmd.Parameters["@Authors"].Value = string.IsNullOrEmpty(parts[1]) ? DBNull.Value : (object)parts[1]; cmd.Parameters.Add("@Title", SqlDbType.NVarChar); cmd.Parameters["@Title"].Value = parts[2]; cmd.Parameters.Add("@Year", SqlDbType.Char); cmd.Parameters["@Year"].Value = string.IsNullOrEmpty(parts[3]) ? DBNull.Value : (object)parts[3]; cmd.Parameters.Add("@Journal", SqlDbType.NVarChar); cmd.Parameters["@Journal"].Value = string.IsNullOrEmpty(parts[4]) ? DBNull.Value : (object)parts[4]; cmd.Parameters.Add("@VolumeCity", SqlDbType.NVarChar); cmd.Parameters["@VolumeCity"].Value = string.IsNullOrEmpty(parts[5]) ? DBNull.Value : (object)parts[5]; cmd.Parameters.Add("@IssueState", SqlDbType.Char); cmd.Parameters["@IssueState"].Value = string.IsNullOrEmpty(parts[6]) ? DBNull.Value : (object)parts[6]; cmd.Parameters.Add("@StartPage", SqlDbType.Char); cmd.Parameters["@StartPage"].Value = string.IsNullOrEmpty(parts[7]) ? DBNull.Value : (object)parts[7]; cmd.Parameters.Add("@EndPage", SqlDbType.Char); cmd.Parameters["@EndPage"].Value = string.IsNullOrEmpty(parts[8]) ? DBNull.Value : (object)parts[8]; cmd.ExecuteNonQuery(); } } public void PopulateFoods_LanguaLFactorsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [Foods_LanguaLFactors] ([FoodId], [LanguaLFactorId]) VALUES (@FoodId, @LanguaLFactorId);"; cmd.Parameters.Add("@FoodId", SqlDbType.Char); cmd.Parameters["@FoodId"].Value = parts[0]; cmd.Parameters.Add("@LanguaLFactorId", SqlDbType.NVarChar); cmd.Parameters["@LanguaLFactorId"].Value = parts[1]; cmd.ExecuteNonQuery(); } } public void PopulateLanguaLFactorsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [LanguaLFactors] ([Id], [Description]) VALUES (@Id, @Description);"; cmd.Parameters.Add("@Id", SqlDbType.Char); cmd.Parameters["@Id"].Value = parts[0]; cmd.Parameters.Add("@Description", SqlDbType.NVarChar); cmd.Parameters["@Description"].Value = parts[1]; cmd.ExecuteNonQuery(); } } public void PopulateDerivationCodesCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [DerivationCodes] ([Id], [Description]) VALUES (@Id, @Description);"; cmd.Parameters.Add("@Id", SqlDbType.Char); cmd.Parameters["@Id"].Value = parts[0]; cmd.Parameters.Add("@Description", SqlDbType.NVarChar); cmd.Parameters["@Description"].Value = parts[1]; cmd.ExecuteNonQuery(); } } public void PopulateSourceCodesCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [SourceCodes] ([Id], [Description]) VALUES (@Id, @Description);"; cmd.Parameters.Add("@Id", SqlDbType.Char); cmd.Parameters["@Id"].Value = parts[0]; cmd.Parameters.Add("@Description", SqlDbType.NVarChar); cmd.Parameters["@Description"].Value = parts[1]; cmd.ExecuteNonQuery(); } } public void PopulateFoodGroupsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [FoodGroups] ([Id], [Description]) VALUES (@Id, @Description);"; cmd.Parameters.Add("@Id", SqlDbType.Char); cmd.Parameters["@Id"].Value = parts[0]; cmd.Parameters.Add("@Description", SqlDbType.NVarChar); cmd.Parameters["@Description"].Value = parts[1]; cmd.ExecuteNonQuery(); } } public void PopulateFoodWeightsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [FoodWeights] ([FoodId], [SequenceNumber], [Amount], [MsreDescription], [Grams], [DataPointCount], [StdDeviation]) VALUES (@FoodId, @SequenceNumber, @Amount, @MsreDescription, @Grams, @DataPointCount, @StdDeviation);"; cmd.Parameters.Add("@FoodId", SqlDbType.Char); cmd.Parameters["@FoodId"].Value = parts[0]; cmd.Parameters.Add("@SequenceNumber", SqlDbType.TinyInt); cmd.Parameters["@SequenceNumber"].Value = int.Parse(parts[1]); cmd.Parameters.Add("@Amount", SqlDbType.Decimal); cmd.Parameters["@Amount"].Value = double.Parse(parts[2]); cmd.Parameters.Add("@MsreDescription", SqlDbType.NVarChar); cmd.Parameters["@MsreDescription"].Value = parts[3]; cmd.Parameters.Add("@Grams", SqlDbType.Decimal); cmd.Parameters["@Grams"].Value = double.Parse(parts[4]); cmd.Parameters.Add("@DataPointCount", SqlDbType.Int); cmd.Parameters["@DataPointCount"].Value = string.IsNullOrEmpty(parts[5]) ? DBNull.Value : (object)(int?)int.Parse(parts[5]); cmd.Parameters.Add("@StdDeviation", SqlDbType.Decimal); cmd.Parameters["@StdDeviation"].Value = string.IsNullOrEmpty(parts[6]) ? DBNull.Value : (object)(double?)double.Parse(parts[6]); cmd.ExecuteNonQuery(); } } public void PopulateNutrientDataPointsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [NutrientDataPoints] ([FoodId], [NutrientId], [NutrientValue], [DataPointCount], [StdError], [SourceCodeId], [DerivationCodeId], [RefFoodId], [AddedNutrient], [StudyCount], [MinValue], [MaxValue], [DegreesOfFreedom], [LowerErrorBound], [UpperErrorBound], [StatisticalComments], [DateModified], [ConfidenceCode]) VALUES (@foodId, @nutrientId, @nutrientValue, @dataPointCount, @stdError, @sourceCode, @derivationCode, @refFoodId, @addedNutrient, @studyCount, @minValue, @maxValue, @degreesOfFreedom, @lowerErrorBound, @upperErrorBound, @statisticalComments, @dateModified, @confidenceCode);"; cmd.Parameters.Add("@foodId", SqlDbType.Char); cmd.Parameters["@foodId"].Value = parts[0]; cmd.Parameters.Add("@nutrientId", SqlDbType.Char); cmd.Parameters["@nutrientId"].Value = parts[1]; cmd.Parameters.Add("@nutrientValue", SqlDbType.Decimal); cmd.Parameters["@nutrientValue"].Value = double.Parse(parts[2]); cmd.Parameters.Add("@dataPointCount", SqlDbType.Decimal); cmd.Parameters["@dataPointCount"].Value = int.Parse(parts[3]); cmd.Parameters.Add("@stdError", SqlDbType.Decimal); cmd.Parameters["@stdError"].Value = string.IsNullOrEmpty(parts[4]) ? DBNull.Value : (object)(double?)double.Parse(parts[4]); cmd.Parameters.Add("@sourceCode", SqlDbType.Char); cmd.Parameters["@sourceCode"].Value = parts[5]; cmd.Parameters.Add("@derivationCode", SqlDbType.Char); cmd.Parameters["@derivationCode"].Value = string.IsNullOrEmpty(parts[6]) ? DBNull.Value : (object)parts[6]; cmd.Parameters.Add("@refFoodId", SqlDbType.NChar); cmd.Parameters["@refFoodId"].Value = string.IsNullOrEmpty(parts[7]) ? DBNull.Value : (object)parts[7]; cmd.Parameters.Add("@addedNutrient", SqlDbType.Char); cmd.Parameters["@addedNutrient"].Value = string.IsNullOrEmpty(parts[8]) ? DBNull.Value : (object)parts[8]; cmd.Parameters.Add("@studyCount", SqlDbType.Decimal); cmd.Parameters["@studyCount"].Value = string.IsNullOrEmpty(parts[9]) ? DBNull.Value : (object)(int?)int.Parse(parts[9]); cmd.Parameters.Add("@minvalue", SqlDbType.Decimal); cmd.Parameters["@minvalue"].Value = string.IsNullOrEmpty(parts[10]) ? DBNull.Value : (object)(double?)double.Parse(parts[10]); cmd.Parameters.Add("@maxValue", SqlDbType.Decimal); cmd.Parameters["@maxValue"].Value = string.IsNullOrEmpty(parts[11]) ? DBNull.Value : (object)(double?)double.Parse(parts[11]); cmd.Parameters.Add("@degreesOfFreedom", SqlDbType.Decimal); cmd.Parameters["@degreesOfFreedom"].Value = string.IsNullOrEmpty(parts[12]) ? DBNull.Value : (object)(int?)int.Parse(parts[12]); cmd.Parameters.Add("@lowerErrorBound", SqlDbType.Decimal); cmd.Parameters["@lowerErrorBound"].Value = string.IsNullOrEmpty(parts[13]) ? DBNull.Value : (object)(double?)double.Parse(parts[13]); cmd.Parameters.Add("@upperErrorBound", SqlDbType.Decimal); cmd.Parameters["@upperErrorBound"].Value = string.IsNullOrEmpty(parts[14]) ? DBNull.Value : (object)(double?)double.Parse(parts[14]); cmd.Parameters.Add("@statisticalComments", SqlDbType.NChar); cmd.Parameters["@statisticalComments"].Value = string.IsNullOrEmpty(parts[15]) ? DBNull.Value : (object)parts[15]; cmd.Parameters.Add("@dateModified", SqlDbType.Date); cmd.Parameters["@dateModified"].Value = string.IsNullOrEmpty(parts[16]) ? DBNull.Value : (object)(DateTime?)DateTime.Parse(parts[16]); cmd.Parameters.Add("@confidenceCode", SqlDbType.Char); cmd.Parameters["@confidenceCode"].Value = string.IsNullOrEmpty(parts[17]) ? DBNull.Value : (object)parts[17]; cmd.ExecuteNonQuery(); } } public void PopulateNutrientsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [Nutrients] ([Id], [Units], [Tagname], [Description], [DecimalPlaces], [SrOrder]) VALUES (@nutrientId, @units, @tagname, @description, @decimalPlaces, @srOrder);"; cmd.Parameters.Add("@nutrientId", SqlDbType.Char); cmd.Parameters["@nutrientId"].Value = parts[0]; cmd.Parameters.Add("@units", SqlDbType.Char); cmd.Parameters["@units"].Value = parts[1]; cmd.Parameters.Add("@tagname", SqlDbType.Char); cmd.Parameters["@tagname"].Value = (object)parts[2] ?? DBNull.Value; cmd.Parameters.Add("@description", SqlDbType.NVarChar); cmd.Parameters["@description"].Value = parts[3]; cmd.Parameters.Add("@decimalPlaces", SqlDbType.Char); cmd.Parameters["@decimalPlaces"].Value = parts[4]; cmd.Parameters.Add("@srOrder", SqlDbType.Decimal); cmd.Parameters["@srOrder"].Value = string.IsNullOrEmpty(parts[5]) ? DBNull.Value : (object)(int?)int.Parse(parts[5]); cmd.ExecuteNonQuery(); } } public void PopulateFoodsCallback(string[] parts) { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = @" INSERT INTO [Foods] ([Id], [FoodGroupId], [LongDescription], [ShortDescription], [CommonNames], [ManufacturerName], [Survey], [RefuseDescription], [Refuse], [ScientificName], [NitrogenFactor], [ProteinFactor], [FatFactor], [CarbFactor]) VALUES (@foodId, @foodGroupId, @longDescription, @shortDescription, @commonName, @manufacturerName, @survey, @refuseDescription, @refuse, @sciName, @nitrogenFactor, @proteinFactor, @fatFactor, @carbohydrateFactor);"; cmd.Parameters.AddWithValue("@foodId", parts[0]); cmd.Parameters.AddWithValue("@foodGroupId", parts[1]); cmd.Parameters.AddWithValue("@longDescription", parts[2]); cmd.Parameters.AddWithValue("@shortDescription", parts[3]); cmd.Parameters.Add("@commonName", SqlDbType.NVarChar); cmd.Parameters["@commonName"].Value = (object)parts[4] ?? DBNull.Value; cmd.Parameters.Add("@manufacturerName", SqlDbType.NVarChar); cmd.Parameters["@manufacturerName"].Value = (object)parts[5] ?? DBNull.Value; cmd.Parameters.Add("@survey", SqlDbType.Bit); cmd.Parameters["@survey"].Value = parts[6] == "Y"; cmd.Parameters.Add("@refuseDescription", SqlDbType.NVarChar); cmd.Parameters["@refuseDescription"].Value = (object)parts[7] ?? DBNull.Value; cmd.Parameters.Add("@refuse", SqlDbType.TinyInt); cmd.Parameters["@refuse"].Value = double.TryParse(parts[8], out var refuse) ? (object)refuse : DBNull.Value; cmd.Parameters.Add("@sciName", SqlDbType.NVarChar); cmd.Parameters["@sciName"].Value = (object)parts[9] ?? DBNull.Value; cmd.Parameters.Add("@nitrogenFactor", SqlDbType.Decimal); cmd.Parameters["@nitrogenFactor"].Value = double.TryParse(parts[10], out var nitrogenFactor) ? (object)nitrogenFactor : DBNull.Value; cmd.Parameters.Add("@proteinFactor", SqlDbType.Decimal); cmd.Parameters["@proteinFactor"].Value = double.TryParse(parts[11], out var proteinFactor) ? (object)proteinFactor : DBNull.Value; cmd.Parameters.Add("@fatFactor", SqlDbType.Decimal); cmd.Parameters["@fatFactor"].Value = double.TryParse(parts[12], out var fatFactor) ? (object)fatFactor : DBNull.Value; cmd.Parameters.Add("@carbohydrateFactor", SqlDbType.Decimal); cmd.Parameters["@carbohydrateFactor"].Value = double.TryParse(parts[13], out var carbohydrateFactor) ? (object)carbohydrateFactor : DBNull.Value; cmd.ExecuteNonQuery(); } } public int CountFoods() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from Foods"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountNutrients() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from Nutrients"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountNutrientDataPoints() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from NutrientDataPoints"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountFoodWeights() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from FoodWeights"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountFoodGroups() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from FoodGroups"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountSourceCodes() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from SourceCodes"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountDerivationCodes() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from DerivationCodes"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountLanguaLFactors() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from LanguaLFactors"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountFoods_LanguaLFactors() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from Foods_LanguaLFactors"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountDataSources() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from DataSources"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountFoods_Nutrients_DataSources() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from Foods_Nutrients_DataSources"; var result = cmd.ExecuteScalar(); return (int)result; } } public int CountFootnotes() { using (var conn = new SqlConnection(_connectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from Footnotes"; var result = cmd.ExecuteScalar(); return (int)result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Collections.Tests { /// <summary> /// Contains tests that ensure the correctness of the LinkedList class. /// </summary> public abstract partial class LinkedList_Generic_Tests<T> : ICollection_Generic_Tests<T> { [Fact] public void AddAfter_LLNode() { LinkedList<T> linkedList = new LinkedList<T>(); int arraySize = 16; int seed = 8293; T[] tempItems, headItems, headItemsReverse, tailItems; headItems = new T[arraySize]; tailItems = new T[arraySize]; headItemsReverse = new T[arraySize]; for (int i = 0; i < arraySize; i++) { int index = (arraySize - 1) - i; T head = CreateT(seed++); T tail = CreateT(seed++); headItems[i] = head; headItemsReverse[index] = head; tailItems[i] = tail; } //[] Verify value is default(T) linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddAfter(linkedList.First, default(T)); InitialItems_Tests(linkedList, new T[] { headItems[0], default(T) }); //[] Node is the Head linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 0, tempItems, 0, headItems.Length); Array.Reverse(tempItems, 1, headItems.Length - 1); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.First, headItems[i]); InitialItems_Tests(linkedList, tempItems); //[] Node is the Tail linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, headItems[i]); InitialItems_Tests(linkedList, headItems); //[] Node is after the Head linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 0, tempItems, 0, headItems.Length); Array.Reverse(tempItems, 2, headItems.Length - 2); for (int i = 2; i < arraySize; ++i) linkedList.AddAfter(linkedList.First.Next, headItems[i]); InitialItems_Tests(linkedList, tempItems); //[] Node is before the Tail linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 2, tempItems, 1, headItems.Length - 2); tempItems[0] = headItems[0]; tempItems[tempItems.Length - 1] = headItems[1]; for (int i = 2; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last.Previous, headItems[i]); InitialItems_Tests(linkedList, tempItems); //[] Node is somewhere in the middle linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 3, tempItems, 1, headItems.Length - 3); tempItems[0] = headItems[0]; tempItems[tempItems.Length - 2] = headItems[1]; tempItems[tempItems.Length - 1] = headItems[2]; for (int i = 3; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last.Previous.Previous, headItems[i]); InitialItems_Tests(linkedList, tempItems); //[] Call AddAfter several times remove some of the items linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, headItems[i]); linkedList.Remove(headItems[2]); linkedList.Remove(headItems[headItems.Length - 3]); linkedList.Remove(headItems[1]); linkedList.Remove(headItems[headItems.Length - 2]); linkedList.RemoveFirst(); linkedList.RemoveLast(); //With the above remove we should have removed the first and last 3 items tempItems = new T[headItems.Length - 6]; Array.Copy(headItems, 3, tempItems, 0, headItems.Length - 6); InitialItems_Tests(linkedList, tempItems); for (int i = 0; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, tailItems[i]); T[] tempItems2 = new T[tempItems.Length + tailItems.Length]; Array.Copy(tempItems, 0, tempItems2, 0, tempItems.Length); Array.Copy(tailItems, 0, tempItems2, tempItems.Length, tailItems.Length); InitialItems_Tests(linkedList, tempItems2); //[] Call AddAfter several times remove all of the items linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, headItems[i]); for (int i = 0; i < arraySize; ++i) linkedList.RemoveFirst(); linkedList.AddFirst(tailItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, tailItems[i]); InitialItems_Tests(linkedList, tailItems); //[] Call AddAfter several times then call Clear linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, headItems[i]); linkedList.Clear(); linkedList.AddFirst(tailItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, tailItems[i]); InitialItems_Tests(linkedList, tailItems); //[] Mix AddBefore and AddAfter calls linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); linkedList.AddLast(tailItems[0]); for (int i = 1; i < arraySize; ++i) { linkedList.AddBefore(linkedList.First, headItems[i]); linkedList.AddAfter(linkedList.Last, tailItems[i]); } tempItems = new T[headItemsReverse.Length + tailItems.Length]; Array.Copy(headItemsReverse, 0, tempItems, 0, headItemsReverse.Length); Array.Copy(tailItems, 0, tempItems, headItemsReverse.Length, tailItems.Length); InitialItems_Tests(linkedList, tempItems); } [Fact] public void AddAfter_LLNode_Negative() { LinkedList<T> linkedList = new LinkedList<T>(); LinkedList<T> tempLinkedList = new LinkedList<T>(); int seed = 8293; T[] items; //[] Verify Null node linkedList = new LinkedList<T>(); Assert.Throws<ArgumentNullException>(() => linkedList.AddAfter(null, CreateT(seed++))); //"Err_858ahia Expected null node to throws ArgumentNullException\n" InitialItems_Tests(linkedList, new T[0]); //[] Verify Node that is a new Node linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++) }; linkedList.AddLast(items[0]); Assert.Throws<InvalidOperationException>(() => linkedList.AddAfter(new LinkedListNode<T>(CreateT(seed++)), CreateT(seed++))); //"Err_0568ajods Expected Node that is a new Node throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); //[] Verify Node that already exists in another collection linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++), CreateT(seed++) }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); tempLinkedList.Clear(); tempLinkedList.AddLast(CreateT(seed++)); tempLinkedList.AddLast(CreateT(seed++)); Assert.Throws<InvalidOperationException>(() => linkedList.AddAfter(tempLinkedList.Last, CreateT(seed++))); //"Err_98809ahied Node that already exists in another collection throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); } [Fact] public void AddAfter_LLNode_LLNode() { LinkedList<T> linkedList = new LinkedList<T>(); int seed = 8293; int arraySize = 16; T[] tempItems, headItems, headItemsReverse, tailItems, tailItemsReverse; headItems = new T[arraySize]; tailItems = new T[arraySize]; headItemsReverse = new T[arraySize]; tailItemsReverse = new T[arraySize]; for (int i = 0; i < arraySize; i++) { int index = (arraySize - 1) - i; T head = CreateT(seed++); T tail = CreateT(seed++); headItems[i] = head; headItemsReverse[index] = head; tailItems[i] = tail; tailItemsReverse[index] = tail; } //[] Verify value is default(T) linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddAfter(linkedList.First, new LinkedListNode<T>(default(T))); InitialItems_Tests(linkedList, new T[] { headItems[0], default(T) }); //[] Node is the Head linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 0, tempItems, 0, headItems.Length); Array.Reverse(tempItems, 1, headItems.Length - 1); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.First, new LinkedListNode<T>(headItems[i])); InitialItems_Tests(linkedList, tempItems); //[] Node is the Tail linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(headItems[i])); InitialItems_Tests(linkedList, headItems); //[] Node is after the Head linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 0, tempItems, 0, headItems.Length); Array.Reverse(tempItems, 2, headItems.Length - 2); for (int i = 2; i < arraySize; ++i) linkedList.AddAfter(linkedList.First.Next, new LinkedListNode<T>(headItems[i])); InitialItems_Tests(linkedList, tempItems); //[] Node is before the Tail linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 2, tempItems, 1, headItems.Length - 2); tempItems[0] = headItems[0]; tempItems[tempItems.Length - 1] = headItems[1]; for (int i = 2; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last.Previous, new LinkedListNode<T>(headItems[i])); InitialItems_Tests(linkedList, tempItems); //[] Node is somewhere in the middle linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); linkedList.AddLast(headItems[1]); linkedList.AddLast(headItems[2]); tempItems = new T[headItems.Length]; Array.Copy(headItems, 3, tempItems, 1, headItems.Length - 3); tempItems[0] = headItems[0]; tempItems[tempItems.Length - 2] = headItems[1]; tempItems[tempItems.Length - 1] = headItems[2]; for (int i = 3; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last.Previous.Previous, new LinkedListNode<T>(headItems[i])); InitialItems_Tests(linkedList, tempItems); //[] Call AddAfter several times remove some of the items linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(headItems[i])); linkedList.Remove(headItems[2]); linkedList.Remove(headItems[headItems.Length - 3]); linkedList.Remove(headItems[1]); linkedList.Remove(headItems[headItems.Length - 2]); linkedList.RemoveFirst(); linkedList.RemoveLast(); //With the above remove we should have removed the first and last 3 items tempItems = new T[headItems.Length - 6]; Array.Copy(headItems, 3, tempItems, 0, headItems.Length - 6); InitialItems_Tests(linkedList, tempItems); for (int i = 0; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(tailItems[i])); T[] tempItems2 = new T[tempItems.Length + tailItems.Length]; Array.Copy(tempItems, 0, tempItems2, 0, tempItems.Length); Array.Copy(tailItems, 0, tempItems2, tempItems.Length, tailItems.Length); InitialItems_Tests(linkedList, tempItems2); //[] Call AddAfter several times remove all of the items linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(headItems[i])); for (int i = 0; i < arraySize; ++i) linkedList.RemoveFirst(); linkedList.AddFirst(tailItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(tailItems[i])); InitialItems_Tests(linkedList, tailItems); //[] Call AddAfter several times then call Clear linkedList = new LinkedList<T>(); linkedList.AddFirst(headItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(headItems[i])); linkedList.Clear(); linkedList.AddFirst(tailItems[0]); for (int i = 1; i < arraySize; ++i) linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(tailItems[i])); InitialItems_Tests(linkedList, tailItems); //[] Mix AddBefore and AddAfter calls linkedList = new LinkedList<T>(); linkedList.AddLast(headItems[0]); linkedList.AddLast(tailItems[0]); for (int i = 1; i < arraySize; ++i) { if (0 == (i & 1)) { linkedList.AddBefore(linkedList.First, headItems[i]); linkedList.AddAfter(linkedList.Last, tailItems[i]); } else { linkedList.AddBefore(linkedList.First, new LinkedListNode<T>(headItems[i])); linkedList.AddAfter(linkedList.Last, new LinkedListNode<T>(tailItems[i])); } } tempItems = new T[headItemsReverse.Length + tailItems.Length]; Array.Copy(headItemsReverse, 0, tempItems, 0, headItemsReverse.Length); Array.Copy(tailItems, 0, tempItems, headItemsReverse.Length, tailItems.Length); InitialItems_Tests(linkedList, tempItems); } [Fact] public void AddAfter_LLNode_LLNode_Negative() { LinkedList<T> linkedList = new LinkedList<T>(); LinkedList<T> tempLinkedList = new LinkedList<T>(); int seed = 8293; T[] items; //[] Verify Null node linkedList = new LinkedList<T>(); Assert.Throws<ArgumentNullException>(() => linkedList.AddAfter(null, new LinkedListNode<T>(CreateT(seed++)))); //"Err_858ahia Expected null node to throws ArgumentNullException\n" InitialItems_Tests(linkedList, new T[0]); //[] Verify Node that is a new Node linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++) }; linkedList.AddLast(items[0]); Assert.Throws<InvalidOperationException>(() => linkedList.AddAfter(new LinkedListNode<T>(CreateT(seed++)), new LinkedListNode<T>(CreateT(seed++)))); //"Err_0568ajods Expected Node that is a new Node throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); //[] Verify Node that already exists in another collection linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++), CreateT(seed++) }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); tempLinkedList.Clear(); tempLinkedList.AddLast(CreateT(seed++)); tempLinkedList.AddLast(CreateT(seed++)); Assert.Throws<InvalidOperationException>(() => linkedList.AddAfter(tempLinkedList.Last, new LinkedListNode<T>(CreateT(seed++)))); //"Err_98809ahied Node that already exists in another collection throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); // negative tests on NewNode //[] Verify Null newNode linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++) }; linkedList.AddLast(items[0]); Assert.Throws<ArgumentNullException>(() => linkedList.AddAfter(linkedList.First, null)); //"Err_0808ajeoia Expected null newNode to throws ArgumentNullException\n" InitialItems_Tests(linkedList, items); //[] Verify newNode that already exists in this collection linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++), CreateT(seed++) }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); Assert.Throws<InvalidOperationException>(() => linkedList.AddAfter(linkedList.First, linkedList.Last)); //"Err_58808adjioe Verify newNode that already exists in this collection throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); //[] Verify newNode that already exists in another collection linkedList = new LinkedList<T>(); items = new T[] { CreateT(seed++), CreateT(seed++) }; linkedList.AddLast(items[0]); linkedList.AddLast(items[1]); tempLinkedList.Clear(); tempLinkedList.AddLast(CreateT(seed++)); tempLinkedList.AddLast(CreateT(seed++)); Assert.Throws<InvalidOperationException>(() => linkedList.AddAfter(linkedList.First, tempLinkedList.Last)); //"Err_54808ajied newNode that already exists in another collection throws InvalidOperationException\n" InitialItems_Tests(linkedList, items); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; using SharpDX.DXGI; namespace SharpDX.Toolkit.Graphics { /// <summary> /// PixelFormat is equivalent to <see cref="SharpDX.DXGI.Format"/>. /// </summary> /// <remarks> /// This structure is implicitly castable to and from <see cref="SharpDX.DXGI.Format"/>, you can use it inplace where <see cref="SharpDX.DXGI.Format"/> is required /// and vice-versa. /// Usage is slightly different from <see cref="SharpDX.DXGI.Format"/>, as you have to select the type of the pixel format first (<see cref="Typeless"/>, <see cref="SInt"/>...etc) /// and then access the available pixel formats for this type. Example: PixelFormat.UNorm.R8. /// </remarks> /// <msdn-id>bb173059</msdn-id> /// <unmanaged>DXGI_FORMAT</unmanaged> /// <unmanaged-short>DXGI_FORMAT</unmanaged-short> [StructLayout(LayoutKind.Sequential, Size = 4)] public struct PixelFormat : IEquatable<PixelFormat> { /// <summary> /// Gets the value as a <see cref="SharpDX.DXGI.Format"/> enum. /// </summary> public readonly Format Value; /// <summary> /// Internal constructor. /// </summary> /// <param name="format"></param> private PixelFormat(Format format) { this.Value = format; } public int SizeInBytes { get { return (int)FormatHelper.SizeOfInBytes(this); } } public static readonly PixelFormat Unknown = new PixelFormat(Format.Unknown); public static class A8 { #region Constants and Fields public static readonly PixelFormat UNorm = new PixelFormat(Format.A8_UNorm); #endregion } public static class B5G5R5A1 { #region Constants and Fields public static readonly PixelFormat UNorm = new PixelFormat(Format.B5G5R5A1_UNorm); #endregion } public static class B5G6R5 { #region Constants and Fields public static readonly PixelFormat UNorm = new PixelFormat(Format.B5G6R5_UNorm); #endregion } public static class B8G8R8A8 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.B8G8R8A8_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.B8G8R8A8_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.B8G8R8A8_UNorm_SRgb); #endregion } public static class B8G8R8X8 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.B8G8R8X8_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.B8G8R8X8_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.B8G8R8X8_UNorm_SRgb); #endregion } public static class BC1 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC1_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC1_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC1_UNorm_SRgb); #endregion } public static class BC2 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC2_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC2_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC2_UNorm_SRgb); #endregion } public static class BC3 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC3_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC3_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC3_UNorm_SRgb); #endregion } public static class BC4 { #region Constants and Fields public static readonly PixelFormat SNorm = new PixelFormat(Format.BC4_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.BC4_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC4_UNorm); #endregion } public static class BC5 { #region Constants and Fields public static readonly PixelFormat SNorm = new PixelFormat(Format.BC5_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.BC5_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC5_UNorm); #endregion } public static class BC6H { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC6H_Typeless); #endregion } public static class BC7 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.BC7_Typeless); public static readonly PixelFormat UNorm = new PixelFormat(Format.BC7_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.BC7_UNorm_SRgb); #endregion } public static class R10G10B10A2 { #region Constants and Fields public static readonly PixelFormat Typeless = new PixelFormat(Format.R10G10B10A2_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R10G10B10A2_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R10G10B10A2_UNorm); #endregion } public static class R11G11B10 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R11G11B10_Float); #endregion } public static class R16 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R16_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R16_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R16_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R16_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R16_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R16_UNorm); #endregion } public static class R16G16 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R16G16_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R16G16_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R16G16_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R16G16_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R16G16_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R16G16_UNorm); #endregion } public static class R16G16B16A16 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R16G16B16A16_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R16G16B16A16_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R16G16B16A16_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R16G16B16A16_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R16G16B16A16_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R16G16B16A16_UNorm); #endregion } public static class R32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32_UInt); #endregion } public static class R32G32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32G32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32G32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32G32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32G32_UInt); #endregion } public static class R32G32B32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32G32B32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32G32B32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32G32B32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32G32B32_UInt); #endregion } public static class R32G32B32A32 { #region Constants and Fields public static readonly PixelFormat Float = new PixelFormat(Format.R32G32B32A32_Float); public static readonly PixelFormat SInt = new PixelFormat(Format.R32G32B32A32_SInt); public static readonly PixelFormat Typeless = new PixelFormat(Format.R32G32B32A32_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R32G32B32A32_UInt); #endregion } public static class R8 { #region Constants and Fields public static readonly PixelFormat SInt = new PixelFormat(Format.R8_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R8_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R8_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R8_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R8_UNorm); #endregion } public static class R8G8 { #region Constants and Fields public static readonly PixelFormat SInt = new PixelFormat(Format.R8G8_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R8G8_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R8G8_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R8G8_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R8G8_UNorm); #endregion } public static class R8G8B8A8 { #region Constants and Fields public static readonly PixelFormat SInt = new PixelFormat(Format.R8G8B8A8_SInt); public static readonly PixelFormat SNorm = new PixelFormat(Format.R8G8B8A8_SNorm); public static readonly PixelFormat Typeless = new PixelFormat(Format.R8G8B8A8_Typeless); public static readonly PixelFormat UInt = new PixelFormat(Format.R8G8B8A8_UInt); public static readonly PixelFormat UNorm = new PixelFormat(Format.R8G8B8A8_UNorm); public static readonly PixelFormat UNormSRgb = new PixelFormat(Format.R8G8B8A8_UNorm_SRgb); #endregion } public static implicit operator Format(PixelFormat from) { return from.Value; } public static implicit operator PixelFormat(Format from) { return new PixelFormat(from); } public bool Equals(PixelFormat other) { return Value == other.Value; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is PixelFormat && Equals((PixelFormat) obj); } public override int GetHashCode() { return Value.GetHashCode(); } public static bool operator ==(PixelFormat left, PixelFormat right) { return left.Equals(right); } public static bool operator !=(PixelFormat left, PixelFormat right) { return !left.Equals(right); } public override string ToString() { return string.Format("{0}", Value); } } }
/* '=============================================================================== ' Generated From - CSharp_dOOdads_BusinessEntity.vbgen ' ' ** IMPORTANT ** ' How to Generate your stored procedures: ' ' SQL = SQL_StoredProcs.vbgen ' ACCESS = Access_StoredProcs.vbgen ' ORACLE = Oracle_StoredProcs.vbgen ' FIREBIRD = FirebirdStoredProcs.vbgen ' ' The supporting base class OleDbEntity is in the Architecture directory in "dOOdads". ' ' This object is 'abstract' which means you need to inherit from it to be able ' to instantiate it. This is very easilly done. You can override properties and ' methods in your derived class, this allows you to regenerate this class at any ' time and not worry about overwriting custom code. ' ' NEVER EDIT THIS FILE. ' ' public class YourObject : _YourObject ' { ' ' } ' '=============================================================================== */ // Generated by MyGeneration Version # (1.0.0.4) using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Collections.Specialized; using MyGeneration.dOOdads; namespace CSharp.ACCESS { public abstract class _Employees : OleDbEntity { public _Employees() { this.QuerySource = "Employees"; this.MappingName = "Employees"; } //================================================================= // public Overrides void AddNew() //================================================================= // //================================================================= public override void AddNew() { base.AddNew(); } public override string GetAutoKeyColumn() { return "EmployeeID"; } public override void FlushData() { this._whereClause = null; base.FlushData(); } //================================================================= // public Function LoadAll() As Boolean //================================================================= // Loads all of the records in the database, and sets the currentRow to the first row //================================================================= public bool LoadAll() { ListDictionary parameters = null; return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_EmployeesLoadAll]", parameters); } //================================================================= // public Overridable Function LoadByPrimaryKey() As Boolean //================================================================= // Loads a single row of via the primary key //================================================================= public virtual bool LoadByPrimaryKey(int EmployeeID) { ListDictionary parameters = new ListDictionary(); parameters.Add(Parameters.EmployeeID, EmployeeID); return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_EmployeesLoadByPrimaryKey]", parameters); } #region Parameters protected class Parameters { public static OleDbParameter EmployeeID { get { return new OleDbParameter("@EmployeeID", OleDbType.Numeric, 0); } } public static OleDbParameter LastName { get { return new OleDbParameter("@LastName", OleDbType.VarWChar, 20); } } public static OleDbParameter FirstName { get { return new OleDbParameter("@FirstName", OleDbType.VarWChar, 10); } } public static OleDbParameter Title { get { return new OleDbParameter("@Title", OleDbType.VarWChar, 30); } } public static OleDbParameter TitleOfCourtesy { get { return new OleDbParameter("@TitleOfCourtesy", OleDbType.VarWChar, 25); } } public static OleDbParameter BirthDate { get { return new OleDbParameter("@BirthDate", OleDbType.Date, 0); } } public static OleDbParameter HireDate { get { return new OleDbParameter("@HireDate", OleDbType.Date, 0); } } public static OleDbParameter Address { get { return new OleDbParameter("@Address", OleDbType.VarWChar, 60); } } public static OleDbParameter City { get { return new OleDbParameter("@City", OleDbType.VarWChar, 15); } } public static OleDbParameter Region { get { return new OleDbParameter("@Region", OleDbType.VarWChar, 15); } } public static OleDbParameter PostalCode { get { return new OleDbParameter("@PostalCode", OleDbType.VarWChar, 10); } } public static OleDbParameter Country { get { return new OleDbParameter("@Country", OleDbType.VarWChar, 15); } } public static OleDbParameter HomePhone { get { return new OleDbParameter("@HomePhone", OleDbType.VarWChar, 24); } } public static OleDbParameter Extension { get { return new OleDbParameter("@Extension", OleDbType.VarWChar, 4); } } public static OleDbParameter Photo { get { return new OleDbParameter("@Photo", OleDbType.LongVarBinary, 0); } } public static OleDbParameter Notes { get { return new OleDbParameter("@Notes", OleDbType.LongVarWChar, 0); } } public static OleDbParameter ReportsTo { get { return new OleDbParameter("@ReportsTo", OleDbType.Numeric, 0); } } } #endregion #region ColumnNames public class ColumnNames { public const string EmployeeID = "EmployeeID"; public const string LastName = "LastName"; public const string FirstName = "FirstName"; public const string Title = "Title"; public const string TitleOfCourtesy = "TitleOfCourtesy"; public const string BirthDate = "BirthDate"; public const string HireDate = "HireDate"; public const string Address = "Address"; public const string City = "City"; public const string Region = "Region"; public const string PostalCode = "PostalCode"; public const string Country = "Country"; public const string HomePhone = "HomePhone"; public const string Extension = "Extension"; public const string Photo = "Photo"; public const string Notes = "Notes"; public const string ReportsTo = "ReportsTo"; static public string ToPropertyName(string columnName) { if(ht == null) { ht = new Hashtable(); ht[EmployeeID] = _Employees.PropertyNames.EmployeeID; ht[LastName] = _Employees.PropertyNames.LastName; ht[FirstName] = _Employees.PropertyNames.FirstName; ht[Title] = _Employees.PropertyNames.Title; ht[TitleOfCourtesy] = _Employees.PropertyNames.TitleOfCourtesy; ht[BirthDate] = _Employees.PropertyNames.BirthDate; ht[HireDate] = _Employees.PropertyNames.HireDate; ht[Address] = _Employees.PropertyNames.Address; ht[City] = _Employees.PropertyNames.City; ht[Region] = _Employees.PropertyNames.Region; ht[PostalCode] = _Employees.PropertyNames.PostalCode; ht[Country] = _Employees.PropertyNames.Country; ht[HomePhone] = _Employees.PropertyNames.HomePhone; ht[Extension] = _Employees.PropertyNames.Extension; ht[Photo] = _Employees.PropertyNames.Photo; ht[Notes] = _Employees.PropertyNames.Notes; ht[ReportsTo] = _Employees.PropertyNames.ReportsTo; } return (string)ht[columnName]; } static private Hashtable ht = null; } #endregion #region PropertyNames public class PropertyNames { public const string EmployeeID = "EmployeeID"; public const string LastName = "LastName"; public const string FirstName = "FirstName"; public const string Title = "Title"; public const string TitleOfCourtesy = "TitleOfCourtesy"; public const string BirthDate = "BirthDate"; public const string HireDate = "HireDate"; public const string Address = "Address"; public const string City = "City"; public const string Region = "Region"; public const string PostalCode = "PostalCode"; public const string Country = "Country"; public const string HomePhone = "HomePhone"; public const string Extension = "Extension"; public const string Photo = "Photo"; public const string Notes = "Notes"; public const string ReportsTo = "ReportsTo"; static public string ToColumnName(string propertyName) { if(ht == null) { ht = new Hashtable(); ht[EmployeeID] = _Employees.ColumnNames.EmployeeID; ht[LastName] = _Employees.ColumnNames.LastName; ht[FirstName] = _Employees.ColumnNames.FirstName; ht[Title] = _Employees.ColumnNames.Title; ht[TitleOfCourtesy] = _Employees.ColumnNames.TitleOfCourtesy; ht[BirthDate] = _Employees.ColumnNames.BirthDate; ht[HireDate] = _Employees.ColumnNames.HireDate; ht[Address] = _Employees.ColumnNames.Address; ht[City] = _Employees.ColumnNames.City; ht[Region] = _Employees.ColumnNames.Region; ht[PostalCode] = _Employees.ColumnNames.PostalCode; ht[Country] = _Employees.ColumnNames.Country; ht[HomePhone] = _Employees.ColumnNames.HomePhone; ht[Extension] = _Employees.ColumnNames.Extension; ht[Photo] = _Employees.ColumnNames.Photo; ht[Notes] = _Employees.ColumnNames.Notes; ht[ReportsTo] = _Employees.ColumnNames.ReportsTo; } return (string)ht[propertyName]; } static private Hashtable ht = null; } #endregion #region StringPropertyNames public class StringPropertyNames { public const string EmployeeID = "s_EmployeeID"; public const string LastName = "s_LastName"; public const string FirstName = "s_FirstName"; public const string Title = "s_Title"; public const string TitleOfCourtesy = "s_TitleOfCourtesy"; public const string BirthDate = "s_BirthDate"; public const string HireDate = "s_HireDate"; public const string Address = "s_Address"; public const string City = "s_City"; public const string Region = "s_Region"; public const string PostalCode = "s_PostalCode"; public const string Country = "s_Country"; public const string HomePhone = "s_HomePhone"; public const string Extension = "s_Extension"; public const string Notes = "s_Notes"; public const string ReportsTo = "s_ReportsTo"; } #endregion #region Properties public virtual int EmployeeID { get { return base.Getint(ColumnNames.EmployeeID); } set { base.Setint(ColumnNames.EmployeeID, value); } } public virtual string LastName { get { return base.Getstring(ColumnNames.LastName); } set { base.Setstring(ColumnNames.LastName, value); } } public virtual string FirstName { get { return base.Getstring(ColumnNames.FirstName); } set { base.Setstring(ColumnNames.FirstName, value); } } public virtual string Title { get { return base.Getstring(ColumnNames.Title); } set { base.Setstring(ColumnNames.Title, value); } } public virtual string TitleOfCourtesy { get { return base.Getstring(ColumnNames.TitleOfCourtesy); } set { base.Setstring(ColumnNames.TitleOfCourtesy, value); } } public virtual DateTime BirthDate { get { return base.GetDateTime(ColumnNames.BirthDate); } set { base.SetDateTime(ColumnNames.BirthDate, value); } } public virtual DateTime HireDate { get { return base.GetDateTime(ColumnNames.HireDate); } set { base.SetDateTime(ColumnNames.HireDate, value); } } public virtual string Address { get { return base.Getstring(ColumnNames.Address); } set { base.Setstring(ColumnNames.Address, value); } } public virtual string City { get { return base.Getstring(ColumnNames.City); } set { base.Setstring(ColumnNames.City, value); } } public virtual string Region { get { return base.Getstring(ColumnNames.Region); } set { base.Setstring(ColumnNames.Region, value); } } public virtual string PostalCode { get { return base.Getstring(ColumnNames.PostalCode); } set { base.Setstring(ColumnNames.PostalCode, value); } } public virtual string Country { get { return base.Getstring(ColumnNames.Country); } set { base.Setstring(ColumnNames.Country, value); } } public virtual string HomePhone { get { return base.Getstring(ColumnNames.HomePhone); } set { base.Setstring(ColumnNames.HomePhone, value); } } public virtual string Extension { get { return base.Getstring(ColumnNames.Extension); } set { base.Setstring(ColumnNames.Extension, value); } } public virtual byte[] Photo { get { return base.GetByteArray(ColumnNames.Photo); } set { base.SetByteArray(ColumnNames.Photo, value); } } public virtual string Notes { get { return base.Getstring(ColumnNames.Notes); } set { base.Setstring(ColumnNames.Notes, value); } } public virtual int ReportsTo { get { return base.Getint(ColumnNames.ReportsTo); } set { base.Setint(ColumnNames.ReportsTo, value); } } #endregion #region String Properties public virtual string s_EmployeeID { get { return this.IsColumnNull(ColumnNames.EmployeeID) ? string.Empty : base.GetintAsString(ColumnNames.EmployeeID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.EmployeeID); else this.EmployeeID = base.SetintAsString(ColumnNames.EmployeeID, value); } } public virtual string s_LastName { get { return this.IsColumnNull(ColumnNames.LastName) ? string.Empty : base.GetstringAsString(ColumnNames.LastName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.LastName); else this.LastName = base.SetstringAsString(ColumnNames.LastName, value); } } public virtual string s_FirstName { get { return this.IsColumnNull(ColumnNames.FirstName) ? string.Empty : base.GetstringAsString(ColumnNames.FirstName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.FirstName); else this.FirstName = base.SetstringAsString(ColumnNames.FirstName, value); } } public virtual string s_Title { get { return this.IsColumnNull(ColumnNames.Title) ? string.Empty : base.GetstringAsString(ColumnNames.Title); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Title); else this.Title = base.SetstringAsString(ColumnNames.Title, value); } } public virtual string s_TitleOfCourtesy { get { return this.IsColumnNull(ColumnNames.TitleOfCourtesy) ? string.Empty : base.GetstringAsString(ColumnNames.TitleOfCourtesy); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.TitleOfCourtesy); else this.TitleOfCourtesy = base.SetstringAsString(ColumnNames.TitleOfCourtesy, value); } } public virtual string s_BirthDate { get { return this.IsColumnNull(ColumnNames.BirthDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.BirthDate); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.BirthDate); else this.BirthDate = base.SetDateTimeAsString(ColumnNames.BirthDate, value); } } public virtual string s_HireDate { get { return this.IsColumnNull(ColumnNames.HireDate) ? string.Empty : base.GetDateTimeAsString(ColumnNames.HireDate); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.HireDate); else this.HireDate = base.SetDateTimeAsString(ColumnNames.HireDate, value); } } public virtual string s_Address { get { return this.IsColumnNull(ColumnNames.Address) ? string.Empty : base.GetstringAsString(ColumnNames.Address); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Address); else this.Address = base.SetstringAsString(ColumnNames.Address, value); } } public virtual string s_City { get { return this.IsColumnNull(ColumnNames.City) ? string.Empty : base.GetstringAsString(ColumnNames.City); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.City); else this.City = base.SetstringAsString(ColumnNames.City, value); } } public virtual string s_Region { get { return this.IsColumnNull(ColumnNames.Region) ? string.Empty : base.GetstringAsString(ColumnNames.Region); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Region); else this.Region = base.SetstringAsString(ColumnNames.Region, value); } } public virtual string s_PostalCode { get { return this.IsColumnNull(ColumnNames.PostalCode) ? string.Empty : base.GetstringAsString(ColumnNames.PostalCode); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.PostalCode); else this.PostalCode = base.SetstringAsString(ColumnNames.PostalCode, value); } } public virtual string s_Country { get { return this.IsColumnNull(ColumnNames.Country) ? string.Empty : base.GetstringAsString(ColumnNames.Country); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Country); else this.Country = base.SetstringAsString(ColumnNames.Country, value); } } public virtual string s_HomePhone { get { return this.IsColumnNull(ColumnNames.HomePhone) ? string.Empty : base.GetstringAsString(ColumnNames.HomePhone); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.HomePhone); else this.HomePhone = base.SetstringAsString(ColumnNames.HomePhone, value); } } public virtual string s_Extension { get { return this.IsColumnNull(ColumnNames.Extension) ? string.Empty : base.GetstringAsString(ColumnNames.Extension); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Extension); else this.Extension = base.SetstringAsString(ColumnNames.Extension, value); } } public virtual string s_Notes { get { return this.IsColumnNull(ColumnNames.Notes) ? string.Empty : base.GetstringAsString(ColumnNames.Notes); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Notes); else this.Notes = base.SetstringAsString(ColumnNames.Notes, value); } } public virtual string s_ReportsTo { get { return this.IsColumnNull(ColumnNames.ReportsTo) ? string.Empty : base.GetintAsString(ColumnNames.ReportsTo); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ReportsTo); else this.ReportsTo = base.SetintAsString(ColumnNames.ReportsTo, value); } } #endregion #region Where Clause public class WhereClause { public WhereClause(BusinessEntity entity) { this._entity = entity; } public TearOffWhereParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffWhereParameter(this); } return _tearOff; } } #region TearOff's public class TearOffWhereParameter { public TearOffWhereParameter(WhereClause clause) { this._clause = clause; } public WhereParameter EmployeeID { get { WhereParameter where = new WhereParameter(ColumnNames.EmployeeID, Parameters.EmployeeID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter LastName { get { WhereParameter where = new WhereParameter(ColumnNames.LastName, Parameters.LastName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter FirstName { get { WhereParameter where = new WhereParameter(ColumnNames.FirstName, Parameters.FirstName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Title { get { WhereParameter where = new WhereParameter(ColumnNames.Title, Parameters.Title); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter TitleOfCourtesy { get { WhereParameter where = new WhereParameter(ColumnNames.TitleOfCourtesy, Parameters.TitleOfCourtesy); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter BirthDate { get { WhereParameter where = new WhereParameter(ColumnNames.BirthDate, Parameters.BirthDate); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter HireDate { get { WhereParameter where = new WhereParameter(ColumnNames.HireDate, Parameters.HireDate); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Address { get { WhereParameter where = new WhereParameter(ColumnNames.Address, Parameters.Address); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter City { get { WhereParameter where = new WhereParameter(ColumnNames.City, Parameters.City); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Region { get { WhereParameter where = new WhereParameter(ColumnNames.Region, Parameters.Region); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter PostalCode { get { WhereParameter where = new WhereParameter(ColumnNames.PostalCode, Parameters.PostalCode); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Country { get { WhereParameter where = new WhereParameter(ColumnNames.Country, Parameters.Country); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter HomePhone { get { WhereParameter where = new WhereParameter(ColumnNames.HomePhone, Parameters.HomePhone); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Extension { get { WhereParameter where = new WhereParameter(ColumnNames.Extension, Parameters.Extension); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Photo { get { WhereParameter where = new WhereParameter(ColumnNames.Photo, Parameters.Photo); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Notes { get { WhereParameter where = new WhereParameter(ColumnNames.Notes, Parameters.Notes); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ReportsTo { get { WhereParameter where = new WhereParameter(ColumnNames.ReportsTo, Parameters.ReportsTo); this._clause._entity.Query.AddWhereParameter(where); return where; } } private WhereClause _clause; } #endregion public WhereParameter EmployeeID { get { if(_EmployeeID_W == null) { _EmployeeID_W = TearOff.EmployeeID; } return _EmployeeID_W; } } public WhereParameter LastName { get { if(_LastName_W == null) { _LastName_W = TearOff.LastName; } return _LastName_W; } } public WhereParameter FirstName { get { if(_FirstName_W == null) { _FirstName_W = TearOff.FirstName; } return _FirstName_W; } } public WhereParameter Title { get { if(_Title_W == null) { _Title_W = TearOff.Title; } return _Title_W; } } public WhereParameter TitleOfCourtesy { get { if(_TitleOfCourtesy_W == null) { _TitleOfCourtesy_W = TearOff.TitleOfCourtesy; } return _TitleOfCourtesy_W; } } public WhereParameter BirthDate { get { if(_BirthDate_W == null) { _BirthDate_W = TearOff.BirthDate; } return _BirthDate_W; } } public WhereParameter HireDate { get { if(_HireDate_W == null) { _HireDate_W = TearOff.HireDate; } return _HireDate_W; } } public WhereParameter Address { get { if(_Address_W == null) { _Address_W = TearOff.Address; } return _Address_W; } } public WhereParameter City { get { if(_City_W == null) { _City_W = TearOff.City; } return _City_W; } } public WhereParameter Region { get { if(_Region_W == null) { _Region_W = TearOff.Region; } return _Region_W; } } public WhereParameter PostalCode { get { if(_PostalCode_W == null) { _PostalCode_W = TearOff.PostalCode; } return _PostalCode_W; } } public WhereParameter Country { get { if(_Country_W == null) { _Country_W = TearOff.Country; } return _Country_W; } } public WhereParameter HomePhone { get { if(_HomePhone_W == null) { _HomePhone_W = TearOff.HomePhone; } return _HomePhone_W; } } public WhereParameter Extension { get { if(_Extension_W == null) { _Extension_W = TearOff.Extension; } return _Extension_W; } } public WhereParameter Photo { get { if(_Photo_W == null) { _Photo_W = TearOff.Photo; } return _Photo_W; } } public WhereParameter Notes { get { if(_Notes_W == null) { _Notes_W = TearOff.Notes; } return _Notes_W; } } public WhereParameter ReportsTo { get { if(_ReportsTo_W == null) { _ReportsTo_W = TearOff.ReportsTo; } return _ReportsTo_W; } } private WhereParameter _EmployeeID_W = null; private WhereParameter _LastName_W = null; private WhereParameter _FirstName_W = null; private WhereParameter _Title_W = null; private WhereParameter _TitleOfCourtesy_W = null; private WhereParameter _BirthDate_W = null; private WhereParameter _HireDate_W = null; private WhereParameter _Address_W = null; private WhereParameter _City_W = null; private WhereParameter _Region_W = null; private WhereParameter _PostalCode_W = null; private WhereParameter _Country_W = null; private WhereParameter _HomePhone_W = null; private WhereParameter _Extension_W = null; private WhereParameter _Photo_W = null; private WhereParameter _Notes_W = null; private WhereParameter _ReportsTo_W = null; public void WhereClauseReset() { _EmployeeID_W = null; _LastName_W = null; _FirstName_W = null; _Title_W = null; _TitleOfCourtesy_W = null; _BirthDate_W = null; _HireDate_W = null; _Address_W = null; _City_W = null; _Region_W = null; _PostalCode_W = null; _Country_W = null; _HomePhone_W = null; _Extension_W = null; _Photo_W = null; _Notes_W = null; _ReportsTo_W = null; this._entity.Query.FlushWhereParameters(); } private BusinessEntity _entity; private TearOffWhereParameter _tearOff; } public WhereClause Where { get { if(_whereClause == null) { _whereClause = new WhereClause(this); } return _whereClause; } } private WhereClause _whereClause = null; #endregion protected override IDbCommand GetInsertCommand() { OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_EmployeesInsert]"; CreateParameters(cmd); return cmd; } protected override IDbCommand GetUpdateCommand() { OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_EmployeesUpdate]"; CreateParameters(cmd); return cmd; } protected override IDbCommand GetDeleteCommand() { OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_EmployeesDelete]"; OleDbParameter p; p = cmd.Parameters.Add(Parameters.EmployeeID); p.SourceColumn = ColumnNames.EmployeeID; p.SourceVersion = DataRowVersion.Current; return cmd; } private IDbCommand CreateParameters(OleDbCommand cmd) { OleDbParameter p; p = cmd.Parameters.Add(Parameters.EmployeeID); p.SourceColumn = ColumnNames.EmployeeID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.LastName); p.SourceColumn = ColumnNames.LastName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.FirstName); p.SourceColumn = ColumnNames.FirstName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Title); p.SourceColumn = ColumnNames.Title; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.TitleOfCourtesy); p.SourceColumn = ColumnNames.TitleOfCourtesy; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.BirthDate); p.SourceColumn = ColumnNames.BirthDate; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.HireDate); p.SourceColumn = ColumnNames.HireDate; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Address); p.SourceColumn = ColumnNames.Address; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.City); p.SourceColumn = ColumnNames.City; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Region); p.SourceColumn = ColumnNames.Region; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.PostalCode); p.SourceColumn = ColumnNames.PostalCode; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Country); p.SourceColumn = ColumnNames.Country; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.HomePhone); p.SourceColumn = ColumnNames.HomePhone; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Extension); p.SourceColumn = ColumnNames.Extension; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Photo); p.SourceColumn = ColumnNames.Photo; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Notes); p.SourceColumn = ColumnNames.Notes; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ReportsTo); p.SourceColumn = ColumnNames.ReportsTo; p.SourceVersion = DataRowVersion.Current; return cmd; } } }
// // MyThreadPoolManager.cs // using System ; using System.IO ; using System.Data; using System.Text ; using System.Xml ; using System.Xml.Xsl ; using System.Xml.XPath ; using System.Xml.Schema ; using System.Collections ; using System.Collections.Generic ; using System.Reflection ; using ST=System.Threading ; namespace alby.core.threadpool { public class MyThreadPoolManager : IDisposable { // // state // protected object _lock = new object() ; protected object _lockShutdownFlag = new object() ; protected int _defaultThreadPoolSize = 30 ; protected int _threadPoolSize = 0 ; protected int _threadPoolQueueMaxSize = 100 ; protected bool _shutdown = false ; // sync protected List<MyThreadPoolThread> _threads = new List<MyThreadPoolThread>() ; protected List<MyThreadPoolItemBase> _tpiQueue = new List<MyThreadPoolItemBase>() ; // sync // // // public MyThreadPoolManager() { this.Init( _defaultThreadPoolSize, _threadPoolQueueMaxSize ) ; } // // // public MyThreadPoolManager( int threadPoolSize, int threadPoolQueueMaxSize ) { this.Init( threadPoolSize, threadPoolQueueMaxSize ) ; } // // // protected void Init( int threadPoolSize, int threadPoolQueueMaxSize ) { _threadPoolSize = threadPoolSize ; _threadPoolQueueMaxSize = threadPoolQueueMaxSize ; for ( int i = 1 ; i <= _threadPoolSize ; i++ ) // create the threads { _threads.Add( new MyThreadPoolThread( this ) ) ; } } // // // public int ThreadPoolSize { get { return _threadPoolSize ; } } // // // public int ThreadPoolQueueMaxSize { get { return _threadPoolQueueMaxSize ; } } // // called from WORKER threads // public bool IsShutdown { get { lock( _lockShutdownFlag ) { return _shutdown ; } } } // // called from main thread // public void Shutdown() { lock( _lock ) { lock( _lockShutdownFlag ) { _shutdown = true ; } } } // // called from main thread // public void Queue( MyThreadPoolItemBase tpi ) { if ( this.IsShutdown ) { Helper.MtWriteLine( "Thread pool is shutting down. Can't queue new item [{0}] that will never be run, dude.", tpi.ID ) ; return ; } if ( tpi.IsStarted ) throw new Exception( "ThreadPoolItem #" + tpi.ID + " has already been started. Create a new one." ) ; this.ThrottleThreadPool() ; // wait for thread count to be less than maximum unstarted + running queue length tpi.IsFinished = false ; tpi.ThreadPoolManager = this ; lock( _lock ) { _tpiQueue.Add( tpi ) ; } } // // called from WORKER threads // // get next unstarted tpi from _tpiQueue -sync // public MyThreadPoolItemBase NextThreadPoolItem() { int queueLength = 0 ; int unstartedItems = 0 ; int finishedItems = 0 ; int runningItems = 0 ; this.ThreadPoolStats( out queueLength, out unstartedItems, out finishedItems, out runningItems ) ; // this is probably a good time to reduce the array size if ( finishedItems > 100 ) this.CleanupFinishedThreadPoolItems() ; lock( _lock ) { foreach ( MyThreadPoolItemBase tpi in _tpiQueue ) { if ( ! tpi.IsStarted ) { //Helper.WriteLine( "ThreadPoolManager - NextThreadPoolItem to run is [{0}]", tpi.ID ) ; tpi.IsStarted = true ; return tpi ; } } return null ; // no waiting thread items } } // // called from main thread // wait here until queue length is sane // wait 'till unstarted + running <= max queue length // public void ThrottleThreadPool() { int queueLength = 0 ; int unstartedItems = 0 ; int finishedItems = 0 ; int runningItems = 0 ; while ( true ) { this.ThreadPoolStats( out queueLength, out unstartedItems, out finishedItems, out runningItems ) ; if ( unstartedItems + runningItems <= _threadPoolQueueMaxSize ) return ; ST.Thread.Sleep( 500 ) ; // let busy cpu do stuff for a while } } // // called from main thread // other threads will use _threadQueue // public void ThreadPoolStats( out int queueLength, out int unstartedItems, out int finishedItems, out int runningItems ) { queueLength = 0 ; unstartedItems = 0 ; finishedItems = 0 ; runningItems = 0 ; lock( _lock ) { queueLength = _tpiQueue.Count ; foreach ( MyThreadPoolItemBase tpi in _tpiQueue ) { if ( tpi == null ) {} else if ( ! tpi.IsStarted ) unstartedItems ++ ; else if ( tpi.IsFinished ) finishedItems ++ ; else runningItems ++ ; } } //Helper.WriteLine( "ThreadPoolStats - threads [{0}] || items running [{1}], unstarted [{2}], finished [{3}], total [{4}]", // _threads.Count, runningItems, unstartedItems, finishedItems, queueLength ) ; } // // called from main thread // wait until all thread items finished // if they havet started yet , then they are considered already finished // public void WaitUntilAllFinished() { //Helper.WriteLine( "ThreadPoolManager - start - WaitUntilAllFinished" ) ; lock( _lock ) { foreach ( MyThreadPoolItemBase tpi in _tpiQueue ) if ( tpi != null ) tpi.WaitUntilFinished() ; } //Helper.WriteLine( "ThreadPoolManager - end - WaitUntilAllFinished" ) ; } // // callled from main thread // public void WaitUntilAllStarted() { int queueLength = 0 ; int unstartedItems = 0 ; int finishedItems = 0 ; int runningItems = 0 ; while ( true ) { if ( this.IsShutdown ) return ; // no point waiting ; this.ThreadPoolStats( out queueLength, out unstartedItems, out finishedItems, out runningItems ) ; if ( unstartedItems == 0 ) return ; //Helper.WriteLine( "ThrottleThreadPool - running [{0}], unstarted [{1}], finished [{2}], total [{3}]", // runningItems, unstartedItems, finishedItems, queueLength ) ; ST.Thread.Sleep( 500 ) ; // let busy cpu do stuff for a while } } // // called from main thread // public void Dispose() { //Helper.WriteLine( "ThreadPoolManager - start - dispose" ) ; this.Shutdown() ; this.WaitUntilAllFinished() ; lock( _lock ) { _tpiQueue.Clear() ; } //ALBY // really wait for worker threads to finish foreach( MyThreadPoolThread tpt in _threads ) tpt.Join() ; //Helper.WriteLine( "ThreadPoolManager - end - dispose" ) ; } // // // public override string ToString() { return base.ToString() ; } // // called from main thread // this is called by the user as required // other threads will look at _threadQueue // public void CleanupFinishedThreadPoolItems() { //Helper.WriteLine( "#### CleanupFinishedThreadPoolItems ####" ) ; lock( _lock ) { List<MyThreadPoolItemBase> liveTpiQueue = new List<MyThreadPoolItemBase>() ; foreach ( MyThreadPoolItemBase tpi in _tpiQueue ) if ( ! tpi.IsFinished ) liveTpiQueue.Add( tpi ) ; _tpiQueue = liveTpiQueue ; } } } // end class } // end namespace
using CppSharp.AST; using CppSharp.Generators; using CppSharp.Parser; using CppSharp.Passes; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using CppAbi = CppSharp.Parser.AST.CppAbi; namespace CppSharp { class Generator : ILibrary { private Options options = null; private string triple = ""; private CppAbi abi = CppAbi.Microsoft; public Generator(Options options) { if (options == null) throw new ArgumentNullException(nameof(options)); this.options = options; } static TargetPlatform GetCurrentPlatform() { if (Platform.IsWindows) return TargetPlatform.Windows; if (Platform.IsMacOS) return TargetPlatform.MacOS; if (Platform.IsLinux) return TargetPlatform.Linux; throw new System.NotImplementedException("Unknown host platform"); } void SetupTargetTriple() { var tripleBuilder = new StringBuilder(); if (options.Architecture == TargetArchitecture.x64) tripleBuilder.Append("x86_64-"); else if(options.Architecture == TargetArchitecture.x86) tripleBuilder.Append("i686-"); if (options.Platform == TargetPlatform.Windows) { tripleBuilder.Append("pc-win32-msvc"); abi = CppAbi.Microsoft; } else if (options.Platform == TargetPlatform.MacOS) { tripleBuilder.Append("apple-darwin12.4.0"); abi = CppAbi.Itanium; } else if (options.Platform == TargetPlatform.Linux) { tripleBuilder.Append("linux-gnu"); abi = CppAbi.Itanium; if(options.Cpp11ABI) tripleBuilder.Append("-cxx11abi"); } triple = tripleBuilder.ToString(); } public bool ValidateOptions(List<string> messages) { if (!options.Platform.HasValue) options.Platform = GetCurrentPlatform(); if (Platform.IsWindows && options.Platform != TargetPlatform.Windows) { messages.Add("Cannot create bindings for a platform other that Windows from a Windows host."); return false; } else if (Platform.IsMacOS && options.Platform != TargetPlatform.MacOS) { messages.Add("Cannot create bindings for a platform other that macOS from a macOS host."); return false; } else if (Platform.IsLinux && options.Platform != TargetPlatform.Linux) { messages.Add("Cannot create bindings for a platform other that Linux from a Linux host."); return false; } if (options.Platform != TargetPlatform.Windows && options.Kind != GeneratorKind.CSharp) { messages.Add("Cannot create bindings for languages other than C# from a non-Windows host."); return false; } if (options.Platform == TargetPlatform.Linux && options.Architecture != TargetArchitecture.x64) { messages.Add("Cannot create bindings for architectures other than x64 for Linux targets."); return false; } if (options.HeaderFiles.Count == 0) { messages.Add("No source header file has been given to generate bindings from."); return false; } if (string.IsNullOrEmpty(options.OutputNamespace)) { messages.Add("Output namespace not specified (see --outputnamespace option)."); return false; } if (string.IsNullOrEmpty(options.OutputFileName)) { messages.Add("Output directory not specified (see --output option)."); return false; } if (string.IsNullOrEmpty(options.InputLibraryName) && !options.CheckSymbols) { messages.Add("Input library name not specified and check symbols option not enabled.\nEither set the input library name (see or the check symbols flag."); return false; } if (string.IsNullOrEmpty(options.InputLibraryName) && options.CheckSymbols && options.Libraries.Count == 0) { messages.Add("Input library name not specified and check symbols is enabled but no libraries were given.\nEither set the input library name or add at least one library."); return false; } SetupTargetTriple(); return true; } public void Setup(Driver driver) { var parserOptions = driver.ParserOptions; parserOptions.TargetTriple = triple; parserOptions.Abi = abi; parserOptions.Verbose = options.Verbose; var driverOptions = driver.Options; driverOptions.GeneratorKind = options.Kind; var module = driverOptions.AddModule(options.OutputFileName); if(!string.IsNullOrEmpty(options.InputLibraryName)) module.SharedLibraryName = options.InputLibraryName; module.Headers.AddRange(options.HeaderFiles); module.Libraries.AddRange(options.Libraries); module.OutputNamespace = options.OutputNamespace; if (abi == CppAbi.Microsoft) parserOptions.MicrosoftMode = true; if (triple.Contains("apple")) SetupMacOptions(parserOptions); if (triple.Contains("linux")) SetupLinuxOptions(parserOptions); foreach (string s in options.Arguments) parserOptions.AddArguments(s); foreach (string s in options.IncludeDirs) parserOptions.AddIncludeDirs(s); foreach (string s in options.LibraryDirs) parserOptions.AddLibraryDirs(s); foreach (KeyValuePair<string, string> d in options.Defines) { if(string.IsNullOrEmpty(d.Value)) parserOptions.AddDefines(d.Key); else parserOptions.AddDefines(d.Key + "=" + d.Value); } driverOptions.GenerateDebugOutput = options.Debug; driverOptions.CompileCode = options.Compile; driverOptions.OutputDir = options.OutputDir; driverOptions.CheckSymbols = options.CheckSymbols; parserOptions.UnityBuild = options.UnityBuild; driverOptions.Verbose = options.Verbose; } private void SetupLinuxOptions(ParserOptions parserOptions) { parserOptions.SetupLinux(); parserOptions.AddDefines("_GLIBCXX_USE_CXX11_ABI=" + (options.Cpp11ABI ? "1" : "0")); } private static void SetupMacOptions(ParserOptions options) { options.MicrosoftMode = false; options.NoBuiltinIncludes = true; if (Platform.IsMacOS) { var headersPaths = new List<string> { "/usr/include" }; foreach (var header in headersPaths) options.AddSystemIncludeDirs(header); } options.AddArguments("-stdlib=libc++"); } public void SetupPasses(Driver driver) { driver.Context.TranslationUnitPasses.AddPass(new FunctionToInstanceMethodPass()); driver.Context.TranslationUnitPasses.AddPass(new MarshalPrimitivePointersAsRefTypePass()); } public void Preprocess(Driver driver, ASTContext ctx) { } public void Postprocess(Driver driver, ASTContext ctx) { } public void Run() { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.Append("Generating "); switch(options.Kind) { case GeneratorKind.CLI: messageBuilder.Append("C++/CLI"); break; case GeneratorKind.CSharp: messageBuilder.Append("C#"); break; } messageBuilder.Append(" bindings for "); switch (options.Platform) { case TargetPlatform.Linux: messageBuilder.Append("Linux"); break; case TargetPlatform.MacOS: messageBuilder.Append("OSX"); break; case TargetPlatform.Windows: messageBuilder.Append("Windows"); break; } messageBuilder.Append(" "); switch (options.Architecture) { case TargetArchitecture.x86: messageBuilder.Append("x86"); break; case TargetArchitecture.x64: messageBuilder.Append("x64"); break; } if(options.Cpp11ABI) messageBuilder.Append(" (GCC C++11 ABI)"); messageBuilder.Append("..."); Console.WriteLine(messageBuilder.ToString()); ConsoleDriver.Run(this); Console.WriteLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Ploeh.AutoFixture.Kernel { /// <summary> /// Selects public static methods that has the same parameters of another method, /// ignoring optional parameters and return type. /// </summary> /// <remarks> /// <para> /// The main target of this <see cref="IMethodQuery" /> implementation is to be able to /// late bind to a method even if it has optional parameters added to it. /// </para> /// <para> /// The order of the methods are based on the match of parameters types of both methods, /// favoring the method with exactly same parameters to be returned first. /// </para> /// </remarks> public class TemplateMethodQuery : IMethodQuery { /// <summary> /// Initializes a new instance of the <see cref="TemplateMethodQuery"/> class. /// </summary> /// <param name="template">The method info to compare.</param> public TemplateMethodQuery(MethodInfo template) { if (template == null) throw new ArgumentNullException(nameof(template)); this.Template = template; } /// <summary> /// Initializes a new instance of the <see cref="TemplateMethodQuery"/> class. /// </summary> /// <param name="template">The method info to compare.</param> /// <param name="owner">The owner.</param> public TemplateMethodQuery(MethodInfo template, object owner) { if (template == null) throw new ArgumentNullException(nameof(template)); if (owner == null) throw new ArgumentNullException(nameof(owner)); this.Owner = owner; this.Template = template; } /// <summary> /// The template <see cref="MethodInfo" /> to compare. /// </summary> public MethodInfo Template { get; } /// <summary> /// The owner instance of the <see cref="MethodInfo" />. /// </summary> public object Owner { get; } /// <summary> /// Selects the methods for the supplied type similar to <see cref="Template" />. /// </summary> /// <param name="type">The type.</param> /// <returns> /// All public static methods for <paramref name="type"/>, ordered by the most similar first. /// </returns> /// <remarks> /// <para> /// The ordering of the returned methods is based on a score that matches the parameters types /// of the method with the <see cref="Template" /> method parameters. Methods with the highest score /// are returned before. /// </para> /// <para> /// The score is calculated with the following rules: The methods earns 100 points for each exact /// match parameter type, it loses 50 points for each hierarchy level down of non-matching parameter /// type and it loses 1 point for each optional parameter. It also sums the score for the generic type /// arguments or element type with a 10% weight and will decrease 50 points for the difference between /// the length of the type arguments array. It also gives 5 points if the type is a class instead of /// an interface. /// </para> /// <para> /// In case of two methods with an equal score, the ordering is unspecified. /// </para> /// </remarks> public IEnumerable<IMethod> SelectMethods(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); return from method in type.GetMethods() where method.Name == Template.Name && (Owner != null || method.IsStatic) let methodParameters = method.GetParameters() let templateParameters = Template.GetParameters() where methodParameters.Length >= templateParameters.Length let score = new LateBindingParameterScore(methodParameters, templateParameters) orderby score descending where methodParameters.All(p => p.Position >= templateParameters.Length ? p.IsOptional || p.IsDefined(typeof(ParamArrayAttribute), true) : Compare(p.ParameterType, templateParameters[p.Position].ParameterType)) select new GenericMethod(method, GetMethodFactory(method)); } private IMethodFactory GetMethodFactory(MethodInfo method) { if (method.IsStatic) return new MissingParametersSupplyingStaticMethodFactory(); return new MissingParametersSupplyingMethodFactory(Owner); } private bool Compare(Type parameterType, Type templateParameterType) { if (parameterType.IsAssignableFrom(templateParameterType)) return true; if (parameterType.IsGenericParameter) return templateParameterType.IsGenericParameter && parameterType.GenericParameterPosition == templateParameterType.GenericParameterPosition; var genericArguments = GetTypeArguments(parameterType); var templateGenericArguments = GetTypeArguments(templateParameterType); if (genericArguments.Length == 0 || genericArguments.Length != templateGenericArguments.Length) return false; return genericArguments.Zip(templateGenericArguments, Compare).All(x => x); } private static Type[] GetTypeArguments(Type type) { return type.HasElementType ? new[] { type.GetElementType() } : type.GetGenericArguments(); } private class LateBindingParameterScore : IComparable<LateBindingParameterScore> { private readonly int score; internal LateBindingParameterScore(IEnumerable<ParameterInfo> methodParameters, IEnumerable<ParameterInfo> templateParameters) { if (methodParameters == null) throw new ArgumentNullException(nameof(methodParameters)); if (templateParameters == null) throw new ArgumentNullException(nameof(templateParameters)); this.score = CalculateScore(methodParameters.Select(p => p.ParameterType), templateParameters.Select(p => p.ParameterType)); } public int CompareTo(LateBindingParameterScore other) { if (other == null) return 1; return this.score.CompareTo(other.score); } private static int CalculateScore(IEnumerable<Type> methodParameters, IEnumerable<Type> templateParameters) { var parametersScore = templateParameters.Zip(methodParameters, (s, m) => CalculateScore(m, s)) .Sum(); var additionalParameters = methodParameters.Count() - templateParameters.Count(); return parametersScore - additionalParameters; } private static int CalculateScore(Type methodParameterType, Type templateParameterType) { if (methodParameterType == templateParameterType) return 100; var hierarchy = GetHierarchy(templateParameterType).ToList(); var matches = methodParameterType.IsClass ? hierarchy.Count(t => t.IsAssignableFrom(methodParameterType)) : hierarchy.Count(t => t.GetInterfaces().Any(i => i.IsAssignableFrom(methodParameterType))); var score = 50 * -(hierarchy.Count - matches); var methodTypeArguments = GetTypeArguments(methodParameterType); var templateTypeArguments = GetTypeArguments(templateParameterType); score += CalculateScore(methodTypeArguments, templateTypeArguments) / 10; score += 50 * -Math.Abs(methodTypeArguments.Length - templateTypeArguments.Length); if (methodParameterType.IsClass) score += 5; return score; } private static IEnumerable<Type> GetHierarchy(Type type) { if (!type.IsClass) foreach (var interfaceType in type.GetInterfaces()) yield return interfaceType; while (type != null) { yield return type; type = type.BaseType; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // namespace System.Collections { using System; using System.Diagnostics.Contracts; // Useful base class for typed read/write collections where items derive from object [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class CollectionBase : IList { ArrayList list; protected CollectionBase() { list = new ArrayList(); } protected CollectionBase(int capacity) { list = new ArrayList(capacity); } protected ArrayList InnerList { get { if (list == null) list = new ArrayList(); return list; } } protected IList List { get { return (IList)this; } } [System.Runtime.InteropServices.ComVisible(false)] public int Capacity { get { return InnerList.Capacity; } set { InnerList.Capacity = value; } } public int Count { get { return list == null ? 0 : list.Count; } } public void Clear() { OnClear(); InnerList.Clear(); OnClearComplete(); } public void RemoveAt(int index) { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); Object temp = InnerList[index]; OnValidate(temp); OnRemove(index, temp); InnerList.RemoveAt(index); try { OnRemoveComplete(index, temp); } catch { InnerList.Insert(index, temp); throw; } } bool IList.IsReadOnly { get { return InnerList.IsReadOnly; } } bool IList.IsFixedSize { get { return InnerList.IsFixedSize; } } bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } } Object ICollection.SyncRoot { get { return InnerList.SyncRoot; } } void ICollection.CopyTo(Array array, int index) { InnerList.CopyTo(array, index); } Object IList.this[int index] { get { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); return InnerList[index]; } set { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); OnValidate(value); Object temp = InnerList[index]; OnSet(index, temp, value); InnerList[index] = value; try { OnSetComplete(index, temp, value); } catch { InnerList[index] = temp; throw; } } } bool IList.Contains(Object value) { return InnerList.Contains(value); } int IList.Add(Object value) { OnValidate(value); OnInsert(InnerList.Count, value); int index = InnerList.Add(value); try { OnInsertComplete(index, value); } catch { InnerList.RemoveAt(index); throw; } return index; } void IList.Remove(Object value) { OnValidate(value); int index = InnerList.IndexOf(value); if (index < 0) throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound")); OnRemove(index, value); InnerList.RemoveAt(index); try{ OnRemoveComplete(index, value); } catch { InnerList.Insert(index, value); throw; } } int IList.IndexOf(Object value) { return InnerList.IndexOf(value); } void IList.Insert(int index, Object value) { if (index < 0 || index > Count) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); OnValidate(value); OnInsert(index, value); InnerList.Insert(index, value); try { OnInsertComplete(index, value); } catch { InnerList.RemoveAt(index); throw; } } public IEnumerator GetEnumerator() { return InnerList.GetEnumerator(); } protected virtual void OnSet(int index, Object oldValue, Object newValue) { } protected virtual void OnInsert(int index, Object value) { } protected virtual void OnClear() { } protected virtual void OnRemove(int index, Object value) { } protected virtual void OnValidate(Object value) { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); } protected virtual void OnSetComplete(int index, Object oldValue, Object newValue) { } protected virtual void OnInsertComplete(int index, Object value) { } protected virtual void OnClearComplete() { } protected virtual void OnRemoveComplete(int index, Object value) { } } }
// // RssParser.cs // // Authors: // Mike Urbanski <michael.c.urbanski@gmail.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007 Mike Urbanski // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Xml; using System.Text; using System.Collections.Generic; using Hyena; namespace Migo.Syndication { public class RssParser { private XmlDocument doc; private XmlNamespaceManager mgr; private string url; public RssParser (string url, string xml) { this.url = url; xml = xml.TrimStart (); doc = new XmlDocument (); try { doc.LoadXml (xml); } catch (XmlException e) { bool have_stripped_control = false; StringBuilder sb = new StringBuilder (); foreach (char c in xml) { if (Char.IsControl (c) && c != '\n') { have_stripped_control = true; } else { sb.Append (c); } } bool loaded = false; if (have_stripped_control) { try { doc.LoadXml (sb.ToString ()); loaded = true; } catch (Exception) { } } if (!loaded) { Hyena.Log.Exception (e); throw new FormatException ("Invalid XML document."); } } CheckRss (); } public RssParser (string url, XmlDocument doc) { this.url = url; this.doc = doc; CheckRss (); } public Feed CreateFeed () { return UpdateFeed (new Feed ()); } public Feed UpdateFeed (Feed feed) { try { if (feed.Title == null || feed.Title.Trim () == "" || feed.Title == Mono.Unix.Catalog.GetString ("Unknown Podcast")) { feed.Title = StringUtil.RemoveNewlines (GetXmlNodeText (doc, "/rss/channel/title")); if (String.IsNullOrEmpty (feed.Title)) { feed.Title = Mono.Unix.Catalog.GetString ("Unknown Podcast"); } } feed.Description = StringUtil.RemoveNewlines (GetXmlNodeText (doc, "/rss/channel/description")); feed.Copyright = GetXmlNodeText (doc, "/rss/channel/copyright"); feed.ImageUrl = GetXmlNodeText (doc, "/rss/channel/itunes:image/@href"); if (String.IsNullOrEmpty (feed.ImageUrl)) { feed.ImageUrl = GetXmlNodeText (doc, "/rss/channel/image/url"); } feed.Language = GetXmlNodeText (doc, "/rss/channel/language"); feed.LastBuildDate = GetRfc822DateTime (doc, "/rss/channel/lastBuildDate"); feed.Link = GetXmlNodeText (doc, "/rss/channel/link"); feed.PubDate = GetRfc822DateTime (doc, "/rss/channel/pubDate"); feed.Keywords = GetXmlNodeText (doc, "/rss/channel/itunes:keywords"); feed.Category = GetXmlNodeText (doc, "/rss/channel/itunes:category/@text"); return feed; } catch (Exception e) { Hyena.Log.Exception ("Caught error parsing RSS channel", e); } return null; } public IEnumerable<FeedItem> GetFeedItems (Feed feed) { XmlNodeList nodes = null; try { nodes = doc.SelectNodes ("//item"); } catch (Exception e) { Hyena.Log.Exception ("Unable to get any RSS items", e); } if (nodes != null) { foreach (XmlNode node in nodes) { FeedItem item = null; try { item = ParseItem (node); if (item != null) { item.Feed = feed; } } catch (Exception e) { Hyena.Log.Exception (e); } if (item != null) { yield return item; } } } } private FeedItem ParseItem (XmlNode node) { try { FeedItem item = new FeedItem (); item.Description = StringUtil.RemoveNewlines (GetXmlNodeText (node, "description")); item.UpdateStrippedDescription (); item.Title = StringUtil.RemoveNewlines (GetXmlNodeText (node, "title")); if (String.IsNullOrEmpty (item.Description) && String.IsNullOrEmpty (item.Title)) { throw new FormatException ("node: Either 'title' or 'description' node must exist."); } item.Author = GetXmlNodeText (node, "author"); item.Comments = GetXmlNodeText (node, "comments"); // Removed, since we form our own Guid, since feeds don't seem to be consistent // about including this element. //item.Guid = GetXmlNodeText (node, "guid"); item.Link = GetXmlNodeText (node, "link"); item.PubDate = GetRfc822DateTime (node, "pubDate"); item.Modified = GetRfc822DateTime (node, "dcterms:modified"); item.LicenseUri = GetXmlNodeText (node, "creativeCommons:license"); // TODO prefer <media:content> nodes over <enclosure>? item.Enclosure = ParseEnclosure (node) ?? ParseMediaContent (node); return item; } catch (Exception e) { Hyena.Log.Exception ("Caught error parsing RSS item", e); } return null; } private FeedEnclosure ParseEnclosure (XmlNode node) { try { FeedEnclosure enclosure = new FeedEnclosure (); enclosure.Url = GetXmlNodeText (node, "enclosure/@url"); if (enclosure.Url == null) return null; enclosure.FileSize = Math.Max (0, GetInt64 (node, "enclosure/@length")); enclosure.MimeType = GetXmlNodeText (node, "enclosure/@type"); enclosure.Duration = GetITunesDuration (node); enclosure.Keywords = GetXmlNodeText (node, "itunes:keywords"); return enclosure; } catch (Exception e) { Hyena.Log.Exception (String.Format ("Caught error parsing RSS enclosure in {0}", url), e); } return null; } // Parse one Media RSS media:content node // http://search.yahoo.com/mrss/ private FeedEnclosure ParseMediaContent (XmlNode item_node) { try { XmlNode node = null; // Get the highest bitrate "full" content item // TODO allow a user-preference for a feed to decide what quality to get, if there // are options? int max_bitrate = 0; foreach (XmlNode test_node in item_node.SelectNodes ("media:content", mgr)) { string expr = GetXmlNodeText (test_node, "@expression"); if (!(String.IsNullOrEmpty (expr) || expr == "full")) continue; int bitrate = GetInt32 (test_node, "@bitrate"); if (node == null || bitrate > max_bitrate) { node = test_node; max_bitrate = bitrate; } } if (node == null) return null; FeedEnclosure enclosure = new FeedEnclosure (); enclosure.Url = GetXmlNodeText (node, "@url"); if (enclosure.Url == null) return null; enclosure.FileSize = Math.Max (0, GetInt64 (node, "@fileSize")); enclosure.MimeType = GetXmlNodeText (node, "@type"); enclosure.Duration = TimeSpan.FromSeconds (GetInt64 (node, "@duration")); enclosure.Keywords = GetXmlNodeText (item_node, "itunes:keywords"); // TODO get the thumbnail URL return enclosure; } catch (Exception e) { Hyena.Log.Exception ("Caught error parsing RSS media:content", e); } return null; } private void CheckRss () { if (doc.SelectSingleNode ("/rss") == null) { throw new FormatException ("Invalid RSS document."); } if (doc.SelectSingleNode ("/rss/channel/title") == null) { throw new FormatException ("Invalid RSS document. Node 'title' is required"); } mgr = new XmlNamespaceManager (doc.NameTable); mgr.AddNamespace ("itunes", "http://www.itunes.com/dtds/podcast-1.0.dtd"); mgr.AddNamespace ("creativeCommons", "http://backend.userland.com/creativeCommonsRssModule"); mgr.AddNamespace ("media", "http://search.yahoo.com/mrss/"); mgr.AddNamespace ("dcterms", "http://purl.org/dc/terms/"); } public TimeSpan GetITunesDuration (XmlNode node) { return GetITunesDuration (GetXmlNodeText (node, "itunes:duration")); } public static TimeSpan GetITunesDuration (string duration) { if (String.IsNullOrEmpty (duration)) { return TimeSpan.Zero; } try { int hours = 0, minutes = 0, seconds = 0; string [] parts = duration.Split (':'); if (parts.Length > 0) seconds = Int32.Parse (parts[parts.Length - 1]); if (parts.Length > 1) minutes = Int32.Parse (parts[parts.Length - 2]); if (parts.Length > 2) hours = Int32.Parse (parts[parts.Length - 3]); return TimeSpan.FromSeconds (hours * 3600 + minutes * 60 + seconds); } catch { return TimeSpan.Zero; } } #region Xml Convienience Methods public string GetXmlNodeText (XmlNode node, string tag) { XmlNode n = node.SelectSingleNode (tag, mgr); return (n == null) ? null : n.InnerText.Trim (); } public DateTime GetRfc822DateTime (XmlNode node, string tag) { DateTime ret = DateTime.MinValue; string result = GetXmlNodeText (node, tag); if (!String.IsNullOrEmpty (result)) { if (Rfc822DateTime.TryParse (result, out ret)) { return ret; } if (DateTime.TryParse (result, out ret)) { return ret; } } return ret; } public long GetInt64 (XmlNode node, string tag) { long ret = 0; string result = GetXmlNodeText (node, tag); if (!String.IsNullOrEmpty (result)) { Int64.TryParse (result, out ret); } return ret; } public int GetInt32 (XmlNode node, string tag) { int ret = 0; string result = GetXmlNodeText (node, tag); if (!String.IsNullOrEmpty (result)) { Int32.TryParse (result, out ret); } return ret; } #endregion } }
using System; using System.Collections.Generic; namespace IFC { public static class Functions { public static IfcSurface IfcAssociatedSurface(IfcPcurve arg) { throw new NotImplementedException(); } public static List<IfcDirection> IfcBaseAxis(int dim,IfcDirection axis1,IfcDirection axis2,IfcDirection axis3) { throw new NotImplementedException(); } public static T IfcBooleanChoose<T>(bool b,T choice1,T choice2) { throw new NotImplementedException(); } public static List<IfcDirection> IfcBuild2Axes(IfcDirection refDirection) { throw new NotImplementedException(); } public static List<IfcDirection> IfcBuildAxes(IfcDirection axis,IfcDirection refDirection) { throw new NotImplementedException(); } public static bool IfcConsecutiveSegments(List<IfcSegmentIndexSelect> segments) { throw new NotImplementedException(); } public static bool IfcConstraintsParamBSpline(int degree,int upKnots,int upCp,int knotMult,IfcParameterValue knots) { throw new NotImplementedException(); } public static IfcDirection IfcConvertDirectionInto2D(IfcDirection direction) { throw new NotImplementedException(); } public static bool? IfcCorrectDimensions(IfcUnitEnum m,IfcDimensionalExponents dim) { throw new NotImplementedException(); } public static bool? IfcCorrectFillAreaStyle(List<IfcFillStyleSelect> styles) { throw new NotImplementedException(); } public static bool? IfcCorrectLocalPlacement(IfcAxis2Placement axisPlacement,IfcObjectPlacement relPlacement) { throw new NotImplementedException(); } public static bool? IfcCorrectObjectAssignment(IfcObjectTypeEnum constraint,List<IfcObjectDefinition> objects) { throw new NotImplementedException(); } public static bool? IfcCorrectUnitAssignment(List<IfcUnit> units) { throw new NotImplementedException(); } public static IfcVector IfcCrossProduct(IfcDirection arg1,IfcDirection arg2) { throw new NotImplementedException(); } public static IfcDimensionCount IfcCurveDim(IfcCurve curve) { throw new NotImplementedException(); } public static bool IfcCurveWeightsPositive(IfcRationalBSplineCurveWithKnots b) { throw new NotImplementedException(); } public static IfcDimensionalExponents IfcDeriveDimensionalExponents(List<IfcDerivedUnitElement> unitElements) { throw new NotImplementedException(); } public static IfcDimensionalExponents IfcDimensionsForSiUnit(IfcSIUnitName n) { throw new NotImplementedException(); } public static double IfcDotProduct(IfcDirection arg1,IfcDirection arg2) { throw new NotImplementedException(); } public static IfcDirection IfcFirstProjAxis(IfcDirection zAxis,IfcDirection arg) { throw new NotImplementedException(); } public static List<IfcSurface> IfcGetBasisSurface(IfcCurveOnSurface c) { throw new NotImplementedException(); } public static T IfcListToArray<T>(List<T> lis,int low,int u) { throw new NotImplementedException(); } public static bool? IfcLoopHeadToTail(IfcEdgeLoop aLoop) { throw new NotImplementedException(); } public static List<List<T>> IfcMakeArrayOfArray<T>(List<List<T>> lis,int low1,int u1,int low2,int u2) { throw new NotImplementedException(); } public static IfcLengthMeasure IfcMlsTotalThickness(IfcMaterialLayerSet layerSet) { throw new NotImplementedException(); } public static IfcVectorOrDirection IfcNormalise(IfcVectorOrDirection arg) { throw new NotImplementedException(); } public static IfcDirection IfcOrthogonalComplement(IfcDirection vec) { throw new NotImplementedException(); } public static bool? IfcPathHeadToTail(IfcPath aPath) { throw new NotImplementedException(); } public static IfcDimensionCount IfcPointListDim(IfcCartesianPointList pointList) { throw new NotImplementedException(); } public static bool? IfcSameAxis2Placement(IfcAxis2Placement ap1,IfcAxis2Placement ap2,double epsilon) { throw new NotImplementedException(); } public static bool? IfcSameCartesianPoint(IfcCartesianPoint cp1,IfcCartesianPoint cp2,double epsilon) { throw new NotImplementedException(); } public static bool? IfcSameDirection(IfcDirection dir1,IfcDirection dir2,double epsilon) { throw new NotImplementedException(); } public static bool? IfcSameValidPrecision(double epsilon1,double epsilon2) { throw new NotImplementedException(); } public static bool? IfcSameValue(double value1,double value2,double epsilon) { throw new NotImplementedException(); } public static IfcVector IfcScalarTimesVector(double scalar,IfcVectorOrDirection vec) { throw new NotImplementedException(); } public static IfcDirection IfcSecondProjAxis(IfcDirection zAxis,IfcDirection xAxis,IfcDirection arg) { throw new NotImplementedException(); } public static bool? IfcShapeRepresentationTypes(IfcLabel repType,IfcRepresentationItem items) { throw new NotImplementedException(); } public static bool IfcSurfaceWeightsPositive(IfcRationalBSplineSurfaceWithKnots b) { throw new NotImplementedException(); } public static bool? IfcTaperedSweptAreaProfiles(IfcProfileDef startArea,IfcProfileDef endArea) { throw new NotImplementedException(); } public static bool? IfcTopologyRepresentationTypes(IfcLabel repType,IfcRepresentationItem items) { throw new NotImplementedException(); } public static bool? IfcUniqueDefinitionNames(List<IfcRelDefinesByProperties> relations) { throw new NotImplementedException(); } public static bool? IfcUniquePropertyName(List<IfcProperty> properties) { throw new NotImplementedException(); } public static bool? IfcUniquePropertySetNames(List<IfcPropertySetDefinition> properties) { throw new NotImplementedException(); } public static bool? IfcUniquePropertyTemplateNames(List<IfcPropertyTemplate> properties) { throw new NotImplementedException(); } public static bool? IfcUniqueQuantityNames(List<IfcPhysicalQuantity> properties) { throw new NotImplementedException(); } public static IfcVector IfcVectorDifference(IfcVectorOrDirection arg1,IfcVectorOrDirection arg2) { throw new NotImplementedException(); } public static IfcVector IfcVectorSum(IfcVectorOrDirection arg1,IfcVectorOrDirection arg2) { throw new NotImplementedException(); } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Data.SqlServerCe; using System.Text; using MLifter.DAL.Interfaces; using MLifter.DAL.Interfaces.DB; using MLifter.DAL.Tools; namespace MLifter.DAL.DB.MsSqlCe { class MsSqlCeCardMediaConnector : IDbCardMediaConnector { private static Dictionary<ConnectionStringStruct, MsSqlCeCardMediaConnector> instances = new Dictionary<ConnectionStringStruct, MsSqlCeCardMediaConnector>(); public static MsSqlCeCardMediaConnector GetInstance(ParentClass parentClass) { ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString; if (!instances.ContainsKey(connection)) instances.Add(connection, new MsSqlCeCardMediaConnector(parentClass)); return instances[connection]; } private ParentClass Parent; private MsSqlCeCardMediaConnector(ParentClass parentClass) { Parent = parentClass; Parent.DictionaryClosed += new EventHandler(Parent_DictionaryClosed); } void Parent_DictionaryClosed(object sender, EventArgs e) { IParent parent = sender as IParent; instances.Remove(parent.Parent.CurrentUser.ConnectionString); } #region IDbCardMediaConnector Members public MLifter.DAL.Interfaces.IMedia GetMedia(int id, int cardid) { IList<IMedia> mediaList = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)] as IList<IMedia>; if (mediaList != null) { GetCardMedia(cardid, Side.Answer, (WordType?)null); foreach (DbMedia media in Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)] as IList<IMedia>) if (media.Id == id) return media; } return null; } public void SetCardMedia(int id, int cardid, MLifter.DAL.Interfaces.Side side, MLifter.DAL.Interfaces.WordType type, bool isDefault, MLifter.DAL.Interfaces.EMedia mediatype) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { SqlCeTransaction tran = cmd.Connection.BeginTransaction(); ClearCardMedia(cardid, side, type, mediatype); cmd.CommandText = "INSERT INTO \"Cards_MediaContent\" (media_id, cards_id, side, type, is_default) " + "VALUES (@mediaid, @cardid, @side, @type, @isdefault);"; cmd.Parameters.Add("@mediaid", id); cmd.Parameters.Add("@cardid", cardid); cmd.Parameters.Add("@side", side.ToString()); cmd.Parameters.Add("@type", type.ToString()); cmd.Parameters.Add("@isdefault", isDefault); MSSQLCEConn.ExecuteNonQuery(cmd); tran.Commit(); } Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)); } public IList<int> GetCardMedia(int cardid, MLifter.DAL.Interfaces.Side side) { return GetCardMedia(cardid, side, null); } public IList<int> GetCardMedia(int cardid, MLifter.DAL.Interfaces.Side side, MLifter.DAL.Interfaces.WordType type) { return GetCardMedia(cardid, side, type); } public void ClearCardMedia(int cardid) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { cmd.CommandText = "DELETE FROM \"Cards_MediaContent\" WHERE cards_id=@cardid;"; cmd.Parameters.Add("@cardid", cardid); cmd.ExecuteNonQuery(); } Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)); } public void ClearCardMedia(int cardid, int id) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { cmd.CommandText = "DELETE FROM \"Cards_MediaContent\" WHERE media_id=@mediaid AND cards_id=@cardid;"; cmd.Parameters.Add("@cardid", cardid); cmd.Parameters.Add("@mediaid", id); cmd.ExecuteNonQuery(); } Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)); } public void ClearCardMedia(int cardid, Side side, WordType type, EMedia mediatype) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { cmd.CommandText = "DELETE FROM \"Cards_MediaContent\" WHERE cards_id=@cardid AND side=@side AND type=@type " + "AND media_id IN (SELECT id FROM \"MediaContent\" WHERE media_type=@mediatype);"; cmd.Parameters.Add("@cardid", cardid); cmd.Parameters.Add("@side", side.ToString()); cmd.Parameters.Add("@type", type.ToString()); cmd.Parameters.Add("@mediatype", mediatype.ToString()); cmd.ExecuteNonQuery(); } Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)); } public void CheckCardMediaId(int id, int cardid) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { cmd.CommandText = "SELECT count(*) FROM \"Cards_MediaContent\" WHERE media_id=@id AND cards_id=@cardid;"; cmd.Parameters.Add("@id", id); cmd.Parameters.Add("@cardid", cardid); if (Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)) < 1) throw new IdAccessException(id); } } public IList<int> GetMediaResources(int lmid) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { cmd.CommandText = "SELECT DISTINCT cc.media_id FROM \"Cards_MediaContent\" AS cc " + "JOIN \"LearningModules_Cards\" AS lc ON cc.cards_id = lc.cards_id WHERE lc.lm_id=@lmid;"; cmd.Parameters.Add("@lmid", lmid); SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); IList<int> ids = new List<int>(); while (reader.Read()) ids.Add(Convert.ToInt32(reader["media_id"])); reader.Close(); return ids; } } #endregion private IList<int> GetCardMedia(int cardid, Side side, WordType? type) { IList<int> ids = new List<int>(); IList<IMedia> mediaList = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardMedia, cardid)] as IList<IMedia>; if (mediaList != null) { foreach (DbMedia cms in mediaList) if (cms.Side == side && (!type.HasValue || cms.Type == type)) ids.Add(cms.Id); return ids; } using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser)) { cmd.CommandText = "SELECT id, media_type, side, type, is_default FROM \"Cards_MediaContent\" JOIN \"MediaContent\" ON media_id=id WHERE cards_id=@cardid;"; cmd.Parameters.Add("@cardid", cardid); SqlCeDataReader reader = MsSqlCe.MSSQLCEConn.ExecuteReader(cmd); mediaList = new List<IMedia>(); while (reader.Read()) { IMedia newMedia = null; int id = Convert.ToInt32(reader["id"]); EMedia mtype = (EMedia)Enum.Parse(typeof(EMedia), Convert.ToString(reader["media_type"])); Side cside = (Side)Enum.Parse(typeof(Side), Convert.ToString(reader["side"])); WordType wordtype = (WordType)Enum.Parse(typeof(WordType), Convert.ToString(reader["type"])); bool isDefault = Convert.ToBoolean(reader["is_default"]); switch (mtype) { case EMedia.Audio: newMedia = new DbAudio(id, cardid, false, cside, wordtype, isDefault, (wordtype == WordType.Sentence), Parent); break; case EMedia.Image: newMedia = new DbImage(id, cardid, false, cside, wordtype, isDefault, (wordtype == WordType.Sentence), Parent); break; case EMedia.Video: newMedia = new DbVideo(id, cardid, false, cside, wordtype, isDefault, (wordtype == WordType.Sentence), Parent); break; } mediaList.Add(newMedia); if ((newMedia as DbMedia).Side == side && (!type.HasValue || (newMedia as DbMedia).Type == type)) ids.Add((newMedia as DbMedia).Id); } reader.Close(); Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardMedia, cardid)] = mediaList; return ids; } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; // need this for the properties metadata using System.Xml; using System.Text.RegularExpressions; using fyiReporting.RDL; namespace fyiReporting.CRI { /// <summary> /// BarCodeBookland: create Bookland compatible BarCode images. /// See http://www.barcodeisland.com/bookland.phtml for description of how to /// construct a Bookland compatible barcode. In essence, Bookland is simply /// EAN-13 barcode with a number system of 978. /// </summary> public class BarCodeBookland: ICustomReportItem { string _ISBN; // ISBN number BarCodeEAN13 _Ean13; // the EAN-13 barcode object public BarCodeBookland() // Need to be able to create an instance { _Ean13 = new BarCodeEAN13(); } #region ICustomReportItem Members /// <summary> /// Runtime: Draw the BarCode /// </summary> /// <param name="bm">Bitmap to draw the barcode in.</param> public void DrawImage(System.Drawing.Bitmap bm) { _Ean13.DrawImage(bm); } /// <summary> /// Design time: Draw a hard coded BarCode for design time; Parameters can't be /// relied on since they aren't available. /// </summary> /// <param name="bm"></param> public void DrawDesignerImage(System.Drawing.Bitmap bm) { _Ean13.DrawImage(bm, "978015602732"); // Yann Martel-Life of Pi } /// <summary> /// BarCode isn't a DataRegion /// </summary> /// <returns></returns> public bool IsDataRegion() { return false; } /// <summary> /// Set the properties; No validation is done at this time. /// </summary> /// <param name="props"></param> public void SetProperties(IDictionary<string, object> props) { try { string p = props["ISBN"] as string; if (p == null) throw new Exception("ISBN property must be a string."); // remove any dashes p = p.Replace("-", ""); if (p.Length > 9) // get rid of the ISBN checksum digit p = p.Substring(0, 9); if (!Regex.IsMatch(p, "^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]$")) throw new Exception("ISBN must have at least nine digits."); _ISBN = p; // Now set the properties of the EAN-13 IDictionary<string, object> ean13_props = new Dictionary<string, object>(); ean13_props.Add("NumberSystem", "97"); ean13_props.Add("ManufacturerCode", "8" + _ISBN.Substring(0, 4)); ean13_props.Add("ProductCode", _ISBN.Substring(4,5)); _Ean13.SetProperties(ean13_props); } catch (KeyNotFoundException ) { throw new Exception("ISBN property must be specified"); } return; } /// <summary> /// Design time call: return string with <CustomReportItem> ... </CustomReportItem> syntax for /// the insert. The string contains a variable {0} which will be substituted with the /// configuration name. This allows the name to be completely controlled by /// the configuration file. /// </summary> /// <returns></returns> public string GetCustomReportItemXml() { return "<CustomReportItem><Type>{0}</Type>" + string.Format("<Height>{0}mm</Height><Width>{1}mm</Width>", BarCodeEAN13.OptimalHeight, BarCodeEAN13.OptimalWidth) + "<CustomProperties>" + "<CustomProperty>" + "<Name>ISBN</Name>" + "<Value>0-15-602732-1</Value>" + // Yann Martel- Life of Pi "</CustomProperty>" + "</CustomProperties>" + "</CustomReportItem>"; } /// <summary> /// Return an instance of the class representing the properties. /// This method is called at design time; /// </summary> /// <returns></returns> public object GetPropertiesInstance(XmlNode iNode) { BarCodeBooklandProperties bcp = new BarCodeBooklandProperties(this, iNode); foreach (XmlNode n in iNode.ChildNodes) { if (n.Name != "CustomProperty") continue; string pname = this.GetNamedElementValue(n, "Name", ""); switch (pname) { case "ISBN": bcp.SetISBN(GetNamedElementValue(n, "Value", "0-15-602732-1")); break; default: break; } } return bcp; } /// <summary> /// Set the custom properties given the properties object /// </summary> /// <param name="node"></param> /// <param name="inst"></param> public void SetPropertiesInstance(XmlNode node, object inst) { node.RemoveAll(); // Get rid of all properties BarCodeBooklandProperties bcp = inst as BarCodeBooklandProperties; if (bcp == null) return; // ISBN CreateChild(node, "ISBN", bcp.ISBN); } void CreateChild(XmlNode node, string nm, string val) { XmlDocument xd = node.OwnerDocument; XmlNode cp = xd.CreateElement("CustomProperty"); node.AppendChild(cp); XmlNode name = xd.CreateElement("Name"); name.InnerText = nm; cp.AppendChild(name); XmlNode v = xd.CreateElement("Value"); v.InnerText = val; cp.AppendChild(v); } public void Dispose() { _Ean13.Dispose(); return; } #endregion /// <summary> /// Get the child element with the specified name. Return the InnerText /// value if found otherwise return the passed default. /// </summary> /// <param name="xNode">Parent node</param> /// <param name="name">Name of child node to look for</param> /// <param name="def">Default value to use if not found</param> /// <returns>Value the named child node</returns> string GetNamedElementValue(XmlNode xNode, string name, string def) { if (xNode == null) return def; foreach (XmlNode cNode in xNode.ChildNodes) { if (cNode.NodeType == XmlNodeType.Element && cNode.Name == name) return cNode.InnerText; } return def; } /// <summary> /// BarCodeProperties- All properties are type string to allow for definition of /// a runtime expression. /// </summary> public class BarCodeBooklandProperties { BarCodeBookland _bcbl; XmlNode _node; string _ISBN; internal BarCodeBooklandProperties(BarCodeBookland bcbl, XmlNode node) { _bcbl = bcbl; _node = node; } internal void SetISBN(string isbn) { _ISBN = isbn; } [CategoryAttribute("BarCode"), DescriptionAttribute("ISBN is the book's ISBN number.")] public string ISBN { get { return _ISBN; } set { _ISBN = value; _bcbl.SetPropertiesInstance(_node, this); } } } } }
using System; using System.Collections.Generic; using System.Linq; using Ammy.VisualStudio.Service.Taggers; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; namespace Ammy.VisualStudio.Service.Infrastructure { public class BraceMatching : INeedLogging { private readonly Dictionary<char, char> _braceList; private readonly ITextBuffer _buffer; private readonly TextMarkerTagger _tagger; private readonly ITextView _textView; private SnapshotPoint? _currentChar; public BraceMatching(TextMarkerTagger tagger, ITextBuffer buffer, ITextView textView) { _tagger = tagger; _buffer = buffer; _textView = textView; _braceList = new Dictionary<char, char> { { '{', '}' }, { '[', ']' }, { '(', ')' } }; _currentChar = null; _textView.Caret.PositionChanged += CaretPositionChanged; _textView.LayoutChanged += ViewLayoutChanged; } private void ViewLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { if (e.NewSnapshot != e.OldSnapshot) UpdateAtCaretPosition(_textView.Caret.Position); } private void CaretPositionChanged(object sender, CaretPositionChangedEventArgs e) { UpdateAtCaretPosition(e.NewPosition); } private void UpdateAtCaretPosition(CaretPosition position) { _currentChar = position.Point.GetPoint(_buffer, position.Affinity); if (!_currentChar.HasValue) return; var snapshot = _buffer.CurrentSnapshot; _tagger.RaiseTagsChanged(new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length))); } public IEnumerable<ITagSpan<TextMarkerTag>> GetTags(NormalizedSnapshotSpanCollection spans) { var result = new List<ITagSpan<TextMarkerTag>>(); try { if (spans.Count == 0) //there is no content in the buffer return result; //don't do anything if the current SnapshotPoint is not initialized or at the end of the buffer if (!_currentChar.HasValue || _currentChar.Value.Position >= _currentChar.Value.Snapshot.Length) return result; //hold on to a snapshot of the current character var currentChar = _currentChar.Value; //if the requested snapshot isn't the same as the one the brace is on, translate our spans to the expected snapshot if (spans[0].Snapshot != currentChar.Snapshot) currentChar = currentChar.TranslateTo(spans[0].Snapshot, PointTrackingMode.Positive); //get the current char and the previous char var currentText = currentChar.GetChar(); var lastChar = currentChar == 0 ? currentChar : currentChar - 1; //if currentChar is 0 (beginning of buffer), don't move it back var lastText = lastChar.GetChar(); var pairSpan = new SnapshotSpan(); if (_braceList.ContainsKey(currentText)) //the key is the open brace { char closeChar; _braceList.TryGetValue(currentText, out closeChar); if (FindMatchingCloseChar(currentChar, currentText, closeChar, _textView.TextViewLines.Count, out pairSpan)) { result.Add(new TagSpan<TextMarkerTag>(new SnapshotSpan(currentChar, 1), new TextMarkerTag("blue"))); result.Add(new TagSpan<TextMarkerTag>(pairSpan, new TextMarkerTag("blue"))); } } else if (_braceList.ContainsValue(lastText)) //the value is the close brace, which is the *previous* character { var open = from n in _braceList where n.Value.Equals(lastText) select n.Key; if (FindMatchingOpenChar(lastChar, open.ElementAt(0), lastText, _textView.TextViewLines.Count, out pairSpan)) { result.Add(new TagSpan<TextMarkerTag>(new SnapshotSpan(lastChar, 1), new TextMarkerTag("blue"))); result.Add(new TagSpan<TextMarkerTag>(pairSpan, new TextMarkerTag("blue"))); } } return result; } catch (Exception e) { this.LogDebugInfo("BraceMatching GetTags failed: " + e); return result; } } private static bool FindMatchingCloseChar(SnapshotPoint startPoint, char open, char close, int maxLines, out SnapshotSpan pairSpan) { pairSpan = new SnapshotSpan(startPoint.Snapshot, 1, 1); var line = startPoint.GetContainingLine(); var lineText = line.GetText(); var lineNumber = line.LineNumber; var offset = startPoint.Position - line.Start.Position + 1; var stopLineNumber = startPoint.Snapshot.LineCount - 1; if (maxLines > 0) stopLineNumber = Math.Min(stopLineNumber, lineNumber + maxLines); var openCount = 0; while (true) { //walk the entire line while (offset < line.Length) { var currentChar = lineText[offset]; if (currentChar == close) //found the close character { if (openCount > 0) { openCount--; } else //found the matching close { pairSpan = new SnapshotSpan(startPoint.Snapshot, line.Start + offset, 1); return true; } } else if (currentChar == open) // this is another open { openCount++; } offset++; } //move on to the next line if (++lineNumber > stopLineNumber) break; line = line.Snapshot.GetLineFromLineNumber(lineNumber); lineText = line.GetText(); offset = 0; } return false; } private static bool FindMatchingOpenChar(SnapshotPoint startPoint, char open, char close, int maxLines, out SnapshotSpan pairSpan) { pairSpan = new SnapshotSpan(startPoint, startPoint); var line = startPoint.GetContainingLine(); var lineNumber = line.LineNumber; var offset = startPoint - line.Start - 1; //move the offset to the character before this one //if the offset is negative, move to the previous line if (offset < 0) { line = line.Snapshot.GetLineFromLineNumber(--lineNumber); offset = line.Length - 1; } var lineText = line.GetText(); var stopLineNumber = 0; if (maxLines > 0) stopLineNumber = Math.Max(stopLineNumber, lineNumber - maxLines); var closeCount = 0; while (true) { // Walk the entire line while (offset >= 0) { var currentChar = lineText[offset]; if (currentChar == open) { if (closeCount > 0) { closeCount--; } else // We've found the open character { pairSpan = new SnapshotSpan(line.Start + offset, 1); //we just want the character itself return true; } } else if (currentChar == close) { closeCount++; } offset--; } // Move to the previous line if (--lineNumber < stopLineNumber) break; line = line.Snapshot.GetLineFromLineNumber(lineNumber); lineText = line.GetText(); offset = line.Length - 1; } return false; } } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System; using Voxalia.ClientGame.ClientMainSystem; using Voxalia.Shared; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL4; using Voxalia.ClientGame.OtherSystems; namespace Voxalia.ClientGame.GraphicsSystems.ParticleSystem { public class ParticleEffect { public Client TheClient; public ParticleEffectType Type; public Func<ParticleEffect, Location> Start; public Func<ParticleEffect, Location> End; public Func<ParticleEffect, float> FData; public int InternalParticleTextureID = -1; public float Alpha = 1; public float TTL; public float O_TTL; public bool Fades; public Func<ParticleEffect, float> AltAlpha = null; public Location Color; public Location Color2; public Texture texture; public int TID = -1; public Action<ParticleEffect> OnDestroy = null; public bool BlowsInWind = true; public Location WindOffset = Location.Zero; public float MinimumLight = 0f; public static float FadeInOut(ParticleEffect pe) { float rel = pe.TTL / pe.O_TTL; if (rel >= 0.5) { return 1 - ((rel - 0.5f) * 2); } else { return rel * 2; } } public ParticleEffect(Client tclient) { TheClient = tclient; } double lTT = 0; public Tuple<Location, Vector4, Vector2> GetDetails() { if (lTT != TheClient.GlobalTickTimeLocal) { TTL -= (float)TheClient.gDelta; lTT = TheClient.GlobalTickTimeLocal; } if (TTL <= 0) { return null; } if (AltAlpha != null) { Alpha = AltAlpha(this); if (Alpha <= 0.01) { return null; } } else if (Fades) { Alpha -= (float)TheClient.gDelta / O_TTL; if (Alpha <= 0.01) { TTL = 0; return null; } } float rel = TTL / O_TTL; if (rel >= 1 || rel <= 0) { return null; } Location start = Start(this) + WindOffset; if (BlowsInWind) { WindOffset += TheClient.TheRegion.ActualWind * SimplexNoiseInternal.Generate((start.X + TheClient.GlobalTickTimeLocal) * 0.2, (start.Y + TheClient.GlobalTickTimeLocal) * 0.2, start.Z * 0.2) * 0.1; } Vector4 light = TheClient.TheRegion.GetLightAmountAdjusted(start, Location.UnitZ); Vector4 scolor = new Vector4((float)Color.X * light.X, (float)Color.Y * light.Y, (float)Color.Z * light.Z, Alpha * light.W); Vector4 scolor2 = new Vector4((float)Color2.X * light.X, (float)Color2.Y * light.Y, (float)Color2.Z * light.Z, Alpha * light.W); Vector4 rcol = scolor * rel + scolor2 * (1 - rel); float scale = (float)End(this).X; if (TID == -1) { TID = TheClient.Particles.Engine.GetTextureID(texture.Name); } return new Tuple<Location, Vector4, Vector2>(start, rcol, new Vector2(scale, TID)); } public void Render() { if (lTT != TheClient.GlobalTickTimeLocal) { TTL -= (float)TheClient.gDelta; lTT = TheClient.GlobalTickTimeLocal; } if (TTL <= 0) { return; } if (AltAlpha != null) { Alpha = AltAlpha(this); if (Alpha <= 0.01) { return; } } else if (Fades) { Alpha -= (float)TheClient.gDelta / O_TTL; if (Alpha <= 0.01) { TTL = 0; return; } } float rel = TTL / O_TTL; if (rel >= 1 || rel <= 0) { return; } texture.Bind(); Location start = Start(this) + WindOffset; if (BlowsInWind) { WindOffset += TheClient.TheRegion.ActualWind * SimplexNoiseInternal.Generate((start.X + TheClient.GlobalTickTimeLocal) * 0.2, (start.Y + TheClient.GlobalTickTimeLocal) * 0.2, start.Z * 0.2) * 0.1; } Vector4 light = TheClient.TheRegion.GetLightAmountAdjusted(start, Location.UnitZ); Vector4 scolor = new Vector4((float)Color.X * light.X, (float)Color.Y * light.Y, (float)Color.Z * light.Z, Alpha * light.W); Vector4 scolor2 = new Vector4((float)Color2.X * light.X, (float)Color2.Y * light.Y, (float)Color2.Z * light.Z, Alpha * light.W); Vector4 rcol = scolor * rel + scolor2 * (1 - rel); rcol = Vector4.Max(rcol, new Vector4(MinimumLight, MinimumLight, MinimumLight, 0f)); TheClient.Rendering.SetColor(rcol); TheClient.Rendering.SetMinimumLight(MinimumLight); switch (Type) { case ParticleEffectType.LINE: { float dat = FData(this); if (dat != 1) { GL.LineWidth(dat); } TheClient.Rendering.RenderLine(start, End(this)); if (dat != 1) { GL.LineWidth(1); } } break; case ParticleEffectType.CYLINDER: { TheClient.Rendering.RenderCylinder(start, End(this), FData(this)); } break; case ParticleEffectType.LINEBOX: { float dat = FData(this); if (dat != 1) { GL.LineWidth(dat); } TheClient.Rendering.RenderLineBox(start, End(this)); if (dat != 1) { GL.LineWidth(1); } } break; case ParticleEffectType.BOX: { Matrix4d mat = Matrix4d.Scale(ClientUtilities.ConvertD(End(this))) * Matrix4d.CreateTranslation(ClientUtilities.ConvertD(start)); TheClient.MainWorldView.SetMatrix(2, mat); TheClient.Models.Cube.Draw(); } break; case ParticleEffectType.SPHERE: { Matrix4d mat = Matrix4d.Scale(ClientUtilities.ConvertD(End(this))) * Matrix4d.CreateTranslation(ClientUtilities.ConvertD(start)); TheClient.MainWorldView.SetMatrix(2, mat); TheClient.Models.Sphere.Draw(); } break; case ParticleEffectType.SQUARE: { TheClient.Rendering.RenderBillboard(start, End(this), TheClient.MainWorldView.CameraPos); } break; default: throw new NotImplementedException(); } } public ParticleEffect Clone() { return (ParticleEffect) MemberwiseClone(); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Generators\EnvQueryGenerator_BlueprintBase.h:17 namespace UnrealEngine { [ManageType("ManageEnvQueryGenerator_BlueprintBase")] public partial class ManageEnvQueryGenerator_BlueprintBase : UEnvQueryGenerator_BlueprintBase, IManageWrapper { public ManageEnvQueryGenerator_BlueprintBase(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_UpdateNodeVersion(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryGenerator_BlueprintBase_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods public override void UpdateNodeVersion() => E__Supper__UEnvQueryGenerator_BlueprintBase_UpdateNodeVersion(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UEnvQueryGenerator_BlueprintBase_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UEnvQueryGenerator_BlueprintBase_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UEnvQueryGenerator_BlueprintBase_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UEnvQueryGenerator_BlueprintBase_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UEnvQueryGenerator_BlueprintBase_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UEnvQueryGenerator_BlueprintBase_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UEnvQueryGenerator_BlueprintBase_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UEnvQueryGenerator_BlueprintBase_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UEnvQueryGenerator_BlueprintBase_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UEnvQueryGenerator_BlueprintBase_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UEnvQueryGenerator_BlueprintBase_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UEnvQueryGenerator_BlueprintBase_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UEnvQueryGenerator_BlueprintBase_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UEnvQueryGenerator_BlueprintBase_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UEnvQueryGenerator_BlueprintBase_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageEnvQueryGenerator_BlueprintBase self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageEnvQueryGenerator_BlueprintBase(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageEnvQueryGenerator_BlueprintBase>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Web.Script.Serialization; // Note: To enable JSON (JavaScriptSerializer) add following reference: System.Web.Extensions namespace GetAccount { public class hftRequest { public getAuthorizationChallengeRequest getAuthorizationChallenge { get; set; } public getAuthorizationTokenRequest getAuthorizationToken { get; set; } public getAccountRequest getAccount { get; set; } } public class hftResponse { public getAuthorizationChallengeResponse getAuthorizationChallengeResponse { get; set; } public getAuthorizationTokenResponse getAuthorizationTokenResponse { get; set; } public getAccountResponse getAccountResponse { get; set; } } public class getAuthorizationChallengeRequest { public string user { get; set; } public getAuthorizationChallengeRequest(String user) { this.user = user; } } public class getAuthorizationChallengeResponse { public string challenge { get; set; } public string timestamp { get; set; } } public class getAuthorizationTokenRequest { public string user { get; set; } public string challengeresp { get; set; } public getAuthorizationTokenRequest(String user, String challengeresp) { this.user = user; this.challengeresp = challengeresp; } } public class getAuthorizationTokenResponse { public string token { get; set; } public string timestamp { get; set; } } public class getAccountRequest { public string user { get; set; } public string token { get; set; } public getAccountRequest(string user, string token) { this.user = user; this.token = token; } } public class getAccountResponse { public List<accountTick> account { get; set; } public string timestamp { get; set; } } public class accountTick { public string name { get; set; } public string description { get; set; } public string style { get; set; } public int leverage { get; set; } public string rollover { get; set; } public string settlement { get; set; } } class GetAccount { private static bool ssl = true; private static String URL = "/getAccount"; private static String domain; //private static String url_stream; private static String url_polling; private static String url_challenge; private static String url_token; private static String user; private static String password; private static String authentication_port; private static String request_port; private static String ssl_cert; private static String challenge; private static String token; //private static int interval; public static void Exec() { // get properties from file getProperties(); HttpWebRequest httpWebRequest; JavaScriptSerializer serializer; HttpWebResponse httpResponse; X509Certificate certificate1 = null; if (ssl) { using (WebClient client = new WebClient()) { client.DownloadFile(ssl_cert, "ssl.cert"); } certificate1 = new X509Certificate("ssl.cert"); } // get challenge httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_challenge); serializer = new JavaScriptSerializer(); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (ssl) { httpWebRequest.ClientCertificates.Add(certificate1); } using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { hftRequest request = new hftRequest(); request.getAuthorizationChallenge = new getAuthorizationChallengeRequest(user); streamWriter.WriteLine(serializer.Serialize(request)); } httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream())) { hftResponse response; try { response = serializer.Deserialize<hftResponse>(streamReader.ReadLine()); challenge = response.getAuthorizationChallengeResponse.challenge; } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ioex) { Console.WriteLine(ioex.Message); } } // create challenge response String res = challenge; char[] passwordArray = password.ToCharArray(); foreach (byte passwordLetter in passwordArray) { int value = Convert.ToInt32(passwordLetter); string hexOutput = String.Format("{0:X}", value); res = res + hexOutput; } int NumberChars = res.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) { bytes[i / 2] = Convert.ToByte(res.Substring(i, 2), 16); } SHA1 sha = new SHA1CryptoServiceProvider(); byte[] tokenArray = sha.ComputeHash(bytes); string challengeresp = BitConverter.ToString(tokenArray); challengeresp = challengeresp.Replace("-", ""); // get token with challenge response httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + authentication_port + url_token); serializer = new JavaScriptSerializer(); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (ssl) { httpWebRequest.ClientCertificates.Add(certificate1); } using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { hftRequest request = new hftRequest(); request.getAuthorizationToken = new getAuthorizationTokenRequest(user, challengeresp); streamWriter.WriteLine(serializer.Serialize(request)); } httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream())) { hftResponse response; try { response = serializer.Deserialize<hftResponse>(streamReader.ReadLine()); token = response.getAuthorizationTokenResponse.token; } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ioex) { Console.WriteLine(ioex.Message); } } // ----------------------------------------- // Prepare and send a getAccount request // ----------------------------------------- httpWebRequest = (HttpWebRequest)WebRequest.Create(domain + ":" + request_port + url_polling + URL); serializer = new JavaScriptSerializer(); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; if (ssl) { httpWebRequest.ClientCertificates.Add(certificate1); } using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { hftRequest request = new hftRequest(); request.getAccount = new getAccountRequest(user, token); streamWriter.WriteLine(serializer.Serialize(request)); } // -------------------------------------------------------------- // Wait for response from server (polling) // -------------------------------------------------------------- httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream())) { hftResponse response; String line; try { while ((line = streamReader.ReadLine()) != null) { response = serializer.Deserialize<hftResponse>(line); if (response.getAccountResponse != null) { if (response.getAccountResponse.account != null) { foreach (accountTick tick in response.getAccountResponse.account) { Console.WriteLine("Name: " + tick.name + " Style: " + tick.style + " Leverage: " + tick.leverage); } } } } } catch (SocketException ex) { Console.WriteLine(ex.Message); } catch (IOException ioex) { Console.WriteLine(ioex.Message); } } } private static void getProperties() { try { foreach (var row in File.ReadAllLines("config.properties")) { //Console.WriteLine(row); /* if ("url-stream".Equals(row.Split('=')[0])) { url_stream = row.Split('=')[1]; } */ if ("url-polling".Equals(row.Split('=')[0])) { url_polling = row.Split('=')[1]; } if ("url-challenge".Equals(row.Split('=')[0])) { url_challenge = row.Split('=')[1]; } if ("url-token".Equals(row.Split('=')[0])) { url_token = row.Split('=')[1]; } if ("user".Equals(row.Split('=')[0])) { user = row.Split('=')[1]; } if ("password".Equals(row.Split('=')[0])) { password = row.Split('=')[1]; } /* if ("interval".Equals(row.Split('=')[0])) { interval = Int32.Parse(row.Split('=')[1]); } */ if (ssl) { if ("ssl-domain".Equals(row.Split('=')[0])) { domain = row.Split('=')[1]; } if ("ssl-authentication-port".Equals(row.Split('=')[0])) { authentication_port = row.Split('=')[1]; } if ("ssl-request-port".Equals(row.Split('=')[0])) { request_port = row.Split('=')[1]; } if ("ssl-cert".Equals(row.Split('=')[0])) { ssl_cert = row.Split('=')[1]; } } else { if ("domain".Equals(row.Split('=')[0])) { domain = row.Split('=')[1]; } if ("authentication-port".Equals(row.Split('=')[0])) { authentication_port = row.Split('=')[1]; } if ("request-port".Equals(row.Split('=')[0])) { request_port = row.Split('=')[1]; } } } } catch (IOException ex) { Console.WriteLine(ex.Message); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ExtractVector128UInt321() { var test = new ImmUnaryOpTest__ExtractVector128UInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.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__ExtractVector128UInt321 { private struct TestStruct { public Vector256<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ExtractVector128UInt321 testClass) { var result = Avx.ExtractVector128(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector256<UInt32> _clsVar; private Vector256<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static ImmUnaryOpTest__ExtractVector128UInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public ImmUnaryOpTest__ExtractVector128UInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.ExtractVector128( Unsafe.Read<Vector256<UInt32>>(_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 = Avx.ExtractVector128( Avx.LoadVector256((UInt32*)(_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 = Avx.ExtractVector128( Avx.LoadAlignedVector256((UInt32*)(_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(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.ExtractVector128), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.ExtractVector128( _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<Vector256<UInt32>>(_dataTable.inArrayPtr); var result = Avx.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx.ExtractVector128(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ExtractVector128UInt321(); var result = Avx.ExtractVector128(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.ExtractVector128(_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 = Avx.ExtractVector128(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(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != firstOp[4]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i+4]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtractVector128)}<UInt32>(Vector256<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Dictionary.cs - Implementation of the * "System.Collections.Generic.Dictionary" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Collections.Generic { #if CONFIG_GENERICS using System.Runtime.InteropServices; #if !ECMA_COMPAT [ComVisible(false)] #endif [CLSCompliant(false)] public class Dictionary<K,V> : System.Collections.ICollection, ICollection< KeyValuePair<K,V> >, System.Collections.IDictionary, IDictionary<K,V>, System.Collections.IEnumerable, IEnumerable< KeyValuePair<K,V> > { // Constructors. [TODO] public Dictionary() { // TODO } [TODO] public Dictionary(int capacity) { // TODO } [TODO] public Dictionary(IKeyComparer comparer) { // TODO } [TODO] public Dictionary(int capacity, IKeyComparer comparer) { // TODO } [TODO] public Dictionary(IDictionary<K,V> dictionary) { // TODO } [TODO] public Dictionary(IDictionary<K,V> dictionary, IKeyComparer comparer) { // TODO } // Implement the non-generic ICollection interface. [TODO] void System.Collections.ICollection.CopyTo(Array array, int index) { // TODO } int System.Collections.ICollection.Count { get { return Count; } } bool System.Collections.ICollection.IsSynchronized { get { return false; } } Object System.Collections.ICollection.SyncRoot { get { return this; } } // Implement the generic ICollection<KeyValuePair<K,V>> interface. [TODO] void ICollection< KeyValuePair<K,V> >.CopyTo (KeyValuePair<K,V> array, int index) { // TODO } [TODO] public int Count { get { // TODO return 0; } } // Implement the non-generic IDictionary interface. [TODO] void System.Collections.IDictionary.Add(Object key, Object value) { // TODO } void System.Collections.IDictionary.Clear() { Clear(); } bool System.Collections.IDictionary.Contains(Object key) { if(key == null) { return false; } else if(key is K) { return ContainsKey((K)key); } else { return false; } } [TODO] new IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { // TODO return null; } void System.Collections.IDictionary.Remove(Object key) { if(key != null && key is K) { Remove((K)key); } } bool System.Collections.IDictionary.IsFixedSize { get { return false; } } bool System.Collections.IDictionary.IsReadOnly { get { return false; } } Object System.Collections.IDictionary.this[Object key] { get { if(key == null) { throw new ArgumentNullException("key"); } else if(key is K) { return this[(K)key]; } else { return null; } } set { if(key == null) { throw new ArgumentNullException("key"); } else { this[(K)key] = (V)value; } } } ICollection System.Collections.IDictionary.Keys { get { return (ICollection)Keys; } } ICollection System.Collections.IDictionary.Values { get { return (ICollection)Values; } } // Implement the generic IDictionary<K,V> interface. [TODO] public void Add(K key, V value) { // TODO } [TODO] public void Clear() { // TODO } [TODO] public bool ContainsKey(K key) { // TODO return false; } [TODO] public bool Remove(K key) { // TODO return false; } bool IDictionary<K,V>.IsFixedSize { get { return false; } } bool IDictionary<K,V>.IsReadOnly { get { return false; } } [TODO[ V IDictionary.this[K key] { get { // TODO throw new NotImplementedException(); } set { // TODO } } [TODO] public ICollection<K> Keys { get { // TODO return null; } } [TODO] public ICollection<V> Values { get { // TODO return null; } } // Implement the non-generic IEnumerable interface. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } // Implement the generic IEnumerable< KeyValuePair<K,V> > interface. IEnumerator< KeyValuePair<K,V> > IEnumerable< KeyValuePair<K,V> >.GetEnumerator() { return GetEnumerator(); } // Determine if this dictionary contains a particular value. [TODO] public bool ContainsValue(V value) { // TODO return false; } // Get an enumerator for this dictionary. public Enumerator<K,V> GetEnumerator() { // TODO return new Enumerator(this); } // Enumerator class for generic dictionaries. public struct Enumerator<K,V> : System.Collections.IEnumerator, IEnumerator< KeyValuePair<K,V> > { // Constructor. [TODO] internal Enumerator(Dictionary<K,V> dictionary) { // TODO } // Dispose of this enumerator. public void Dispose() { // TODO } // Implement the non-generic IEnumerator interface. bool System.Collections.IEnumerator.MoveNext() { return MoveNext(); } void System.Collections.IEnumerator.Reset() { throw new InvalidOperationException(); } Object System.Collections.IEnumerator.Current { get { return Current; } } // Implement the generic IEnumerator< KeyValuePair<K,V> > interface. public bool MoveNext() { // TODO return false; } public KeyValuePair<K,V> Current { get { // TODO throw new NotImplementedException(); } } }; // struct Enumerator<K,V> }; // class IDictionary<K,V> #endif // CONFIG_GENERICS }; // namespace System.Collections.Generic
using UnityEngine; using System.Collections; [System.Serializable] public class YoYo : MonoBehaviour { public Transform playerObj; public Transform handTransform; public GameObject enemy ; public string yoyoThrowButton = "PS4_SQUARE"; public string yoyoThrowKey = "r"; //public float throwSpeed = 1f; private float throwTime = 0f; //public LayerMask hitCheckLayers; private Vector3 beginPoint = new Vector3(0f, 0f, 0f); private Vector3 finalPoint = new Vector3(0f, 0f, 30f); private Vector3 centerPoint = new Vector3(0f, 0f, 0f); public Vector3 offset = Vector3.zero; private Vector3 origPos; private RaycastHit hit; private bool collided = false; private bool playerHasYoyo = true; public GameObject effects; public float posX = 0f; public float posZ = 0f; public Vector3 test; [HideInInspector] public Rigidbody rigidBody; [HideInInspector] public MeshCollider meshCollider; [HideInInspector] public TrailRenderer trailRenderer; void Start () { origPos = transform.position; trailRenderer = this.GetComponent<TrailRenderer>(); rigidBody = this.GetComponent<Rigidbody>(); meshCollider = this.GetComponent<MeshCollider>(); trailRenderer.enabled = false; offset = new Vector3(-0.03f, 0f, 0.06f); enemy = new GameObject(); ResetYoyoState(); Charging(false); } private void FixedUpdate() { enemy = playerObj.gameObject.GetComponent<RPGCharacterControllerFREE>().currentTarget; if (enemy != null) { beginPoint = enemy.transform.position; } else if (playerHasYoyo) { beginPoint = new Vector3(playerObj.position.x, this.transform.position.y, playerObj.position.z) + playerObj.forward * 5f; } //new Vector3(posX + 0.15f, transform.position.y, posZ) + (Vector3.forward * 5f);//enemy.position; finalPoint = beginPoint; finalPoint.z = -finalPoint.z; centerPoint = Vector3.Lerp(beginPoint, finalPoint, 0.1f); meshCollider.enabled = !playerHasYoyo; } void Update() { //if (Vector3.Distance(transform.position, playerObj.position) >= 10f && !playerHasYoyo) //{ // //ResetYoyoState(); //} //Check if player has yoyo and if it is thrown. if (playerHasYoyo && Input.GetButtonDown(yoyoThrowButton)) { Charging(true); trailRenderer.enabled = true; } //Check if player has yoyo and if it is thrown. if (playerHasYoyo && Input.GetButtonUp(yoyoThrowButton)) { posX = playerObj.position.x; posZ = playerObj.position.z; Charging(false); SetYoyoState(false); //Throw yoyo. transform.rotation = Quaternion.Euler(0, 0, 90); //Used to fix Z rotation. } if (playerHasYoyo) { if (throwTime == 0) { //Keep yoyo into player's hand. transform.position = handTransform.position + offset; transform.rotation = handTransform.rotation; } return; } //Increase throwTime by deltaTime throwTime += Time.deltaTime; if (throwTime > 0f && throwTime < 1f) { //Move yoyo at desired position transform.position = Vector3.Lerp(transform.position, beginPoint, throwTime); } else if (throwTime >= 1f && throwTime <= 2f) { //Random parabolic before return if (beginPoint.z > 0f) { transform.RotateAround(centerPoint, Vector3.left, 10 * Time.deltaTime); } else { transform.RotateAround(centerPoint, Vector3.right, 10 * Time.deltaTime); } } else if (throwTime > 2f && throwTime < 3f) { //Get yoyo back in hand smoothly with lerp function. transform.position = Vector3.Lerp(transform.position, handTransform.position + offset, throwTime - 2f); } if (throwTime >= 2.4f) { trailRenderer.enabled = false; if (!playerHasYoyo) { //Reset yoyo state. ResetYoyoState(); } } else { //Rotate yoyo 'till it returns to player's hand. transform.Rotate(Vector3.up, throwTime * 50f); } } public void SetYoyoState(bool isYoyoInHand) { playerHasYoyo = isYoyoInHand; } public void ResetYoyoState() { playerHasYoyo = true; transform.rotation = handTransform.rotation; collided = false; throwTime = 0f; rigidBody.useGravity = false; rigidBody.velocity = Vector3.zero; rigidBody.angularVelocity = Vector3.zero; } public void Charging(bool isCharging) { if (isCharging) { effects.SetActive(true); } else { effects.SetActive(false); } } //Used to check if yoyo hits something. void OnTriggerEnter(Collider other) { if (!playerHasYoyo) { //Check if hitted gameobject is an Enemy. if (other.transform.tag == "Enemy") { //Change CapsuleCollider with body collider of enemy. if (other.GetType() == typeof(CapsuleCollider)) { Destroy(other.transform.parent.gameObject); //Return yoyo into player's hand. throwTime = 2f; } } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.Configuration; using System.IO; using System.ComponentModel; using System.Collections.Generic; namespace Northwind.CSLA.Library { public delegate void CustomerInfoEvent(object sender); /// <summary> /// CustomerInfo Generated by MyGeneration using the CSLA Object Mapping template /// </summary> [Serializable()] [TypeConverter(typeof(CustomerInfoConverter))] public partial class CustomerInfo : ReadOnlyBase<CustomerInfo>, IDisposable { public event CustomerInfoEvent Changed; private void OnChange() { if (Changed != null) Changed(this); } #region Collection protected static List<CustomerInfo> _AllList = new List<CustomerInfo>(); private static Dictionary<string, CustomerInfo> _AllByPrimaryKey = new Dictionary<string, CustomerInfo>(); private static void ConvertListToDictionary() { List<CustomerInfo> remove = new List<CustomerInfo>(); foreach (CustomerInfo tmp in _AllList) { _AllByPrimaryKey[tmp.CustomerID.ToString()]=tmp; // Primary Key remove.Add(tmp); } foreach (CustomerInfo tmp in remove) _AllList.Remove(tmp); } internal static void AddList(CustomerInfoList lst) { foreach (CustomerInfo item in lst) _AllList.Add(item); } public static CustomerInfo GetExistingByPrimaryKey(string customerID) { ConvertListToDictionary(); string key = customerID.ToString(); if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } protected Customer _Editable; private IVEHasBrokenRules HasBrokenRules { get { IVEHasBrokenRules hasBrokenRules = null; if (_Editable != null) hasBrokenRules = _Editable.HasBrokenRules; return hasBrokenRules; } } private string _CustomerID = string.Empty; [System.ComponentModel.DataObjectField(true, true)] public string CustomerID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _CustomerID; } } private string _CompanyName = string.Empty; public string CompanyName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _CompanyName; } } private string _ContactName = string.Empty; public string ContactName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ContactName; } } private string _ContactTitle = string.Empty; public string ContactTitle { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ContactTitle; } } private string _Address = string.Empty; public string Address { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Address; } } private string _City = string.Empty; public string City { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _City; } } private string _Region = string.Empty; public string Region { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Region; } } private string _PostalCode = string.Empty; public string PostalCode { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _PostalCode; } } private string _Country = string.Empty; public string Country { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Country; } } private string _Phone = string.Empty; public string Phone { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Phone; } } private string _Fax = string.Empty; public string Fax { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Fax; } } private int _CustomerCustomerCustomerDemoCount = 0; /// <summary> /// Count of CustomerCustomerCustomerDemos for this Customer /// </summary> public int CustomerCustomerCustomerDemoCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _CustomerCustomerCustomerDemoCount; } } private CustomerCustomerDemoInfoList _CustomerCustomerCustomerDemos = null; [TypeConverter(typeof(CustomerCustomerDemoInfoListConverter))] public CustomerCustomerDemoInfoList CustomerCustomerCustomerDemos { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_CustomerCustomerCustomerDemoCount > 0 && _CustomerCustomerCustomerDemos == null) _CustomerCustomerCustomerDemos = CustomerCustomerDemoInfoList.GetByCustomerID(_CustomerID); return _CustomerCustomerCustomerDemos; } } private int _CustomerOrderCount = 0; /// <summary> /// Count of CustomerOrders for this Customer /// </summary> public int CustomerOrderCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _CustomerOrderCount; } } private OrderInfoList _CustomerOrders = null; [TypeConverter(typeof(OrderInfoListConverter))] public OrderInfoList CustomerOrders { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_CustomerOrderCount > 0 && _CustomerOrders == null) _CustomerOrders = OrderInfoList.GetByCustomerID(_CustomerID); return _CustomerOrders; } } // TODO: Replace base CustomerInfo.ToString function as necessary /// <summary> /// Overrides Base ToString /// </summary> /// <returns>A string representation of current CustomerInfo</returns> //public override string ToString() //{ // return base.ToString(); //} // TODO: Check CustomerInfo.GetIdValue to assure that the ID returned is unique /// <summary> /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// </summary> /// <returns>A Unique ID for the current CustomerInfo</returns> protected override object GetIdValue() { return _CustomerID; } #endregion #region Factory Methods private CustomerInfo() {/* require use of factory methods */ _AllList.Add(this); } public void Dispose() { _AllList.Remove(this); _AllByPrimaryKey.Remove(CustomerID.ToString()); } public virtual Customer Get() { return _Editable = Customer.Get(_CustomerID); } public static void Refresh(Customer tmp) { CustomerInfo tmpInfo = GetExistingByPrimaryKey(tmp.CustomerID); if (tmpInfo == null) return; tmpInfo.RefreshFields(tmp); } private void RefreshFields(Customer tmp) { _CompanyName = tmp.CompanyName; _ContactName = tmp.ContactName; _ContactTitle = tmp.ContactTitle; _Address = tmp.Address; _City = tmp.City; _Region = tmp.Region; _PostalCode = tmp.PostalCode; _Country = tmp.Country; _Phone = tmp.Phone; _Fax = tmp.Fax; _CustomerInfoExtension.Refresh(this); OnChange();// raise an event } public static CustomerInfo Get(string customerID) { //if (!CanGetObject()) // throw new System.Security.SecurityException("User not authorized to view a Customer"); try { CustomerInfo tmp = GetExistingByPrimaryKey(customerID); if (tmp == null) { tmp = DataPortal.Fetch<CustomerInfo>(new PKCriteria(customerID)); _AllList.Add(tmp); } if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) { throw new DbCslaException("Error on CustomerInfo.Get", ex); } } #endregion #region Data Access Portal internal CustomerInfo(SafeDataReader dr) { Database.LogInfo("CustomerInfo.Constructor", GetHashCode()); try { ReadData(dr); } catch (Exception ex) { Database.LogException("CustomerInfo.Constructor", ex); throw new DbCslaException("CustomerInfo.Constructor", ex); } } [Serializable()] protected class PKCriteria { private string _CustomerID; public string CustomerID { get { return _CustomerID; } } public PKCriteria(string customerID) { _CustomerID = customerID; } } private void ReadData(SafeDataReader dr) { Database.LogInfo("CustomerInfo.ReadData", GetHashCode()); try { _CustomerID = dr.GetString("CustomerID"); _CompanyName = dr.GetString("CompanyName"); _ContactName = dr.GetString("ContactName"); _ContactTitle = dr.GetString("ContactTitle"); _Address = dr.GetString("Address"); _City = dr.GetString("City"); _Region = dr.GetString("Region"); _PostalCode = dr.GetString("PostalCode"); _Country = dr.GetString("Country"); _Phone = dr.GetString("Phone"); _Fax = dr.GetString("Fax"); _CustomerCustomerCustomerDemoCount = dr.GetInt32("CustomerCustomerDemoCount"); _CustomerOrderCount = dr.GetInt32("OrderCount"); } catch (Exception ex) { Database.LogException("CustomerInfo.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("CustomerInfo.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { Database.LogInfo("CustomerInfo.DataPortal_Fetch", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "getCustomer"; cm.Parameters.AddWithValue("@CustomerID", criteria.CustomerID); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); } } // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { Database.LogException("CustomerInfo.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("CustomerInfo.DataPortal_Fetch", ex); } } #endregion // Standard Refresh #region extension CustomerInfoExtension _CustomerInfoExtension = new CustomerInfoExtension(); [Serializable()] partial class CustomerInfoExtension : extensionBase {} [Serializable()] class extensionBase { // Default Refresh public virtual void Refresh(CustomerInfo tmp) { } } #endregion } // Class #region Converter internal class CustomerInfoConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is CustomerInfo) { // Return the ToString value return ((CustomerInfo)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace
using System; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Digests { /** * Base class for SHA-384 and SHA-512. */ public abstract class LongDigest : IDigest { private int MyByteLength = 128; private byte[] xBuf; private int xBufOff; private long byteCount1; private long byteCount2; internal ulong H1, H2, H3, H4, H5, H6, H7, H8; private ulong[] W = new ulong[80]; private int wOff; /** * Constructor for variable length word */ internal LongDigest() { xBuf = new byte[8]; Reset(); } /** * Copy constructor. We are using copy constructors in place * of the object.Clone() interface as this interface is not * supported by J2ME. */ internal LongDigest( LongDigest t) { xBuf = new byte[t.xBuf.Length]; Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length); xBufOff = t.xBufOff; byteCount1 = t.byteCount1; byteCount2 = t.byteCount2; H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.W, 0, W, 0, t.W.Length); wOff = t.wOff; } public void Update( byte input) { xBuf[xBufOff++] = input; if (xBufOff == xBuf.Length) { ProcessWord(xBuf, 0); xBufOff = 0; } byteCount1++; } public void BlockUpdate( byte[] input, int inOff, int length) { // // fill the current word // while ((xBufOff != 0) && (length > 0)) { Update(input[inOff]); inOff++; length--; } // // process whole words. // while (length > xBuf.Length) { ProcessWord(input, inOff); inOff += xBuf.Length; length -= xBuf.Length; byteCount1 += xBuf.Length; } // // load in the remainder. // while (length > 0) { Update(input[inOff]); inOff++; length--; } } public void Finish() { AdjustByteCounts(); long lowBitLength = byteCount1 << 3; long hiBitLength = byteCount2; // // add the pad bytes. // Update((byte)128); while (xBufOff != 0) { Update((byte)0); } ProcessLength(lowBitLength, hiBitLength); ProcessBlock(); } public virtual void Reset() { byteCount1 = 0; byteCount2 = 0; xBufOff = 0; for ( int i = 0; i < xBuf.Length; i++ ) { xBuf[i] = 0; } wOff = 0; Array.Clear(W, 0, W.Length); } internal void ProcessWord( byte[] input, int inOff) { W[wOff] = Pack.BE_To_UInt64(input, inOff); if (++wOff == 16) { ProcessBlock(); } } /** * adjust the byte counts so that byteCount2 represents the * upper long (less 3 bits) word of the byte count. */ private void AdjustByteCounts() { if (byteCount1 > 0x1fffffffffffffffL) { byteCount2 += (long) ((ulong) byteCount1 >> 61); byteCount1 &= 0x1fffffffffffffffL; } } internal void ProcessLength( long lowW, long hiW) { if (wOff > 14) { ProcessBlock(); } W[14] = (ulong)hiW; W[15] = (ulong)lowW; } internal void ProcessBlock() { AdjustByteCounts(); // // expand 16 word block into 80 word blocks. // for (int ti = 16; ti <= 79; ++ti) { W[ti] = Sigma1(W[ti - 2]) + W[ti - 7] + Sigma0(W[ti - 15]) + W[ti - 16]; } // // set up working variables. // ulong a = H1; ulong b = H2; ulong c = H3; ulong d = H4; ulong e = H5; ulong f = H6; ulong g = H7; ulong h = H8; int t = 0; for(int i = 0; i < 10; i ++) { // t = 8 * i h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++]; d += h; h += Sum0(a) + Maj(a, b, c); // t = 8 * i + 1 g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++]; c += g; g += Sum0(h) + Maj(h, a, b); // t = 8 * i + 2 f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++]; b += f; f += Sum0(g) + Maj(g, h, a); // t = 8 * i + 3 e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++]; a += e; e += Sum0(f) + Maj(f, g, h); // t = 8 * i + 4 d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++]; h += d; d += Sum0(e) + Maj(e, f, g); // t = 8 * i + 5 c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++]; g += c; c += Sum0(d) + Maj(d, e, f); // t = 8 * i + 6 b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++]; f += b; b += Sum0(c) + Maj(c, d, e); // t = 8 * i + 7 a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++]; e += a; a += Sum0(b) + Maj(b, c, d); } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // wOff = 0; Array.Clear(W, 0, 16); } /* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */ private static ulong Ch(ulong x, ulong y, ulong z) { return (x & y) ^ (~x & z); } private static ulong Maj(ulong x, ulong y, ulong z) { return (x & y) ^ (x & z) ^ (y & z); } private static ulong Sum0(ulong x) { return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39)); } private static ulong Sum1(ulong x) { return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41)); } private static ulong Sigma0(ulong x) { return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7); } private static ulong Sigma1(ulong x) { return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6); } /* SHA-384 and SHA-512 Constants * (represent the first 64 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ internal static readonly ulong[] K = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; public int GetByteLength() { return MyByteLength; } public abstract string AlgorithmName { get; } public abstract int GetDigestSize(); public abstract int DoFinal(byte[] output, int outOff); } }
// 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 FloorSingle() { var test = new SimpleUnaryOpTest__FloorSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__FloorSingle { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__FloorSingle testClass) { var result = Sse41.Floor(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__FloorSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.Floor( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__FloorSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__FloorSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Floor( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Floor( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Floor( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Floor), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Floor), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Floor), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Floor( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = Sse41.Floor( Sse.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = Sse41.Floor(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.Floor(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var result = Sse41.Floor(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__FloorSingle(); var result = Sse41.Floor(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__FloorSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = Sse41.Floor( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Floor(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = Sse41.Floor( Sse.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Floor(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.Floor( Sse.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[0]))) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Floor(firstOp[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Floor)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
namespace System.Windows.Forms { using System.Drawing; public class ToolStripDropDownItem : ToolStripItem { private readonly ToolStripItemCollection dropDownItems; private ToolStripDropDown dropDownToolStrip; private ToolStripDropDown userDropDown; private float mouseHoverTime; private bool pressed; protected ToolStripDropDownItem() { dropDownItems = new ToolStripItemCollection(Parent, null); ArrowColor = Color.Black; ArrowImage = ApplicationResources.Images.DropDownRightArrow; } internal delegate void uwfDropDownHandler(ToolStripDropDown dropDown); internal event uwfDropDownHandler uwfDropDownCreated; // Workaround to not implement ToolStripRenderer. public ToolStripDropDown DropDown { get { return dropDownToolStrip; } set { userDropDown = value; } } public ToolStripItemCollection DropDownItems { get { return dropDownItems; } } public override bool Pressed { get { return pressed; } } internal Color ArrowColor { get; set; } internal Bitmap ArrowImage { get; set; } internal void CloseEverything() { // Self var parent = Owner as ToolStripDropDown; if (parent != null) { parent.Dispose(); var parentItem = parent.OwnerItem as ToolStripDropDownItem; if (parentItem != null) parentItem.CloseEverything(); } } internal void CloseToolStrip() { if (dropDownToolStrip == null) return; if (dropDownToolStrip.IsDisposed == false) dropDownToolStrip.Dispose(); } internal void CreateToolStrip() { if (Enabled == false) return; if (dropDownItems.Count == 0) return; var dropDownBounds = new Rectangle(Point.Empty, Owner.Size); for (int i = 0; i < dropDownItems.Count; i++) // Reset items. { var item = dropDownItems[i]; item.Unselect(); var dropDownItem = item as ToolStripDropDownItem; if (dropDownItem == null) continue; dropDownItem.ArrowImage = ApplicationResources.Images.DropDownRightArrow; dropDownItem.ArrowColor = Color.Black; } var direction = ToolStripDropDownDirection.Right; if (Owner.IsDropDown == false) direction = ToolStripDropDownDirection.BelowRight; dropDownToolStrip = userDropDown == null ? new ToolStripDropDownMenu() : userDropDown; dropDownToolStrip.OwnerItem = this; dropDownToolStrip.Items.AddRange(dropDownItems); dropDownToolStrip.selectedItem = dropDownToolStrip.SelectNextToolStripItem(null, true); dropDownToolStrip.shouldFixWidth = true; dropDownToolStrip.direction = direction; dropDownToolStrip.Location = DropDownDirectionToDropDownBounds(direction, dropDownBounds).Location; dropDownToolStrip.Disposed += DropDownToolStrip_Disposed; dropDownToolStrip.Show(dropDownToolStrip.Location); if (uwfDropDownCreated != null) uwfDropDownCreated(dropDownToolStrip); pressed = true; } internal void ResetToolStrip() { if (dropDownToolStrip == null) return; var clientRect = new Rectangle(dropDownToolStrip.Location, dropDownToolStrip.Size); var contains = clientRect.Contains(Owner.PointToClient(Control.MousePosition)); if (!contains) pressed = false; else pressed = !pressed; dropDownToolStrip.Disposed -= DropDownToolStrip_Disposed; dropDownToolStrip = null; //Owner.Focus(); } internal override void Unselect() { base.Unselect(); if (dropDownToolStrip == null) return; CloseToolStrip(); } protected internal override void DrawImage(Graphics graphics) { var image = Image; if (image != null) { var rect = Bounds; graphics.uwfDrawImage( image, uwfImageColor, rect.X + 2, rect.Y + 2, rect.Height - 4, rect.Height - 4); } } protected override void OnClick(EventArgs e) { if (Enabled == false) return; base.OnClick(e); if (DropDownItems.Count == 0) { CloseEverything(); return; } if (dropDownToolStrip != null) return; if (!pressed) CreateToolStrip(); else pressed = false; } protected override void OnMouseHover(EventArgs e) { base.OnMouseHover(e); if (Owner == null || Owner.IsDropDown == false) return; // Create toolstrip if hovering item with mouse. if (dropDownToolStrip != null) { mouseHoverTime = 0f; return; } mouseHoverTime += swfHelper.GetDeltaTime(); if (mouseHoverTime > .5f) CreateToolStrip(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (dropDownItems.Count > 0 && Owner != null && Owner.Orientation == Orientation.Vertical) { var bounds = Bounds; e.Graphics.uwfDrawImage( ArrowImage, ArrowColor, bounds.X + bounds.Width - 25, bounds.Y + (bounds.Height - ArrowImage.Height) / 2, ArrowImage.Width, ArrowImage.Height); } } private Rectangle DropDownDirectionToDropDownBounds(ToolStripDropDownDirection dropDownDirection, Rectangle dropDownBounds) { var offset = Point.Empty; switch (dropDownDirection) { case ToolStripDropDownDirection.AboveLeft: offset.X = -dropDownBounds.Width + this.Width; offset.Y = -dropDownBounds.Height + 1; break; case ToolStripDropDownDirection.AboveRight: offset.Y = -dropDownBounds.Height + 1; break; case ToolStripDropDownDirection.BelowRight: offset.Y = this.Height - 2; break; case ToolStripDropDownDirection.BelowLeft: offset.X = -dropDownBounds.Width + this.Width; offset.Y = this.Height - 1; break; case ToolStripDropDownDirection.Right: offset.X = this.Width; if (!IsOnDropDown) offset.X -= 1; else { offset.X -= 6; offset.Y -= 2; } break; case ToolStripDropDownDirection.Left: offset.X = -dropDownBounds.Width; break; } var itemScreenLocation = Owner.PointToScreen(Point.Empty); itemScreenLocation.Offset(Bounds.Location); dropDownBounds.Location = new Point(itemScreenLocation.X + offset.X, itemScreenLocation.Y + offset.Y); return dropDownBounds; } private void DropDownToolStrip_Disposed(object sender, EventArgs e) { ResetToolStrip(); } } }
// 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 CertNameStrTypeAndFlags dwStrType = CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG; string issuer = Interop.Crypt32.CertNameToStr(ref certId.u.IssuerSerialNumber.Issuer, dwStrType); 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.Assert(false); // 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); 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 = BinaryPrimitives.ReadMachineEndian<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 = BinaryPrimitives.ReadMachineEndian<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 = Helpers.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.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudioTools.Project { //[DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0Exp")] //[PackageRegistration(UseManagedResourcesOnly = true)] public abstract class CommonProjectPackage : ProjectPackage, IVsInstalledProduct, IOleComponent { private IOleComponentManager _compMgr; private uint _componentID; public abstract ProjectFactory CreateProjectFactory(); public abstract CommonEditorFactory CreateEditorFactory(); public virtual CommonEditorFactory CreateEditorFactoryPromptForEncoding() { return null; } /// <summary> /// This method is called to get the icon that will be displayed in the /// Help About dialog when this package is selected. /// </summary> /// <returns>The resource id corresponding to the icon to display on the Help About dialog</returns> public abstract uint GetIconIdForAboutBox(); /// <summary> /// This method is called during Devenv /Setup to get the bitmap to /// display on the splash screen for this package. /// </summary> /// <returns>The resource id corresponding to the bitmap to display on the splash screen</returns> public abstract uint GetIconIdForSplashScreen(); /// <summary> /// This methods provides the product official name, it will be /// displayed in the help about dialog. /// </summary> public abstract string GetProductName(); /// <summary> /// This methods provides the product description, it will be /// displayed in the help about dialog. /// </summary> public abstract string GetProductDescription(); /// <summary> /// This methods provides the product version, it will be /// displayed in the help about dialog. /// </summary> public abstract string GetProductVersion(); protected override void Initialize() { UIThread.EnsureService(this); base.Initialize(); this.RegisterProjectFactory(CreateProjectFactory()); var editFactory = CreateEditorFactory(); if (editFactory != null) { this.RegisterEditorFactory(editFactory); } var encodingEditorFactory = CreateEditorFactoryPromptForEncoding(); if (encodingEditorFactory != null) { RegisterEditorFactory(encodingEditorFactory); } var componentManager = this._compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager)); var crinfo = new OLECRINFO[1]; crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)); crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime; crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff; crinfo[0].uIdleTimeInterval = 0; ErrorHandler.ThrowOnFailure(componentManager.FRegisterComponent(this, crinfo, out this._componentID)); } protected override void Dispose(bool disposing) { try { if (this._componentID != 0) { if (GetService(typeof(SOleComponentManager)) is IOleComponentManager mgr) { mgr.FRevokeComponent(this._componentID); } this._componentID = 0; } } finally { base.Dispose(disposing); } } /// <summary> /// This method loads a localized string based on the specified resource. /// </summary> /// <param name="resourceName">Resource to load</param> /// <returns>String loaded for the specified resource</returns> public string GetResourceString(string resourceName) { var resourceManager = (IVsResourceManager)GetService(typeof(SVsResourceManager)); if (resourceManager == null) { throw new InvalidOperationException("Could not get SVsResourceManager service. Make sure the package is Sited before calling this method"); } var packageGuid = this.GetType().GUID; var hr = resourceManager.LoadResourceString(ref packageGuid, -1, resourceName, out var resourceValue); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); return resourceValue; } #region IVsInstalledProduct Members /// <summary> /// This method is called during Devenv /Setup to get the bitmap to /// display on the splash screen for this package. /// </summary> /// <param name="pIdBmp">The resource id corresponding to the bitmap to display on the splash screen</param> /// <returns>HRESULT, indicating success or failure</returns> public int IdBmpSplash(out uint pIdBmp) { pIdBmp = GetIconIdForSplashScreen(); return VSConstants.S_OK; } /// <summary> /// This method is called to get the icon that will be displayed in the /// Help About dialog when this package is selected. /// </summary> /// <param name="pIdIco">The resource id corresponding to the icon to display on the Help About dialog</param> /// <returns>HRESULT, indicating success or failure</returns> public int IdIcoLogoForAboutbox(out uint pIdIco) { pIdIco = GetIconIdForAboutBox(); return VSConstants.S_OK; } /// <summary> /// This methods provides the product official name, it will be /// displayed in the help about dialog. /// </summary> /// <param name="pbstrName">Out parameter to which to assign the product name</param> /// <returns>HRESULT, indicating success or failure</returns> public int OfficialName(out string pbstrName) { pbstrName = GetProductName(); return VSConstants.S_OK; } /// <summary> /// This methods provides the product description, it will be /// displayed in the help about dialog. /// </summary> /// <param name="pbstrProductDetails">Out parameter to which to assign the description of the package</param> /// <returns>HRESULT, indicating success or failure</returns> public int ProductDetails(out string pbstrProductDetails) { pbstrProductDetails = GetProductDescription(); return VSConstants.S_OK; } /// <summary> /// This methods provides the product version, it will be /// displayed in the help about dialog. /// </summary> /// <param name="pbstrPID">Out parameter to which to assign the version number</param> /// <returns>HRESULT, indicating success or failure</returns> public int ProductID(out string pbstrPID) { pbstrPID = GetProductVersion(); return VSConstants.S_OK; } #endregion #region IOleComponent Members public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) { return 1; } public int FDoIdle(uint grfidlef) { var onIdle = OnIdle; if (onIdle != null) { onIdle(this, new ComponentManagerEventArgs(this._compMgr)); } return 0; } internal event EventHandler<ComponentManagerEventArgs> OnIdle; public int FPreTranslateMessage(MSG[] pMsg) { return 0; } public int FQueryTerminate(int fPromptUser) { return 1; } public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) { return 1; } public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) { return IntPtr.Zero; } public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { } public void OnAppActivate(int fActive, uint dwOtherThreadID) { } public void OnEnterState(uint uStateID, int fEnter) { } public void OnLoseActivation() { } public void Terminate() { } #endregion } }
// // FieldDefinition.cs // // Author: // Jb Evain (jbevain@gmail.com) // // (C) 2005 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace Mono.Cecil { using Mono.Cecil; using Mono.Cecil.Binary; public sealed class FieldDefinition : FieldReference, IMemberDefinition, ICustomAttributeProvider, IHasMarshalSpec, IHasConstant { FieldAttributes m_attributes; CustomAttributeCollection m_customAttrs; bool m_hasInfo; uint m_offset; RVA m_rva; byte [] m_initVal; bool m_hasConstant; object m_const; MarshalSpec m_marshalDesc; public bool HasLayoutInfo { get { return m_hasInfo; } } public uint Offset { get { return m_offset; } set { m_hasInfo = true; m_offset = value; } } public RVA RVA { get { return m_rva; } set { m_rva = value; } } public byte [] InitialValue { get { return m_initVal; } set { m_initVal = value; } } public FieldAttributes Attributes { get { return m_attributes; } set { m_attributes = value; } } public bool HasConstant { get { return m_hasConstant; } } public object Constant { get { return m_const; } set { m_hasConstant = true; m_const = value; } } public CustomAttributeCollection CustomAttributes { get { if (m_customAttrs == null) m_customAttrs = new CustomAttributeCollection (this); return m_customAttrs; } } public MarshalSpec MarshalSpec { get { return m_marshalDesc; } set { m_marshalDesc = value; } } #region FieldAttributes public bool IsCompilerControlled { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Compilercontrolled; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.Compilercontrolled; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.Compilercontrolled); } } public bool IsPrivate { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.Private; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.Private); } } public bool IsFamilyAndAssembly { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.FamANDAssem; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.FamANDAssem); } } public bool IsAssembly { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.Assembly; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.Assembly); } } public bool IsFamily { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.Family; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.Family); } } public bool IsFamilyOrAssembly { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.FamORAssem; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.FamORAssem); } } public bool IsPublic { get { return (m_attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } set { if (value) { m_attributes &= ~FieldAttributes.FieldAccessMask; m_attributes |= FieldAttributes.Public; } else m_attributes &= ~(FieldAttributes.FieldAccessMask & FieldAttributes.Public); } } public bool IsStatic { get { return (m_attributes & FieldAttributes.Static) != 0; } set { if (value) m_attributes |= FieldAttributes.Static; else m_attributes &= ~FieldAttributes.Static; } } public bool IsInitOnly { get { return (m_attributes & FieldAttributes.InitOnly) != 0; } set { if (value) m_attributes |= FieldAttributes.InitOnly; else m_attributes &= ~FieldAttributes.InitOnly; } } public bool IsLiteral { get { return (m_attributes & FieldAttributes.Literal) != 0; } set { if (value) m_attributes |= FieldAttributes.Literal; else m_attributes &= ~FieldAttributes.Literal; } } public bool IsNotSerialized { get { return (m_attributes & FieldAttributes.NotSerialized) != 0; } set { if (value) m_attributes |= FieldAttributes.NotSerialized; else m_attributes &= ~FieldAttributes.NotSerialized; } } public bool IsSpecialName { get { return (m_attributes & FieldAttributes.SpecialName) != 0; } set { if (value) m_attributes |= FieldAttributes.SpecialName; else m_attributes &= ~FieldAttributes.SpecialName; } } public bool IsPInvokeImpl { get { return (m_attributes & FieldAttributes.PInvokeImpl) != 0; } set { if (value) m_attributes |= FieldAttributes.PInvokeImpl; else m_attributes &= ~FieldAttributes.PInvokeImpl; } } public bool IsRuntimeSpecialName { get { return (m_attributes & FieldAttributes.RTSpecialName) != 0; } set { if (value) m_attributes |= FieldAttributes.RTSpecialName; else m_attributes &= ~FieldAttributes.RTSpecialName; } } public bool HasDefault { get { return (m_attributes & FieldAttributes.HasDefault) != 0; } set { if (value) m_attributes |= FieldAttributes.HasDefault; else m_attributes &= ~FieldAttributes.HasDefault; } } #endregion public FieldDefinition (string name, TypeReference fieldType, FieldAttributes attrs) : base (name, fieldType) { m_attributes = attrs; } public FieldDefinition Clone () { return Clone (this, new ImportContext (NullReferenceImporter.Instance, this.DeclaringType)); } internal static FieldDefinition Clone (FieldDefinition field, ImportContext context) { FieldDefinition nf = new FieldDefinition ( field.Name, context.Import (field.FieldType), field.Attributes); if (field.HasConstant) nf.Constant = field.Constant; if (field.MarshalSpec != null) nf.MarshalSpec = field.MarshalSpec; if (field.RVA != RVA.Zero) nf.InitialValue = field.InitialValue; else nf.InitialValue = new byte [0]; if (field.HasLayoutInfo) nf.Offset = field.Offset; foreach (CustomAttribute ca in field.CustomAttributes) nf.CustomAttributes.Add (CustomAttribute.Clone (ca, context)); return nf; } public override void Accept (IReflectionVisitor visitor) { visitor.VisitFieldDefinition (this); if (this.MarshalSpec != null) this.MarshalSpec.Accept (visitor); this.CustomAttributes.Accept (visitor); } } }
// 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 XorSByte() { var test = new SimpleBinaryOpTest__XorSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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 (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorSByte { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int Op2ElementCount = VectorSize / sizeof(SByte); private const int RetElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable; static SimpleBinaryOpTest__XorSByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__XorSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Xor( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Xor( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Xor( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__XorSByte(); var result = Avx2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { if ((sbyte)(left[0] ^ right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((sbyte)(left[i] ^ right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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 Internal.IL.Stubs; using Internal.IL; using Debug = System.Diagnostics.Debug; using ILLocalVariable = Internal.IL.Stubs.ILLocalVariable; namespace Internal.TypeSystem.Interop { enum MarshallerKind { Unknown, BlittableValue, Array, BlittableArray, Bool, // 4 byte bool CBool, // 1 byte bool Enum, AnsiChar, // Marshal char (Unicode 16bits) for byte (Ansi 8bits) UnicodeChar, AnsiCharArray, ByValArray, ByValAnsiCharArray, // Particular case of ByValArray because the conversion between wide Char and Byte need special treatment. AnsiString, UnicodeString, ByValAnsiString, ByValUnicodeString, AnsiStringBuilder, UnicodeStringBuilder, FunctionPointer, SafeHandle, CriticalHandle, HandleRef, VoidReturn, Variant, Object, OleDateTime, Decimal, Guid, Struct, BlittableStruct, BlittableStructPtr, // Additional indirection on top of blittable struct. Used by MarshalAs(LpStruct) Invalid } public enum MarshalDirection { Forward, // safe-to-unsafe / managed-to-native Reverse, // unsafe-to-safe / native-to-managed } public enum MarshallerType { Argument, Element, Field } // Each type of marshaller knows how to generate the marshalling code for the argument it marshals. // Marshallers contain method related marshalling information (which is common to all the Marshallers) // and also argument specific marshalling informaiton abstract class Marshaller { #region Instance state information public TypeSystemContext Context; public InteropStateManager InteropStateManager; public MarshallerKind MarshallerKind; public MarshallerType MarshallerType; public MarshalAsDescriptor MarshalAsDescriptor; public MarshallerKind ElementMarshallerKind; public int Index; public TypeDesc ManagedType; public TypeDesc ManagedParameterType; public PInvokeFlags PInvokeFlags; protected Marshaller[] Marshallers; private TypeDesc _nativeType; private TypeDesc _nativeParamType; /// <summary> /// Native Type of the value being marshalled /// For by-ref scenarios (ref T), Native Type is T /// </summary> public TypeDesc NativeType { get { if (_nativeType == null) { _nativeType = MarshalHelpers.GetNativeTypeFromMarshallerKind( ManagedType, MarshallerKind, ElementMarshallerKind, InteropStateManager, MarshalAsDescriptor); Debug.Assert(_nativeType != null); } return _nativeType; } } /// <summary> /// NativeType appears in function parameters /// For by-ref scenarios (ref T), NativeParameterType is T* /// </summary> public TypeDesc NativeParameterType { get { if (_nativeParamType == null) { TypeDesc nativeParamType = NativeType; if (IsNativeByRef) nativeParamType = nativeParamType.MakePointerType(); _nativeParamType = nativeParamType; } return _nativeParamType; } } /// <summary> /// Indicates whether cleanup is necessay if this marshaller is used /// as an element of an array marshaller /// </summary> internal virtual bool CleanupRequired { get { return false; } } public bool In; public bool Out; public bool Return; public bool IsManagedByRef; // Whether managed argument is passed by ref public bool IsNativeByRef; // Whether native argument is passed by byref // There are special cases (such as LpStruct, and class) that // isNativeByRef != IsManagedByRef public MarshalDirection MarshalDirection; protected PInvokeILCodeStreams _ilCodeStreams; protected Home _managedHome; protected Home _nativeHome; #endregion enum HomeType { Arg, Local, ByRefArg, ByRefLocal } /// <summary> /// Abstraction for handling by-ref and non-by-ref locals/arguments /// </summary> internal class Home { public Home(ILLocalVariable var, TypeDesc type, bool isByRef) { _homeType = isByRef ? HomeType.ByRefLocal : HomeType.Local; _type = type; _var = var; } public Home(int argIndex, TypeDesc type, bool isByRef) { _homeType = isByRef ? HomeType.ByRefArg : HomeType.Arg; _type = type; _argIndex = argIndex; } public void LoadValue(ILCodeStream stream) { switch (_homeType) { case HomeType.Arg: stream.EmitLdArg(_argIndex); break; case HomeType.ByRefArg: stream.EmitLdArg(_argIndex); stream.EmitLdInd(_type); break; case HomeType.Local: stream.EmitLdLoc(_var); break; case HomeType.ByRefLocal: stream.EmitLdLoc(_var); stream.EmitLdInd(_type); break; default: Debug.Assert(false); break; } } public void LoadAddr(ILCodeStream stream) { switch (_homeType) { case HomeType.Arg: stream.EmitLdArga(_argIndex); break; case HomeType.ByRefArg: stream.EmitLdArg(_argIndex); break; case HomeType.Local: stream.EmitLdLoca(_var); break; case HomeType.ByRefLocal: stream.EmitLdLoc(_var); break; default: Debug.Assert(false); break; } } public void StoreValue(ILCodeStream stream) { switch (_homeType) { case HomeType.Arg: Debug.Fail("Unexpectting setting value on non-byref arg"); break; case HomeType.Local: stream.EmitStLoc(_var); break; default: // Storing by-ref arg/local is not supported because StInd require // address to be pushed first. Instead we need to introduce a non-byref // local and propagate value as needed for by-ref arguments Debug.Assert(false); break; } } HomeType _homeType; TypeDesc _type; ILLocalVariable _var; int _argIndex; } #region Creation of marshallers /// <summary> /// Protected ctor /// Only Marshaller.CreateMarshaller can create a marshaller /// </summary> protected Marshaller() { } /// <summary> /// Create a marshaller /// </summary> /// <param name="parameterType">type of the parameter to marshal</param> /// <returns>The created Marshaller</returns> public static Marshaller CreateMarshaller(TypeDesc parameterType, MarshallerType marshallerType, MarshalAsDescriptor marshalAs, MarshalDirection direction, Marshaller[] marshallers, InteropStateManager interopStateManager, int index, PInvokeFlags flags, bool isIn, bool isOut, bool isReturn) { MarshallerKind elementMarshallerKind; MarshallerKind marshallerKind = MarshalHelpers.GetMarshallerKind(parameterType, marshalAs, isReturn, flags.CharSet == CharSet.Ansi, marshallerType, out elementMarshallerKind); TypeSystemContext context = parameterType.Context; // Create the marshaller based on MarshallerKind Marshaller marshaller = CreateMarshaller(marshallerKind); marshaller.Context = context; marshaller.InteropStateManager = interopStateManager; marshaller.MarshallerKind = marshallerKind; marshaller.MarshallerType = marshallerType; marshaller.ElementMarshallerKind = elementMarshallerKind; marshaller.ManagedParameterType = parameterType; marshaller.ManagedType = parameterType.IsByRef ? parameterType.GetParameterType() : parameterType; marshaller.Return = isReturn; marshaller.IsManagedByRef = parameterType.IsByRef; marshaller.IsNativeByRef = marshaller.IsManagedByRef /* || isRetVal || LpStruct /etc */; marshaller.In = isIn; marshaller.MarshalDirection = direction; marshaller.MarshalAsDescriptor = marshalAs; marshaller.Marshallers = marshallers; marshaller.Index = index; marshaller.PInvokeFlags = flags; // // Desktop ignores [Out] on marshaling scenarios where they don't make sense // if (isOut) { // Passing as [Out] by ref is always valid. if (!marshaller.IsManagedByRef) { // Ignore [Out] for ValueType, string and pointers if (parameterType.IsValueType || parameterType.IsString || parameterType.IsPointer || parameterType.IsFunctionPointer) { isOut = false; } } } marshaller.Out = isOut; if (!marshaller.In && !marshaller.Out) { // // Rules for in/out // 1. ByRef args: [in]/[out] implied by default // 2. StringBuilder: [in, out] by default // 3. non-ByRef args: [In] is implied if no [In]/[Out] is specified // if (marshaller.IsManagedByRef) { marshaller.In = true; marshaller.Out = true; } else if (InteropTypes.IsStringBuilder(context, parameterType)) { marshaller.In = true; marshaller.Out = true; } else { marshaller.In = true; } } // For unicodestring/ansistring, ignore out when it's in if (!marshaller.IsManagedByRef && marshaller.In) { if (marshaller.MarshallerKind == MarshallerKind.AnsiString || marshaller.MarshallerKind == MarshallerKind.UnicodeString) marshaller.Out = false; } return marshaller; } protected static Marshaller CreateMarshaller(MarshallerKind kind) { switch (kind) { case MarshallerKind.Enum: case MarshallerKind.BlittableValue: case MarshallerKind.BlittableStruct: case MarshallerKind.UnicodeChar: return new BlittableValueMarshaller(); case MarshallerKind.BlittableStructPtr: return new BlittableStructPtrMarshaller(); case MarshallerKind.AnsiChar: return new AnsiCharMarshaller(); case MarshallerKind.Array: return new ArrayMarshaller(); case MarshallerKind.BlittableArray: return new BlittableArrayMarshaller(); case MarshallerKind.Bool: case MarshallerKind.CBool: return new BooleanMarshaller(); case MarshallerKind.AnsiString: return new AnsiStringMarshaller(); case MarshallerKind.UnicodeString: return new UnicodeStringMarshaller(); case MarshallerKind.SafeHandle: return new SafeHandleMarshaller(); case MarshallerKind.UnicodeStringBuilder: return new StringBuilderMarshaller(isAnsi: false); case MarshallerKind.AnsiStringBuilder: return new StringBuilderMarshaller(isAnsi: true); case MarshallerKind.VoidReturn: return new VoidReturnMarshaller(); case MarshallerKind.FunctionPointer: return new DelegateMarshaller(); case MarshallerKind.Struct: return new StructMarshaller(); case MarshallerKind.ByValAnsiString: return new ByValAnsiStringMarshaller(); case MarshallerKind.ByValUnicodeString: return new ByValUnicodeStringMarshaller(); case MarshallerKind.ByValAnsiCharArray: case MarshallerKind.ByValArray: return new ByValArrayMarshaller(); case MarshallerKind.AnsiCharArray: return new AnsiCharArrayMarshaller(); default: // ensures we don't throw during create marshaller. We will throw NSE // during EmitIL which will be handled and an Exception method body // will be emitted. return new NotSupportedMarshaller(); } } public bool IsMarshallingRequired() { if (Out) return true; switch (MarshallerKind) { case MarshallerKind.Enum: case MarshallerKind.BlittableValue: case MarshallerKind.BlittableStruct: case MarshallerKind.UnicodeChar: case MarshallerKind.VoidReturn: return false; } return true; } #endregion public virtual void EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams) { _ilCodeStreams = pInvokeILCodeStreams; switch (MarshallerType) { case MarshallerType.Argument: EmitArgumentMarshallingIL(); return; case MarshallerType.Element: EmitElementMarshallingIL(); return; case MarshallerType.Field: EmitFieldMarshallingIL(); return; } } private void EmitArgumentMarshallingIL() { switch (MarshalDirection) { case MarshalDirection.Forward: EmitForwardArgumentMarshallingIL(); return; case MarshalDirection.Reverse: EmitReverseArgumentMarshallingIL(); return; } } private void EmitElementMarshallingIL() { switch (MarshalDirection) { case MarshalDirection.Forward: EmitForwardElementMarshallingIL(); return; case MarshalDirection.Reverse: EmitReverseElementMarshallingIL(); return; } } private void EmitFieldMarshallingIL() { switch (MarshalDirection) { case MarshalDirection.Forward: EmitForwardFieldMarshallingIL(); return; case MarshalDirection.Reverse: EmitReverseFieldMarshallingIL(); return; } } protected virtual void EmitForwardArgumentMarshallingIL() { if (Return) { EmitMarshalReturnValueManagedToNative(); } else { EmitMarshalArgumentManagedToNative(); } } protected virtual void EmitReverseArgumentMarshallingIL() { if (Return) { EmitMarshalReturnValueNativeToManaged(); } else { EmitMarshalArgumentNativeToManaged(); } } protected virtual void EmitForwardElementMarshallingIL() { if (In) EmitMarshalElementManagedToNative(); else EmitMarshalElementNativeToManaged(); } protected virtual void EmitReverseElementMarshallingIL() { if (In) EmitMarshalElementNativeToManaged(); else EmitMarshalElementManagedToNative(); } protected virtual void EmitForwardFieldMarshallingIL() { if (In) EmitMarshalFieldManagedToNative(); else EmitMarshalFieldNativeToManaged(); } protected virtual void EmitReverseFieldMarshallingIL() { if (In) EmitMarshalFieldNativeToManaged(); else EmitMarshalFieldManagedToNative(); } protected virtual void EmitMarshalReturnValueManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; SetupArgumentsForReturnValueMarshalling(); StoreNativeValue(_ilCodeStreams.ReturnValueMarshallingCodeStream); AllocAndTransformNativeToManaged(_ilCodeStreams.ReturnValueMarshallingCodeStream); } public virtual void LoadReturnValue(ILCodeStream codeStream) { Debug.Assert(Return); switch (MarshalDirection) { case MarshalDirection.Forward: LoadManagedValue(codeStream); return; case MarshalDirection.Reverse: LoadNativeValue(codeStream); return; } } protected virtual void SetupArguments() { ILEmitter emitter = _ilCodeStreams.Emitter; if (MarshalDirection == MarshalDirection.Forward) { // Due to StInd order (address, value), we can't do the following: // LoadValue // StoreManagedValue (LdArg + StInd) // The way to work around this is to put it in a local if (IsManagedByRef) _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, false); else _managedHome = new Home(Index - 1, ManagedType, false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } else { _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); if (IsNativeByRef) _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); else _nativeHome = new Home(Index - 1, NativeType, isByRef: false); } } protected virtual void SetupArgumentsForElementMarshalling() { ILEmitter emitter = _ilCodeStreams.Emitter; _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } protected virtual void SetupArgumentsForFieldMarshalling() { ILEmitter emitter = _ilCodeStreams.Emitter; // // these are temporary locals for propagating value // _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } protected virtual void SetupArgumentsForReturnValueMarshalling() { ILEmitter emitter = _ilCodeStreams.Emitter; _managedHome = new Home(emitter.NewLocal(ManagedType), ManagedType, isByRef: false); _nativeHome = new Home(emitter.NewLocal(NativeType), NativeType, isByRef: false); } protected void LoadManagedValue(ILCodeStream stream) { _managedHome.LoadValue(stream); } protected void LoadManagedAddr(ILCodeStream stream) { _managedHome.LoadAddr(stream); } /// <summary> /// Loads the argument to be passed to managed functions /// In by-ref scenarios (ref T), it is &T /// </summary> protected void LoadManagedArg(ILCodeStream stream) { if (IsManagedByRef) _managedHome.LoadAddr(stream); else _managedHome.LoadValue(stream); } protected void StoreManagedValue(ILCodeStream stream) { _managedHome.StoreValue(stream); } protected void LoadNativeValue(ILCodeStream stream) { _nativeHome.LoadValue(stream); } /// <summary> /// Loads the argument to be passed to native functions /// In by-ref scenarios (ref T), it is T* /// </summary> protected void LoadNativeArg(ILCodeStream stream) { if (IsNativeByRef) _nativeHome.LoadAddr(stream); else _nativeHome.LoadValue(stream); } protected void LoadNativeAddr(ILCodeStream stream) { _nativeHome.LoadAddr(stream); } protected void StoreNativeValue(ILCodeStream stream) { _nativeHome.StoreValue(stream); } /// <summary> /// Propagate by-ref arg to corresponding local /// We can't load value + ldarg + ldind in the expected order, so /// we had to use a non-by-ref local and manually propagate the value /// </summary> protected void PropagateFromByRefArg(ILCodeStream stream, Home home) { stream.EmitLdArg(Index - 1); stream.EmitLdInd(ManagedType); home.StoreValue(stream); } /// <summary> /// Propagate local to corresponding by-ref arg /// We can't load value + ldarg + ldind in the expected order, so /// we had to use a non-by-ref local and manually propagate the value /// </summary> protected void PropagateToByRefArg(ILCodeStream stream, Home home) { stream.EmitLdArg(Index - 1); home.LoadValue(stream); stream.EmitStInd(ManagedType); } protected virtual void EmitMarshalArgumentManagedToNative() { SetupArguments(); if (IsManagedByRef && In) { // Propagate byref arg to local PropagateFromByRefArg(_ilCodeStreams.MarshallingCodeStream, _managedHome); } // // marshal // if (IsManagedByRef && !In) { ReInitNativeTransform(_ilCodeStreams.MarshallingCodeStream); } else { AllocAndTransformManagedToNative(_ilCodeStreams.MarshallingCodeStream); } LoadNativeArg(_ilCodeStreams.CallsiteSetupCodeStream); // // unmarshal // if (Out) { if (In) { ClearManagedTransform(_ilCodeStreams.UnmarshallingCodestream); } if (IsManagedByRef && !In) { AllocNativeToManaged(_ilCodeStreams.UnmarshallingCodestream); } TransformNativeToManaged(_ilCodeStreams.UnmarshallingCodestream); if (IsManagedByRef) { // Propagate back to byref arguments PropagateToByRefArg(_ilCodeStreams.UnmarshallingCodestream, _managedHome); } } EmitCleanupManaged(_ilCodeStreams.UnmarshallingCodestream); } /// <summary> /// Reads managed parameter from _vManaged and writes the marshalled parameter in _vNative /// </summary> protected virtual void AllocAndTransformManagedToNative(ILCodeStream codeStream) { AllocManagedToNative(codeStream); if (In) { TransformManagedToNative(codeStream); } } protected virtual void AllocAndTransformNativeToManaged(ILCodeStream codeStream) { AllocNativeToManaged(codeStream); TransformNativeToManaged(codeStream); } protected virtual void AllocManagedToNative(ILCodeStream codeStream) { } protected virtual void TransformManagedToNative(ILCodeStream codeStream) { LoadManagedValue(codeStream); StoreNativeValue(codeStream); } protected virtual void ClearManagedTransform(ILCodeStream codeStream) { } protected virtual void AllocNativeToManaged(ILCodeStream codeStream) { } protected virtual void TransformNativeToManaged(ILCodeStream codeStream) { LoadNativeValue(codeStream); StoreManagedValue(codeStream); } protected virtual void EmitCleanupManaged(ILCodeStream codeStream) { } protected virtual void EmitMarshalReturnValueNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; SetupArgumentsForReturnValueMarshalling(); StoreManagedValue(_ilCodeStreams.ReturnValueMarshallingCodeStream); AllocAndTransformManagedToNative(_ilCodeStreams.ReturnValueMarshallingCodeStream); } protected virtual void EmitMarshalArgumentNativeToManaged() { SetupArguments(); if (IsNativeByRef && In) { // Propagate byref arg to local PropagateFromByRefArg(_ilCodeStreams.MarshallingCodeStream, _nativeHome); } if (IsNativeByRef && !In) { ReInitManagedTransform(_ilCodeStreams.MarshallingCodeStream); } else { AllocAndTransformNativeToManaged(_ilCodeStreams.MarshallingCodeStream); } LoadManagedArg(_ilCodeStreams.CallsiteSetupCodeStream); if (Out) { if (IsNativeByRef) { AllocManagedToNative(_ilCodeStreams.UnmarshallingCodestream); } TransformManagedToNative(_ilCodeStreams.UnmarshallingCodestream); if (IsNativeByRef) { // Propagate back to byref arguments PropagateToByRefArg(_ilCodeStreams.UnmarshallingCodestream, _nativeHome); } } } protected virtual void EmitMarshalElementManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; Debug.Assert(codeStream != null); SetupArgumentsForElementMarshalling(); StoreManagedValue(codeStream); // marshal AllocAndTransformManagedToNative(codeStream); LoadNativeValue(codeStream); } protected virtual void EmitMarshalElementNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; Debug.Assert(codeStream != null); SetupArgumentsForElementMarshalling(); StoreNativeValue(codeStream); // unmarshal AllocAndTransformNativeToManaged(codeStream); LoadManagedValue(codeStream); } protected virtual void EmitMarshalFieldManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; SetupArgumentsForFieldMarshalling(); // // For field marshalling we expect the value of the field is already loaded // in the stack. // StoreManagedValue(marshallingCodeStream); // marshal AllocAndTransformManagedToNative(marshallingCodeStream); LoadNativeValue(marshallingCodeStream); } protected virtual void EmitMarshalFieldNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; SetupArgumentsForFieldMarshalling(); StoreNativeValue(codeStream); // unmarshal AllocAndTransformNativeToManaged(codeStream); LoadManagedValue(codeStream); } protected virtual void ReInitManagedTransform(ILCodeStream codeStream) { } protected virtual void ReInitNativeTransform(ILCodeStream codeStream) { } internal virtual void EmitElementCleanup(ILCodeStream codestream, ILEmitter emitter) { } } class NotSupportedMarshaller : Marshaller { public override void EmitMarshallingIL(PInvokeILCodeStreams pInvokeILCodeStreams) { throw new NotSupportedException(); } } class VoidReturnMarshaller : Marshaller { protected override void EmitMarshalReturnValueManagedToNative() { } protected override void EmitMarshalReturnValueNativeToManaged() { } public override void LoadReturnValue(ILCodeStream codeStream) { Debug.Assert(Return); } } class BlittableValueMarshaller : Marshaller { protected override void EmitMarshalArgumentManagedToNative() { if (IsNativeByRef && MarshalDirection == MarshalDirection.Forward) { ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; ILEmitter emitter = _ilCodeStreams.Emitter; ILLocalVariable native = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); ILLocalVariable vPinnedByRef = emitter.NewLocal(ManagedParameterType, true); marshallingCodeStream.EmitLdArg(Index - 1); marshallingCodeStream.EmitStLoc(vPinnedByRef); marshallingCodeStream.EmitLdLoc(vPinnedByRef); marshallingCodeStream.Emit(ILOpcode.conv_i); marshallingCodeStream.EmitStLoc(native); _ilCodeStreams.CallsiteSetupCodeStream.EmitLdLoc(native); } else { _ilCodeStreams.CallsiteSetupCodeStream.EmitLdArg(Index - 1); } } protected override void EmitMarshalArgumentNativeToManaged() { if (Out) { base.EmitMarshalArgumentNativeToManaged(); } else { _ilCodeStreams.CallsiteSetupCodeStream.EmitLdArg(Index - 1); } } } class BlittableStructPtrMarshaller : Marshaller { protected override void TransformManagedToNative(ILCodeStream codeStream) { if (Out) { // TODO: https://github.com/dotnet/corert/issues/4466 throw new NotSupportedException("Marshalling an LPStruct argument not yet implemented"); } else { LoadManagedAddr(codeStream); StoreNativeValue(codeStream); } } protected override void TransformNativeToManaged(ILCodeStream codeStream) { // TODO: https://github.com/dotnet/corert/issues/4466 throw new NotSupportedException("Marshalling an LPStruct argument not yet implemented"); } } class ArrayMarshaller : Marshaller { private Marshaller _elementMarshaller; protected TypeDesc ManagedElementType { get { Debug.Assert(ManagedType is ArrayType); var arrayType = (ArrayType)ManagedType; return arrayType.ElementType; } } protected TypeDesc NativeElementType { get { Debug.Assert(NativeType is PointerType); return ((PointerType)NativeType).ParameterType; } } protected Marshaller GetElementMarshaller(MarshalDirection direction) { if (_elementMarshaller == null) { _elementMarshaller = CreateMarshaller(ElementMarshallerKind); _elementMarshaller.MarshallerKind = ElementMarshallerKind; _elementMarshaller.MarshallerType = MarshallerType.Element; _elementMarshaller.InteropStateManager = InteropStateManager; _elementMarshaller.Return = Return; _elementMarshaller.Context = Context; _elementMarshaller.ManagedType = ManagedElementType; _elementMarshaller.MarshalAsDescriptor = MarshalAsDescriptor; _elementMarshaller.PInvokeFlags = PInvokeFlags; } _elementMarshaller.In = (direction == MarshalDirection); _elementMarshaller.Out = !In; _elementMarshaller.MarshalDirection = MarshalDirection; return _elementMarshaller; } protected virtual void EmitElementCount(ILCodeStream codeStream, MarshalDirection direction) { if (direction == MarshalDirection.Forward) { // In forward direction we skip whatever is passed through SizeParamIndex, because the // size of the managed array is already known LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.ldlen); codeStream.Emit(ILOpcode.conv_i4); } else if (MarshalDirection == MarshalDirection.Forward && MarshallerType == MarshallerType.Argument && !Return && !IsManagedByRef) { EmitElementCount(codeStream, MarshalDirection.Forward); } else { uint? sizeParamIndex = MarshalAsDescriptor != null ? MarshalAsDescriptor.SizeParamIndex : null; uint? sizeConst = MarshalAsDescriptor != null ? MarshalAsDescriptor.SizeConst : null; if (sizeConst.HasValue) { codeStream.EmitLdc((int)sizeConst.Value); } if (sizeParamIndex.HasValue) { uint index = sizeParamIndex.Value; if (index < 0 || index >= Marshallers.Length - 1) { throw new InvalidProgramException("Invalid SizeParamIndex, must be between 0 and parameter count"); } //zero-th index is for return type index++; var indexType = Marshallers[index].ManagedType; switch (indexType.Category) { case TypeFlags.Byte: case TypeFlags.SByte: case TypeFlags.Int16: case TypeFlags.UInt16: case TypeFlags.Int32: case TypeFlags.UInt32: case TypeFlags.Int64: case TypeFlags.UInt64: break; default: throw new InvalidProgramException("Invalid SizeParamIndex, parameter must be of type int/uint"); } // @TODO - We can use LoadManagedValue, but that requires byref arg propagation happen in a special setup stream // otherwise there is an ordering issue codeStream.EmitLdArg(Marshallers[index].Index - 1); if (Marshallers[index].IsManagedByRef) codeStream.EmitLdInd(indexType); if (sizeConst.HasValue) codeStream.Emit(ILOpcode.add); } if (!sizeConst.HasValue && !sizeParamIndex.HasValue) { // if neither sizeConst or sizeParamIndex are specified, default to 1 codeStream.EmitLdc(1); } } } protected override void AllocManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeLabel lNullArray = emitter.NewCodeLabel(); LoadNativeAddr(codeStream); codeStream.Emit(ILOpcode.initobj, emitter.NewToken(NativeType)); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); // allocate memory // nativeParameter = (byte**)CoTaskMemAllocAndZeroMemory((IntPtr)(checked(managedParameter.Length * sizeof(byte*)))); // loads the number of elements EmitElementCount(codeStream, MarshalDirection.Forward); TypeDesc nativeElementType = NativeElementType; codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.Emit(ILOpcode.mul_ovf); codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemAllocAndZeroMemory"))); StoreNativeValue(codeStream); codeStream.EmitLabel(lNullArray); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var elementType = ManagedElementType; var lRangeCheck = emitter.NewCodeLabel(); var lLoopHeader = emitter.NewCodeLabel(); var lNullArray = emitter.NewCodeLabel(); var vNativeTemp = emitter.NewLocal(NativeType); var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); var vSizeOf = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); var vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); // loads the number of elements EmitElementCount(codeStream, MarshalDirection.Forward); codeStream.EmitStLoc(vLength); TypeDesc nativeElementType = NativeElementType; codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.EmitStLoc(vSizeOf); LoadNativeValue(codeStream); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); codeStream.EmitLdLoc(vNativeTemp); LoadManagedValue(codeStream); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdElem(elementType); // generate marshalling IL for the element GetElementMarshaller(MarshalDirection.Forward) .EmitMarshallingIL(new PInvokeILCodeStreams(_ilCodeStreams.Emitter, codeStream)); codeStream.EmitStInd(nativeElementType); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdLoc(vSizeOf); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); codeStream.EmitLabel(lNullArray); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var elementType = ManagedElementType; var nativeElementType = NativeElementType; ILLocalVariable vSizeOf = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); ILCodeLabel lRangeCheck = emitter.NewCodeLabel(); ILCodeLabel lLoopHeader = emitter.NewCodeLabel(); var lNullArray = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.EmitStLoc(vLength); codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.EmitStLoc(vSizeOf); var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vNativeTemp = emitter.NewLocal(NativeType); LoadNativeValue(codeStream); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); LoadManagedValue(codeStream); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdInd(nativeElementType); // generate marshalling IL for the element GetElementMarshaller(MarshalDirection.Reverse) .EmitMarshallingIL(new PInvokeILCodeStreams(_ilCodeStreams.Emitter, codeStream)); codeStream.EmitStElem(elementType); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdLoc(vSizeOf); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); codeStream.EmitLabel(lNullArray); } protected override void AllocNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var elementType = ManagedElementType; EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.Emit(ILOpcode.newarr, emitter.NewToken(elementType)); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { Marshaller elementMarshaller = GetElementMarshaller(MarshalDirection.Forward); ILEmitter emitter = _ilCodeStreams.Emitter; var lNullArray = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); // generate cleanup code only if it is necessary if (elementMarshaller.CleanupRequired) { // // for (index=0; index< array.length; index++) // Cleanup(array[i]); // var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); ILCodeLabel lRangeCheck = emitter.NewCodeLabel(); ILCodeLabel lLoopHeader = emitter.NewCodeLabel(); ILLocalVariable vSizeOf = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); var nativeElementType = NativeElementType; // calculate sizeof(array[i]) codeStream.Emit(ILOpcode.sizeof_, emitter.NewToken(nativeElementType)); codeStream.EmitStLoc(vSizeOf); // calculate array.length EmitElementCount(codeStream, MarshalDirection.Forward); codeStream.EmitStLoc(vLength); // load native value ILLocalVariable vNativeTemp = emitter.NewLocal(NativeType); LoadNativeValue(codeStream); codeStream.EmitStLoc(vNativeTemp); // index = 0 codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdInd(nativeElementType); // generate cleanup code for this element elementMarshaller.EmitElementCleanup(codeStream, emitter); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLdLoc(vNativeTemp); codeStream.EmitLdLoc(vSizeOf); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vNativeTemp); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); } LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); codeStream.EmitLabel(lNullArray); } } class BlittableArrayMarshaller : ArrayMarshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var arrayType = (ArrayType)ManagedType; Debug.Assert(arrayType.IsSzArray); ILLocalVariable vPinnedFirstElement = emitter.NewLocal(arrayType.ParameterType.MakeByRefType(), true); ILCodeLabel lNullArray = emitter.NewCodeLabel(); // Check for null array, or 0 element array. LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullArray); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.ldlen); codeStream.Emit(ILOpcode.conv_i4); codeStream.Emit(ILOpcode.brfalse, lNullArray); // Array has elements. LoadManagedValue(codeStream); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ldelema, emitter.NewToken(arrayType.ElementType)); codeStream.EmitStLoc(vPinnedFirstElement); // Fall through. If array didn't have elements, vPinnedFirstElement is zeroinit. codeStream.EmitLabel(lNullArray); codeStream.EmitLdLoc(vPinnedFirstElement); codeStream.Emit(ILOpcode.conv_i); StoreNativeValue(codeStream); } protected override void ReInitNativeTransform(ILCodeStream codeStream) { codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_u); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { if (IsManagedByRef && !In) base.TransformNativeToManaged(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { if (IsManagedByRef && !In) base.EmitCleanupManaged(codeStream); } } class AnsiCharArrayMarshaller : ArrayMarshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var helper = Context.GetHelperEntryPoint("InteropHelpers", "AllocMemoryForAnsiCharArray"); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreNativeValue(codeStream); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var helper = Context.GetHelperEntryPoint("InteropHelpers", "WideCharArrayToAnsiCharArray"); LoadManagedValue(codeStream); LoadNativeValue(codeStream); codeStream.Emit(PInvokeFlags.BestFitMapping ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(PInvokeFlags.ThrowOnUnmappableChar ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var helper = Context.GetHelperEntryPoint("InteropHelpers", "AnsiCharArrayToWideCharArray"); LoadNativeValue(codeStream); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); } } class AnsiCharMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var helper = Context.GetHelperEntryPoint("InteropHelpers", "WideCharToAnsiChar"); LoadManagedValue(codeStream); codeStream.Emit(PInvokeFlags.BestFitMapping ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(PInvokeFlags.ThrowOnUnmappableChar ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var helper = Context.GetHelperEntryPoint("InteropHelpers", "AnsiCharToWideChar"); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreNativeValue(codeStream); } } class BooleanMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { LoadManagedValue(codeStream); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); StoreNativeValue(codeStream); } protected override void AllocAndTransformNativeToManaged(ILCodeStream codeStream) { LoadNativeValue(codeStream); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.ceq); StoreManagedValue(codeStream); } } class UnicodeStringMarshaller : Marshaller { private bool ShouldBePinned { get { return MarshalDirection == MarshalDirection.Forward && MarshallerType != MarshallerType.Field && !IsManagedByRef && In && !Out; } } internal override bool CleanupRequired { get { return !ShouldBePinned; //cleanup is only required when it is not pinned } } internal override void EmitElementCleanup(ILCodeStream codeStream, ILEmitter emitter) { codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); } protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; if (ShouldBePinned) { // // Pin the string and push a pointer to the first character on the stack. // TypeDesc stringType = Context.GetWellKnownType(WellKnownType.String); ILLocalVariable vPinnedString = emitter.NewLocal(stringType, true); ILCodeLabel lNullString = emitter.NewCodeLabel(); LoadManagedValue(codeStream); codeStream.EmitStLoc(vPinnedString); codeStream.EmitLdLoc(vPinnedString); codeStream.Emit(ILOpcode.conv_i); codeStream.Emit(ILOpcode.dup); // Marshalling a null string? codeStream.Emit(ILOpcode.brfalse, lNullString); codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.SystemModule. GetKnownType("System.Runtime.CompilerServices", "RuntimeHelpers"). GetKnownMethod("get_OffsetToStringData", null))); codeStream.Emit(ILOpcode.add); codeStream.EmitLabel(lNullString); StoreNativeValue(codeStream); } else { var helper = Context.GetHelperEntryPoint("InteropHelpers", "StringToUnicodeBuffer"); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreNativeValue(codeStream); } } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var helper = Context.GetHelperEntryPoint("InteropHelpers", "UnicodeBufferToString"); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { if (CleanupRequired) { var emitter = _ilCodeStreams.Emitter; var lNullCheck = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullCheck); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); codeStream.EmitLabel(lNullCheck); } } } class AnsiStringMarshaller : Marshaller { internal override bool CleanupRequired { get { return true; } } internal override void EmitElementCleanup(ILCodeStream codeStream, ILEmitter emitter) { codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); } protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; // // ANSI marshalling. Allocate a byte array, copy characters // var stringToAnsi = Context.GetHelperEntryPoint("InteropHelpers", "StringToAnsiString"); LoadManagedValue(codeStream); codeStream.Emit(PInvokeFlags.BestFitMapping ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(PInvokeFlags.ThrowOnUnmappableChar ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(ILOpcode.call, emitter.NewToken(stringToAnsi)); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; var ansiToString = Context.GetHelperEntryPoint("InteropHelpers", "AnsiStringToString"); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(ansiToString)); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { var emitter = _ilCodeStreams.Emitter; var lNullCheck = emitter.NewCodeLabel(); // Check for null array LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNullCheck); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); codeStream.EmitLabel(lNullCheck); } } class SafeHandleMarshaller : ReferenceMarshaller { protected override void AllocNativeToManaged(ILCodeStream codeStream) { var ctor = ManagedType.GetParameterlessConstructor(); if (ctor == null) { var emitter = _ilCodeStreams.Emitter; MethodSignature ctorSignature = new MethodSignature(0, 0, Context.GetWellKnownType(WellKnownType.Void), new TypeDesc[] { Context.GetWellKnownType(WellKnownType.String) }); MethodDesc exceptionCtor = InteropTypes.GetMissingMemberException(Context).GetKnownMethod(".ctor", ctorSignature); string name = ((MetadataType)ManagedType).Name; codeStream.Emit(ILOpcode.ldstr, emitter.NewToken(String.Format("'{0}' does not have a default constructor. Subclasses of SafeHandle must have a default constructor to support marshaling a Windows HANDLE into managed code.", name))); codeStream.Emit(ILOpcode.newobj, emitter.NewToken(exceptionCtor)); codeStream.Emit(ILOpcode.throw_); } else { base.AllocNativeToManaged(codeStream); } } protected override void EmitMarshalArgumentManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream marshallingCodeStream = _ilCodeStreams.MarshallingCodeStream; ILCodeStream callsiteCodeStream = _ilCodeStreams.CallsiteSetupCodeStream; ILCodeStream unmarshallingCodeStream = _ilCodeStreams.UnmarshallingCodestream; SetupArguments(); if (IsManagedByRef && In) { PropagateFromByRefArg(marshallingCodeStream, _managedHome); } // TODO: https://github.com/dotnet/corert/issues/3291 // We don't support [IN,OUT] together yet, either IN or OUT. if (Out && In) { throw new NotSupportedException("Marshalling an argument as both in and out not yet implemented"); } var safeHandleType = InteropTypes.GetSafeHandle(Context); if (Out && IsManagedByRef) { // 1) If this is an output parameter we need to preallocate a SafeHandle to wrap the new native handle value. We // must allocate this before the native call to avoid a failure point when we already have a native resource // allocated. We must allocate a new SafeHandle even if we have one on input since both input and output native // handles need to be tracked and released by a SafeHandle. // 2) Initialize a local IntPtr that will be passed to the native call. // 3) After the native call, the new handle value is written into the output SafeHandle and that SafeHandle // is propagated back to the caller. var vOutValue = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); var vSafeHandle = emitter.NewLocal(ManagedType); marshallingCodeStream.Emit(ILOpcode.newobj, emitter.NewToken(ManagedType.GetParameterlessConstructor())); marshallingCodeStream.EmitStLoc(vSafeHandle); _ilCodeStreams.CallsiteSetupCodeStream.EmitLdLoca(vOutValue); unmarshallingCodeStream.EmitLdLoc(vSafeHandle); unmarshallingCodeStream.EmitLdLoc(vOutValue); unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("SetHandle", null))); unmarshallingCodeStream.EmitLdLoc(vSafeHandle); StoreManagedValue(unmarshallingCodeStream); PropagateToByRefArg(unmarshallingCodeStream, _managedHome); } else { var vAddRefed = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); LoadManagedValue(marshallingCodeStream); marshallingCodeStream.EmitLdLoca(vAddRefed); marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousAddRef", null))); LoadManagedValue(marshallingCodeStream); marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousGetHandle", null))); StoreNativeValue(marshallingCodeStream); // TODO: This should be inside finally block and only executed it the handle was addrefed LoadManagedValue(unmarshallingCodeStream); unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( safeHandleType.GetKnownMethod("DangerousRelease", null))); LoadNativeArg(_ilCodeStreams.CallsiteSetupCodeStream); } } protected override void TransformNativeToManaged(ILCodeStream codeStream) { LoadManagedValue(codeStream); LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropTypes.GetSafeHandle(Context).GetKnownMethod("SetHandle", null))); } } class ReferenceMarshaller : Marshaller { protected override void AllocNativeToManaged(ILCodeStream codeStream) { var emitter = _ilCodeStreams.Emitter; var lNull = emitter.NewCodeLabel(); // Check for null LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.brfalse, lNull); codeStream.Emit(ILOpcode.newobj, emitter.NewToken( ManagedType.GetParameterlessConstructor())); StoreManagedValue(codeStream); codeStream.EmitLabel(lNull); } } class StringBuilderMarshaller : ReferenceMarshaller { private bool _isAnsi; public StringBuilderMarshaller(bool isAnsi) { _isAnsi = isAnsi; } internal override bool CleanupRequired { get { return true; } } internal override void EmitElementCleanup(ILCodeStream codeStream, ILEmitter emitter) { codeStream.Emit(ILOpcode.call, emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); } protected override void AllocManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; string helperMethodName = _isAnsi ? "AllocMemoryForAnsiStringBuilder" : "AllocMemoryForUnicodeStringBuilder"; var helper = Context.GetHelperEntryPoint("InteropHelpers", helperMethodName); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); StoreNativeValue(codeStream); } protected override void TransformManagedToNative(ILCodeStream codeStream) { ILEmitter emitter = _ilCodeStreams.Emitter; string helperMethodName = _isAnsi ? "StringBuilderToAnsiString" : "StringBuilderToUnicodeString"; var helper = Context.GetHelperEntryPoint("InteropHelpers", helperMethodName); LoadManagedValue(codeStream); LoadNativeValue(codeStream); if (_isAnsi) { codeStream.Emit(PInvokeFlags.BestFitMapping ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(PInvokeFlags.ThrowOnUnmappableChar ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); } codeStream.Emit(ILOpcode.call, emitter.NewToken(helper)); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { string helperMethodName = _isAnsi ? "AnsiStringToStringBuilder" : "UnicodeStringToStringBuilder"; var helper = Context.GetHelperEntryPoint("InteropHelpers", helperMethodName); LoadNativeValue(codeStream); LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken(helper)); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "CoTaskMemFree"))); } } class DelegateMarshaller : Marshaller { protected override void AllocAndTransformManagedToNative(ILCodeStream codeStream) { LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "GetFunctionPointerForDelegate"))); StoreNativeValue(codeStream); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { LoadNativeValue(codeStream); codeStream.Emit(ILOpcode.ldtoken, _ilCodeStreams.Emitter.NewToken(ManagedType)); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( Context.GetHelperEntryPoint("InteropHelpers", "GetDelegateForFunctionPointer"))); StoreManagedValue(codeStream); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { if (In && MarshalDirection == MarshalDirection.Forward && MarshallerType == MarshallerType.Argument) { LoadManagedValue(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken(InteropTypes.GetGC(Context).GetKnownMethod("KeepAlive", null))); } } } class StructMarshaller : Marshaller { protected override void AllocManagedToNative(ILCodeStream codeStream) { LoadNativeAddr(codeStream); codeStream.Emit(ILOpcode.initobj, _ilCodeStreams.Emitter.NewToken(NativeType)); } protected override void TransformManagedToNative(ILCodeStream codeStream) { LoadManagedAddr(codeStream); LoadNativeAddr(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropStateManager.GetStructMarshallingManagedToNativeThunk(ManagedType))); } protected override void TransformNativeToManaged(ILCodeStream codeStream) { LoadManagedAddr(codeStream); LoadNativeAddr(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropStateManager.GetStructMarshallingNativeToManagedThunk(ManagedType))); } protected override void EmitCleanupManaged(ILCodeStream codeStream) { // Only do cleanup if it is IN if (!In) { return; } LoadNativeAddr(codeStream); codeStream.Emit(ILOpcode.call, _ilCodeStreams.Emitter.NewToken( InteropStateManager.GetStructMarshallingCleanupThunk(ManagedType))); } } class ByValArrayMarshaller : ArrayMarshaller { protected FieldDesc _managedField; protected FieldDesc _nativeField; public void EmitMarshallingIL(PInvokeILCodeStreams codeStreams, FieldDesc managedField, FieldDesc nativeField) { _managedField = managedField; _nativeField = nativeField; EmitMarshallingIL(codeStreams); } protected override void EmitElementCount(ILCodeStream codeStream, MarshalDirection direction) { ILEmitter emitter = _ilCodeStreams.Emitter; if (MarshalAsDescriptor == null || !MarshalAsDescriptor.SizeConst.HasValue) { throw new InvalidProgramException("SizeConst is required for ByValArray."); } if (direction == MarshalDirection.Forward) { // In forward direction ElementCount = Min(managed.length, SizeConst); var vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); var lSmaller = emitter.NewCodeLabel(); var lDone = emitter.NewCodeLabel(); codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); var lNullCheck = emitter.NewCodeLabel(); codeStream.Emit(ILOpcode.brfalse, lNullCheck); codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); codeStream.Emit(ILOpcode.ldlen); codeStream.Emit(ILOpcode.conv_i4); codeStream.EmitStLoc(vLength); codeStream.EmitLabel(lNullCheck); Debug.Assert(MarshalAsDescriptor.SizeConst.HasValue); int sizeConst = (int)MarshalAsDescriptor.SizeConst.Value; codeStream.EmitLdc(sizeConst); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lSmaller); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.br, lDone); codeStream.EmitLabel(lSmaller); codeStream.EmitLdc(sizeConst); codeStream.EmitLabel(lDone); } else { // In reverse direction ElementCount = SizeConst; Debug.Assert(MarshalAsDescriptor.SizeConst.HasValue); int sizeConst = (int)MarshalAsDescriptor.SizeConst.Value; codeStream.EmitLdc(sizeConst); } } protected override void EmitMarshalFieldManagedToNative() { // It generates the following code //if (ManagedArg.Field != null) //{ // // fixed (InlineArray* pUnsafe = &NativeArg.Field) // { // uint index = 0u; // while ((ulong)index < (ulong)((long)ManagedArg.Field.Length)) // { // NativeArg.s[index] = ManagedArg.Field[(int)index]; // index += 1u; // } // } //} ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; var nativeArrayType = NativeType as InlineArrayType; Debug.Assert(nativeArrayType != null); Debug.Assert(ManagedType is ArrayType); var managedElementType = ((ArrayType)ManagedType).ElementType; ILCodeLabel lDone = emitter.NewCodeLabel(); ILCodeLabel lRangeCheck = emitter.NewCodeLabel(); ILCodeLabel lLoopHeader = emitter.NewCodeLabel(); ILLocalVariable vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable vNative = emitter.NewLocal(NativeType.MakeByRefType(), isPinned: true); // check if ManagedType == null, then return codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); codeStream.Emit(ILOpcode.brfalse, lDone); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.EmitStLoc(vNative); EmitElementCount(codeStream, MarshalDirection.Forward); codeStream.EmitStLoc(vLength); codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdElem(managedElementType); // generate marshalling IL for the element GetElementMarshaller(MarshalDirection.Forward) .EmitMarshallingIL(new PInvokeILCodeStreams(_ilCodeStreams.Emitter, codeStream)); codeStream.Emit(ILOpcode.call, emitter.NewToken( nativeArrayType.GetInlineArrayMethod(InlineArrayMethodKind.Setter))); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); codeStream.EmitLabel(lDone); } protected override void EmitMarshalFieldNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.UnmarshallingCodestream; // It generates the following IL: // ManagedArg.s = new ElementType[Length]; // // for (uint index = 0u; index < Length; index += 1u) // { // ManagedArg.s[index] = NativeArg.s[index]; // } // ILCodeLabel lRangeCheck = emitter.NewCodeLabel(); ILCodeLabel lLoopHeader = emitter.NewCodeLabel(); Debug.Assert(ManagedType is ArrayType); var nativeArrayType = NativeType as InlineArrayType; Debug.Assert(nativeArrayType != null); var managedElementType = ((ArrayType)ManagedType).ElementType; ILLocalVariable vLength = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); codeStream.EmitLdArg(0); // load the length EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.EmitStLoc(vLength); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.newarr, emitter.NewToken(managedElementType)); codeStream.Emit(ILOpcode.stfld, emitter.NewToken(_managedField)); var vIndex = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); // index = 0 codeStream.EmitLdc(0); codeStream.EmitStLoc(vIndex); codeStream.Emit(ILOpcode.br, lRangeCheck); codeStream.EmitLabel(lLoopHeader); // load managed type codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); codeStream.EmitLdLoc(vIndex); // load native type codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.EmitLdLoc(vIndex); codeStream.Emit(ILOpcode.call, emitter.NewToken( nativeArrayType.GetInlineArrayMethod(InlineArrayMethodKind.Getter))); // generate marshalling IL for the element GetElementMarshaller(MarshalDirection.Reverse) .EmitMarshallingIL(new PInvokeILCodeStreams(_ilCodeStreams.Emitter, codeStream)); codeStream.EmitStElem(managedElementType); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(vIndex); codeStream.EmitLabel(lRangeCheck); codeStream.EmitLdLoc(vIndex); codeStream.EmitLdLoc(vLength); codeStream.Emit(ILOpcode.blt, lLoopHeader); } } abstract class ByValStringMarshaller : ByValArrayMarshaller { protected virtual bool IsAnsi { get; } protected virtual MethodDesc GetManagedToNativeHelper() { return null; } protected virtual MethodDesc GetNativeToManagedHelper() { return null; } protected override void EmitMarshalFieldManagedToNative() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.MarshallingCodeStream; var nativeArrayType = NativeType as InlineArrayType; Debug.Assert(nativeArrayType != null); codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(_managedField)); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.Emit(ILOpcode.conv_u); EmitElementCount(codeStream, MarshalDirection.Forward); if (IsAnsi) { codeStream.Emit(PInvokeFlags.BestFitMapping ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); codeStream.Emit(PInvokeFlags.ThrowOnUnmappableChar ? ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0); } codeStream.Emit(ILOpcode.call, emitter.NewToken(GetManagedToNativeHelper())); } protected override void EmitMarshalFieldNativeToManaged() { ILEmitter emitter = _ilCodeStreams.Emitter; ILCodeStream codeStream = _ilCodeStreams.UnmarshallingCodestream; codeStream.EmitLdArg(0); codeStream.EmitLdArg(1); codeStream.Emit(ILOpcode.ldflda, emitter.NewToken(_nativeField)); codeStream.Emit(ILOpcode.conv_u); EmitElementCount(codeStream, MarshalDirection.Reverse); codeStream.Emit(ILOpcode.call, emitter.NewToken(GetNativeToManagedHelper())); codeStream.Emit(ILOpcode.stfld, emitter.NewToken(_managedField)); } } class ByValAnsiStringMarshaller : ByValStringMarshaller { protected override bool IsAnsi { get { return true; } } protected override MethodDesc GetManagedToNativeHelper() { return Context.GetHelperEntryPoint("InteropHelpers", "StringToByValAnsiString"); } protected override MethodDesc GetNativeToManagedHelper() { return Context.GetHelperEntryPoint("InteropHelpers", "ByValAnsiStringToString"); } } class ByValUnicodeStringMarshaller : ByValStringMarshaller { protected override bool IsAnsi { get { return false; } } protected override MethodDesc GetManagedToNativeHelper() { return Context.GetHelperEntryPoint("InteropHelpers", "StringToUnicodeFixedArray"); } protected override MethodDesc GetNativeToManagedHelper() { return Context.GetHelperEntryPoint("InteropHelpers", "UnicodeToStringFixedArray"); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Runtime.Serialization; using TrackableEntities; using TrackableEntities.Client; namespace AIM.Client.Entities.Models { [JsonObject(IsReference = true)] [DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")] public partial class User : ModelBase<User>, IEquatable<User>, ITrackable { [DataMember] public int UserId { get { return _userId; } set { if (Equals(value, _userId)) return; _userId = value; NotifyPropertyChanged(m => m.UserId); } } private int _userId; [DataMember] public string FirstName { get { return _firstName; } set { if (Equals(value, _firstName)) return; _firstName = value; NotifyPropertyChanged(m => m.FirstName); } } private string _firstName; [DataMember] public string MiddleName { get { return _middleName; } set { if (Equals(value, _middleName)) return; _middleName = value; NotifyPropertyChanged(m => m.MiddleName); } } private string _middleName; [DataMember] public string LastName { get { return _lastName; } set { if (Equals(value, _lastName)) return; _lastName = value; NotifyPropertyChanged(m => m.LastName); } } private string _lastName; [DataMember] public string Email { get { return _email; } set { if (Equals(value, _email)) return; _email = value; NotifyPropertyChanged(m => m.Email); } } private string _email; [DataMember] public string SocialSecurityNumber { get { return _socialSecurityNumber; } set { if (Equals(value, _socialSecurityNumber)) return; _socialSecurityNumber = value; NotifyPropertyChanged(m => m.SocialSecurityNumber); } } private string _socialSecurityNumber; [DataMember] public int? PersonalInfoId { get { return _personalInfoId; } set { if (Equals(value, _personalInfoId)) return; _personalInfoId = value; NotifyPropertyChanged(m => m.PersonalInfoId); } } private int? _personalInfoId; [DataMember] public int? ApplicantId { get { return _applicantId; } set { if (Equals(value, _applicantId)) return; _applicantId = value; NotifyPropertyChanged(m => m.ApplicantId); } } private int? _applicantId; [DataMember] public int? ApplicationId { get { return _applicationId; } set { if (Equals(value, _applicationId)) return; _applicationId = value; NotifyPropertyChanged(m => m.ApplicationId); } } private int? _applicationId; [DataMember] public int? EmployeeId { get { return _employeeId; } set { if (Equals(value, _employeeId)) return; _employeeId = value; NotifyPropertyChanged(m => m.EmployeeId); } } private int? _employeeId; [DataMember] public string UserName { get { return _userName; } set { if (Equals(value, _userName)) return; _userName = value; NotifyPropertyChanged(m => m.UserName); } } private string _userName; [DataMember] public string Password { get { return _password; } set { if (Equals(value, _password)) return; _password = value; NotifyPropertyChanged(m => m.Password); } } private string _password; [DataMember] public string AspNetUsersId { get { return _aspNetUsersId; } set { if (Equals(value, _aspNetUsersId)) return; _aspNetUsersId = value; NotifyPropertyChanged(m => m.AspNetUsersId); } } private string _aspNetUsersId; [DataMember] public Applicant Applicant { get { return _applicant; } set { if (Equals(value, _applicant)) return; _applicant = value; ApplicantChangeTracker = _applicant == null ? null : new ChangeTrackingCollection<Applicant> { _applicant }; NotifyPropertyChanged(m => m.Applicant); } } private Applicant _applicant; private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; } [DataMember] public AspNetUser AspNetUser { get { return _aspNetUser; } set { if (Equals(value, _aspNetUser)) return; _aspNetUser = value; AspNetUserChangeTracker = _aspNetUser == null ? null : new ChangeTrackingCollection<AspNetUser> { _aspNetUser }; NotifyPropertyChanged(m => m.AspNetUser); } } private AspNetUser _aspNetUser; private ChangeTrackingCollection<AspNetUser> AspNetUserChangeTracker { get; set; } [DataMember] public Employee Employee { get { return _employee; } set { if (Equals(value, _employee)) return; _employee = value; EmployeeChangeTracker = _employee == null ? null : new ChangeTrackingCollection<Employee> { _employee }; NotifyPropertyChanged(m => m.Employee); } } private Employee _employee; private ChangeTrackingCollection<Employee> EmployeeChangeTracker { get; set; } [DataMember] public PersonalInfo PersonalInfo { get { return _personalInfo; } set { if (Equals(value, _personalInfo)) return; _personalInfo = value; PersonalInfoChangeTracker = _personalInfo == null ? null : new ChangeTrackingCollection<PersonalInfo> { _personalInfo }; NotifyPropertyChanged(m => m.PersonalInfo); } } private PersonalInfo _personalInfo; private ChangeTrackingCollection<PersonalInfo> PersonalInfoChangeTracker { get; set; } #region Change Tracking [DataMember] public TrackingState TrackingState { get; set; } [DataMember] public ICollection<string> ModifiedProperties { get; set; } [JsonProperty, DataMember] private Guid EntityIdentifier { get; set; } #pragma warning disable 414 [JsonProperty, DataMember] private Guid _entityIdentity = default(Guid); #pragma warning restore 414 bool IEquatable<User>.Equals(User other) { if (EntityIdentifier != default(Guid)) return EntityIdentifier == other.EntityIdentifier; return false; } #endregion Change Tracking } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System.Collections.Generic; using UnityEditor; using UnityEditor.FacebookEditor; using UnityEngine; [CustomEditor(typeof(FacebookSettings))] public class FacebookSettingsEditor : UnityEditor.Editor { private bool showFacebookInitSettings = false; private bool showAndroidUtils = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android; private bool showIOSSettings = EditorUserBuildSettings.activeBuildTarget.ToString() == "iOS"; private bool showAppLinksSettings = false; private bool showAboutSection = false; private GUIContent appNameLabel = new GUIContent("App Name [?]:", "For your own use and organization.\n(ex. 'dev', 'qa', 'prod')"); private GUIContent appIdLabel = new GUIContent("App Id [?]:", "Facebook App Ids can be found at https://developers.facebook.com/apps"); private GUIContent urlSuffixLabel = new GUIContent("URL Scheme Suffix [?]", "Use this to share Facebook APP ID's across multiple iOS apps. https://developers.facebook.com/docs/ios/share-appid-across-multiple-apps-ios-sdk/"); private GUIContent cookieLabel = new GUIContent("Cookie [?]", "Sets a cookie which your server-side code can use to validate a user's Facebook session"); private GUIContent loggingLabel = new GUIContent("Logging [?]", "(Web Player only) If true, outputs a verbose log to the Javascript console to facilitate debugging."); private GUIContent statusLabel = new GUIContent("Status [?]", "If 'true', attempts to initialize the Facebook object with valid session data."); private GUIContent xfbmlLabel = new GUIContent("Xfbml [?]", "(Web Player only If true) Facebook will immediately parse any XFBML elements on the Facebook Canvas page hosting the app"); private GUIContent frictionlessLabel = new GUIContent("Frictionless Requests [?]", "Use frictionless app requests, as described in their own documentation."); private GUIContent packageNameLabel = new GUIContent("Package Name [?]", "aka: the bundle identifier"); private GUIContent classNameLabel = new GUIContent("Class Name [?]", "aka: the activity name"); private GUIContent debugAndroidKeyLabel = new GUIContent("Debug Android Key Hash [?]", "Copy this key to the Facebook Settings in order to test a Facebook Android app"); private GUIContent sdkVersion = new GUIContent("SDK Version [?]", "This Unity Facebook SDK version. If you have problems or compliments please include this so we know exactly what version to look out for."); public override void OnInspectorGUI() { EditorGUILayout.Separator(); this.AppIdGUI(); EditorGUILayout.Separator(); this.FBParamsInitGUI(); EditorGUILayout.Separator(); this.AndroidUtilGUI(); EditorGUILayout.Separator(); this.IOSUtilGUI(); EditorGUILayout.Separator(); this.AppLinksUtilGUI(); EditorGUILayout.Separator(); this.AboutGUI(); EditorGUILayout.Separator(); this.BuildGUI(); } private void AppIdGUI() { EditorGUILayout.LabelField("Add the Facebook App Id(s) associated with this game"); if (FacebookSettings.AppIds.Count == 0 || FacebookSettings.AppId == "0") { EditorGUILayout.HelpBox("Invalid App Id", MessageType.Error); } EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.appNameLabel); EditorGUILayout.LabelField(this.appIdLabel); EditorGUILayout.EndHorizontal(); for (int i = 0; i < FacebookSettings.AppIds.Count; ++i) { EditorGUILayout.BeginHorizontal(); FacebookSettings.AppLabels[i] = EditorGUILayout.TextField(FacebookSettings.AppLabels[i]); GUI.changed = false; FacebookSettings.AppIds[i] = EditorGUILayout.TextField(FacebookSettings.AppIds[i]); if (GUI.changed) { FacebookSettings.SettingsChanged(); ManifestMod.GenerateManifest(); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add Another App Id")) { FacebookSettings.AppLabels.Add("New App"); FacebookSettings.AppIds.Add("0"); FacebookSettings.AppLinkSchemes.Add(new FacebookSettings.UrlSchemes()); FacebookSettings.SettingsChanged(); } if (FacebookSettings.AppLabels.Count > 1) { if (GUILayout.Button("Remove Last App Id")) { FacebookSettings.AppLabels.Pop(); FacebookSettings.AppIds.Pop(); FacebookSettings.AppLinkSchemes.Pop(); FacebookSettings.SettingsChanged(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (FacebookSettings.AppIds.Count > 1) { EditorGUILayout.HelpBox("2) Select Facebook App Id to be compiled with this game", MessageType.None); GUI.changed = false; FacebookSettings.SelectedAppIndex = EditorGUILayout.Popup( "Selected App Id", FacebookSettings.SelectedAppIndex, FacebookSettings.AppIds.ToArray()); if (GUI.changed) { ManifestMod.GenerateManifest(); } EditorGUILayout.Space(); } else { FacebookSettings.SelectedAppIndex = 0; } } private void FBParamsInitGUI() { this.showFacebookInitSettings = EditorGUILayout.Foldout(this.showFacebookInitSettings, "FB.Init() Parameters"); if (this.showFacebookInitSettings) { FacebookSettings.Cookie = EditorGUILayout.Toggle(this.cookieLabel, FacebookSettings.Cookie); FacebookSettings.Logging = EditorGUILayout.Toggle(this.loggingLabel, FacebookSettings.Logging); FacebookSettings.Status = EditorGUILayout.Toggle(this.statusLabel, FacebookSettings.Status); FacebookSettings.Xfbml = EditorGUILayout.Toggle(this.xfbmlLabel, FacebookSettings.Xfbml); FacebookSettings.FrictionlessRequests = EditorGUILayout.Toggle(this.frictionlessLabel, FacebookSettings.FrictionlessRequests); } EditorGUILayout.Space(); } private void IOSUtilGUI() { this.showIOSSettings = EditorGUILayout.Foldout(this.showIOSSettings, "iOS Build Settings"); if (this.showIOSSettings) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(this.urlSuffixLabel, GUILayout.Width(135), GUILayout.Height(16)); FacebookSettings.IosURLSuffix = EditorGUILayout.TextField(FacebookSettings.IosURLSuffix); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); } private void AndroidUtilGUI() { this.showAndroidUtils = EditorGUILayout.Foldout(this.showAndroidUtils, "Android Build Facebook Settings"); if (this.showAndroidUtils) { if (!FacebookAndroidUtil.SetupProperly) { var msg = "Your Android setup is not right. Check the documentation."; switch (FacebookAndroidUtil.SetupError) { case FacebookAndroidUtil.ErrorNoSDK: msg = "You don't have the Android SDK setup! Go to " + (Application.platform == RuntimePlatform.OSXEditor ? "Unity" : "Edit") + "->Preferences... and set your Android SDK Location under External Tools"; break; case FacebookAndroidUtil.ErrorNoKeystore: msg = "Your android debug keystore file is missing! You can create new one by creating and building empty Android project in Ecplise."; break; case FacebookAndroidUtil.ErrorNoKeytool: msg = "Keytool not found. Make sure that Java is installed, and that Java tools are in your path."; break; case FacebookAndroidUtil.ErrorNoOpenSSL: msg = "OpenSSL not found. Make sure that OpenSSL is installed, and that it is in your path."; break; case FacebookAndroidUtil.ErrorKeytoolError: msg = "Unkown error while getting Debug Android Key Hash."; break; } EditorGUILayout.HelpBox(msg, MessageType.Warning); } EditorGUILayout.LabelField( "Copy and Paste these into your \"Native Android App\" Settings on developers.facebook.com/apps"); this.SelectableLabelField(this.packageNameLabel, PlayerSettings.bundleIdentifier); this.SelectableLabelField(this.classNameLabel, ManifestMod.DeepLinkingActivityName); this.SelectableLabelField(this.debugAndroidKeyLabel, FacebookAndroidUtil.DebugKeyHash); if (GUILayout.Button("Regenerate Android Manifest")) { ManifestMod.GenerateManifest(); } } EditorGUILayout.Space(); } private void AppLinksUtilGUI() { this.showAppLinksSettings = EditorGUILayout.Foldout(this.showAppLinksSettings, "App Links Settings"); if (this.showAppLinksSettings) { for (int i = 0; i < FacebookSettings.AppLinkSchemes.Count; ++i) { EditorGUILayout.LabelField(string.Format("App Link Schemes for '{0}'", FacebookSettings.AppLabels[i])); List<string> currentAppLinkSchemes = FacebookSettings.AppLinkSchemes[i].Schemes; for (int j = 0; j < currentAppLinkSchemes.Count; ++j) { GUI.changed = false; string scheme = EditorGUILayout.TextField(currentAppLinkSchemes[j]); if (scheme != currentAppLinkSchemes[j]) { currentAppLinkSchemes[j] = scheme; FacebookSettings.SettingsChanged(); } if (GUI.changed) { ManifestMod.GenerateManifest(); } } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Add a Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Add(string.Empty); FacebookSettings.SettingsChanged(); } if (currentAppLinkSchemes.Count > 0) { if (GUILayout.Button("Remove Last Scheme")) { FacebookSettings.AppLinkSchemes[i].Schemes.Pop(); } } EditorGUILayout.EndHorizontal(); } } } private void AboutGUI() { this.showAboutSection = EditorGUILayout.Foldout(this.showAboutSection, "About the Facebook SDK"); if (this.showAboutSection) { this.SelectableLabelField(this.sdkVersion, FacebookSdkVersion.Build); EditorGUILayout.Space(); } } private void SelectableLabelField(GUIContent label, string value) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(label, GUILayout.Width(180), GUILayout.Height(16)); EditorGUILayout.SelectableLabel(value, GUILayout.Height(16)); EditorGUILayout.EndHorizontal(); } private void BuildGUI() { if (GUILayout.Button("Build SDK Package")) { try { string outputPath = FacebookBuild.ExportPackage(); EditorUtility.DisplayDialog("Finished Exporting unityPackage", "Exported to: " + outputPath, "Okay"); } catch (System.Exception e) { EditorUtility.DisplayDialog("Error Exporting unityPackage", e.Message, "Okay"); } } } } }
// Copyright 2019 DeepMind Technologies Limited // // 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.IO; using System.Runtime.InteropServices; using System.Xml; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools.Utils; namespace Mujoco { [TestFixture] public class MjEngineToolXmlLoadingTests { [Test] public unsafe void LoadingSceneFromAProvidedAsset() { var modelFile = Resources.Load<TextAsset>("ValidModel"); var modelPtr = MjEngineTool.LoadModelFromString(modelFile.text); var model = (MujocoLib.mjModel_)Marshal.PtrToStructure(new IntPtr(modelPtr), typeof(MujocoLib.mjModel_)); Assert.That(model.nbody, Is.EqualTo(3)); } } [TestFixture] public class MjEngineToolTransformHelpersTests { [TestCase(1, 2, 3)] [TestCase(-1, -2, -3)] [TestCase(-1, 2, 3)] [TestCase(1, -2, 3)] [TestCase(1, 2, -3)] public unsafe void RoundrobinConversionOfVector3(float x, float y, float z) { var vec = new Vector3(x, y, z); var MjVec = MjEngineTool.MjVector3(vec); var MjVecAsArray = new double[] { 10, 11, 12, MjVec.x, MjVec.y, MjVec.z }; fixed (double* MjArrPtr = MjVecAsArray) { var recreatedVec = MjEngineTool.UnityVector3(MjArrPtr, 1); Assert.That(recreatedVec, Is.EqualTo(vec)); } } [TestCase(1, 2, 3)] [TestCase(-1, -2, -3)] [TestCase(-1, 2, 3)] [TestCase(1, -2, 3)] [TestCase(1, 2, -3)] public void RoundrobinConversionOfVector3UsingCoreType(float x, float y, float z) { var vec = new Vector3(x, y, z); var MjVec = MjEngineTool.MjVector3(vec); var unityVec = MjEngineTool.UnityVector3(MjVec); Assert.That(unityVec, Is.EqualTo(vec)); } [TestCase(0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(-0.1f, -0.2f, -0.3f, -0.4f)] [TestCase(-0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(0.1f, -0.2f, 0.3f, 0.4f)] [TestCase(0.1f, 0.2f, -0.3f, 0.4f)] [TestCase(0.1f, 0.2f, 0.3f, -0.4f)] public unsafe void RoundrobinConversionOfQuaternion(float x, float y, float z, float w) { var quat = new Quaternion(x, y, z, w); var MjQuat = MjEngineTool.MjQuaternion(quat); var MjQuatAsArray = new double[] { 10, 20, 30, 40, MjQuat.w, MjQuat.x, MjQuat.y, MjQuat.z }; var recreatedQuat = MjEngineTool.UnityQuaternion(MjQuatAsArray, 1); var q1 = new Vector4(quat.x, quat.y, quat.z, quat.w); var q2 = new Vector4(recreatedQuat.x, recreatedQuat.y, recreatedQuat.z, recreatedQuat.w); Assert.That(q1, Is.EqualTo(q2)); } [TestCase(0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(-0.1f, -0.2f, -0.3f, -0.4f)] [TestCase(-0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(0.1f, -0.2f, 0.3f, 0.4f)] [TestCase(0.1f, 0.2f, -0.3f, 0.4f)] [TestCase(0.1f, 0.2f, 0.3f, -0.4f)] public unsafe void RoundrobinConversionOfQuaternionUsingUnsafeArrays(float x, float y, float z, float w) { var quat = new Quaternion(x, y, z, w); var MjQuat = MjEngineTool.MjQuaternion(quat); var MjQuatAsArray = new double[] { 10, 20, 30, 40, MjQuat.w, MjQuat.x, MjQuat.y, MjQuat.z }; fixed (double* MjArrPtr = MjQuatAsArray) { var recreatedQuat = MjEngineTool.UnityQuaternion(MjArrPtr, 1); var q1 = new Vector4(quat.x, quat.y, quat.z, quat.w); var q2 = new Vector4(recreatedQuat.x, recreatedQuat.y, recreatedQuat.z, recreatedQuat.w); Assert.That(q1, Is.EqualTo(q2)); } } [TestCase(0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(-0.1f, -0.2f, -0.3f, -0.4f)] [TestCase(-0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(0.1f, -0.2f, 0.3f, 0.4f)] [TestCase(0.1f, 0.2f, -0.3f, 0.4f)] [TestCase(0.1f, 0.2f, 0.3f, -0.4f)] public void RoundrobinConversionOfQuaternionUsingCoreType(float x, float y, float z, float w) { var quat = new Quaternion(x, y, z, w); var MjQuat = MjEngineTool.MjQuaternion(quat); var unityQuat = MjEngineTool.UnityQuaternion(MjQuat); Assert.That(unityQuat, Is.EqualTo(quat)); } [TestCase(1, 2, 3)] [TestCase(-1, -2, -3)] [TestCase(-1, 2, 3)] [TestCase(1, -2, 3)] [TestCase(1, 2, -3)] public void RoundrobinConversionOfExtents(float x, float y, float z) { var extents = new Vector3(x, y, z); var MjExtents = MjEngineTool.MjExtents(extents); var unityExtents = MjEngineTool.UnityExtents(MjExtents); Assert.That(MjExtents, Is.Not.EqualTo(extents)); Assert.That(unityExtents, Is.EqualTo(extents)); } [TestCase(0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(-0.1f, -0.2f, -0.3f, -0.4f)] [TestCase(-0.1f, 0.2f, 0.3f, 0.4f)] [TestCase(0.1f, -0.2f, 0.3f, 0.4f)] [TestCase(0.1f, 0.2f, -0.3f, 0.4f)] [TestCase(0.1f, 0.2f, 0.3f, -0.4f)] public unsafe void SettingAndRetrievingQuaternions(float x, float y, float z, float w) { var quat = new Quaternion(x, y, z, w); var result = Quaternion.identity; var buffer = new double[4]; fixed (double* unsafeBuffer = buffer) { MjEngineTool.SetMjQuaternion(unsafeBuffer, quat, entryIndex: 0); result = MjEngineTool.UnityQuaternion(unsafeBuffer, entryIndex: 0); } Assert.That(quat, Is.EqualTo(result)); } [TestCase(1, 2, 3)] [TestCase(-1, -2, -3)] [TestCase(-1, 2, 3)] [TestCase(1, -2, 3)] [TestCase(1, 2, -3)] public unsafe void SettingAndRetrievingVectors(float x, float y, float z) { var vec = new Vector3(x, y, z); var result = Vector3.zero; double[] buffer = new double[3]; fixed (double* unsafeBuffer = buffer) { MjEngineTool.SetMjVector3(unsafeBuffer, vec, entryIndex: 0); result = MjEngineTool.UnityVector3(unsafeBuffer, entryIndex: 0); } Assert.That(vec, Is.EqualTo(result)); } } [TestFixture] public class MjEngineToolTransformSerializationTests { public class FakeMjComponent : MjComponent { public override MujocoLib.mjtObj ObjectType => MujocoLib.mjtObj.mjOBJ_GEOM; protected override void OnParseMjcf(XmlElement mjcf) {} protected override XmlElement OnGenerateMjcf(XmlDocument doc) { return doc.CreateElement("geom"); } } private GameObject _rootObject; private GameObject _intermediateObject; private FakeMjComponent _component; private Vector3EqualityComparer _vectorComparer; private Vector4EqualityComparer _quaternionComparer; [SetUp] public void SetUp() { _rootObject = new GameObject("rootObject"); _intermediateObject = new GameObject("intermediateObject"); _component = new GameObject("component").AddComponent<FakeMjComponent>(); var epsilon = 1e-3f; _vectorComparer = new Vector3EqualityComparer(epsilon); _quaternionComparer = new Vector4EqualityComparer(epsilon); } [TearDown] public void TearDown() { UnityEngine.Object.DestroyImmediate(_component.gameObject); UnityEngine.Object.DestroyImmediate(_intermediateObject); UnityEngine.Object.DestroyImmediate(_rootObject); MjSceneImportSettings.AnglesInDegrees = true; } [Test] public void SerializingPositionRotationOfRootComponent() { _component.transform.position = new Vector3(1, 2, 3); _component.transform.rotation = Quaternion.AngleAxis(45, Vector3.up); var doc = new XmlDocument(); var mjcf = doc.CreateElement("element"); MjEngineTool.PositionRotationToMjcf(mjcf, _component); Assert.That(mjcf.GetAttribute("pos"), Is.EqualTo("1 3 2")); Assert.That(mjcf.GetQuaternionAttribute("quat", Quaternion.identity), Is.EqualTo(new Quaternion(w:-0.9238795f, x:0, y:0, z:0.3826835f)) .Using(_quaternionComparer)); } [Test] public void SerializingPositionRotationOfRootComponentParentedToGameObject() { _component.transform.parent = _rootObject.transform; _rootObject.transform.position = new Vector3(1, 2, 3); _rootObject.transform.rotation = Quaternion.AngleAxis(45, Vector3.up); var doc = new XmlDocument(); var mjcf = doc.CreateElement("element"); MjEngineTool.PositionRotationToMjcf(mjcf, _component); Assert.That(mjcf.GetAttribute("pos"), Is.EqualTo("1 3 2")); Assert.That(mjcf.GetQuaternionAttribute("quat", Quaternion.identity), Is.EqualTo(new Quaternion(w:-0.9238795f, x:0, y:0, z:0.3826835f)) .Using(_quaternionComparer)); } [Test] public void SerializingPositionRotationOfChildComponentParentedThroughGameObject() { _component.transform.parent = _intermediateObject.transform; _intermediateObject.transform.parent = _rootObject.transform; _intermediateObject.transform.position = new Vector3(1, 2, 3); _intermediateObject.transform.rotation = Quaternion.AngleAxis(45, Vector3.up); var doc = new XmlDocument(); var mjcf = doc.CreateElement("element"); MjEngineTool.PositionRotationToMjcf(mjcf, _component); Assert.That(mjcf.GetAttribute("pos"), Is.EqualTo("1 3 2")); Assert.That(mjcf.GetQuaternionAttribute("quat", Quaternion.identity), Is.EqualTo(new Quaternion(w:-0.9238795f, x:0, y:0, z:0.3826835f)) .Using(_quaternionComparer)); } [Test] public void SerializingPositionAxisOfRootComponent() { _component.transform.position = new Vector3(1, 2, 3); _component.transform.rotation = Quaternion.AngleAxis(45, Vector3.up); var doc = new XmlDocument(); var mjcf = doc.CreateElement("element"); MjEngineTool.PositionAxisToMjcf(mjcf, _component); Assert.That(mjcf.GetAttribute("pos"), Is.EqualTo("1 3 2")); Assert.That(mjcf.GetVector3Attribute("axis", Vector3.zero), Is.EqualTo(new Vector3(0.7071068f, -0.7071069f, 0)).Using(_vectorComparer)); Assert.That(mjcf.GetAttribute("ref"), Is.EqualTo("0")); } [Test] public void SerializingPositionAxisOfRootComponentParentedToGameObject() { _component.transform.parent = _rootObject.transform; _rootObject.transform.position = new Vector3(1, 2, 3); _rootObject.transform.rotation = Quaternion.AngleAxis(45, Vector3.up); var doc = new XmlDocument(); var mjcf = doc.CreateElement("element"); MjEngineTool.PositionAxisToMjcf(mjcf, _component); Assert.That(mjcf.GetAttribute("pos"), Is.EqualTo("1 3 2")); Assert.That(mjcf.GetVector3Attribute("axis", Vector3.zero), Is.EqualTo(new Vector3(0.7071068f, -0.7071069f, 0)).Using(_vectorComparer)); Assert.That(mjcf.GetAttribute("ref"), Is.EqualTo("0")); } [Test] public void SerializingPositionAxisOfChildComponentParentedThroughGameObject() { _component.transform.parent = _intermediateObject.transform; _intermediateObject.transform.parent = _rootObject.transform; _intermediateObject.transform.position = new Vector3(1, 2, 3); _intermediateObject.transform.rotation = Quaternion.AngleAxis(45, Vector3.up); var doc = new XmlDocument(); var mjcf = doc.CreateElement("element"); MjEngineTool.PositionAxisToMjcf(mjcf, _component); Assert.That(mjcf.GetAttribute("pos"), Is.EqualTo("1 3 2")); Assert.That(mjcf.GetVector3Attribute("axis", Vector3.zero), Is.EqualTo(new Vector3(0.7071068f, -0.7071069f, 0)).Using(_vectorComparer)); Assert.That(mjcf.GetAttribute("ref"), Is.EqualTo("0")); } [Test] public void ParsePosition() { var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("pos", "1 3 2"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); Assert.That(_rootObject.transform.position, Is.EqualTo(new Vector3(1, 2, 3))); } [Test] public void ParseRotationFromQuat() { var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("quat", "-0.9238795 0 0 0.3826835"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); var expectedRotation = Quaternion.AngleAxis(45, Vector3.up); Assert.That(_rootObject.transform.rotation.x, Is.EqualTo(expectedRotation.x).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.y, Is.EqualTo(expectedRotation.y).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.z, Is.EqualTo(expectedRotation.z).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.w, Is.EqualTo(expectedRotation.w).Within(1e-5f)); // Assert.That( // _rootObject.transform.rotation, // Is.EqualTo(Quaternion.AngleAxis(45, Vector3.up)) // .Using(_quaternionComparer)); } [Test] public void ParseRotationFromZAxis() { var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("zaxis", "0 1 0"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); var expectedRotation = Quaternion.AngleAxis(90, Vector3.right); Assert.That(_rootObject.transform.rotation.x, Is.EqualTo(expectedRotation.x).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.y, Is.EqualTo(expectedRotation.y).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.z, Is.EqualTo(expectedRotation.z).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.w, Is.EqualTo(expectedRotation.w).Within(1e-5f)); // Assert.That( // _rootObject.transform.rotation, // Is.EqualTo(Quaternion.AngleAxis(90, Vector3.right)) // .Using(_quaternionComparer)); } [TestCase(true, 45, 45)] [TestCase(false, 0.785398f, 45)] [TestCase(true, 90, 90)] [TestCase(false, 1.570796f, 90)] public void ParseRotationFromAxisAngle(bool useDegrees, float MjAngle, float expectedAngle) { MjSceneImportSettings.AnglesInDegrees = useDegrees; var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("axisangle", $"1 0 0 {MjAngle}"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); var expectedRotation = Quaternion.AngleAxis(expectedAngle, Vector3.right); Assert.That(_rootObject.transform.rotation.x, Is.EqualTo(expectedRotation.x).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.y, Is.EqualTo(expectedRotation.y).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.z, Is.EqualTo(expectedRotation.z).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.w, Is.EqualTo(expectedRotation.w).Within(1e-5f)); // Assert.That( // _rootObject.transform.rotation, // Is.EqualTo(Quaternion.AngleAxis(expectedAngle, Vector3.right)) // .Using(_quaternionComparer)); } [TestCase(true, 0, 45, 0, 0, 0, -45)] [TestCase(false, 0, 0.785398f, 0, 0, 0, -45)] [TestCase(true, 0, 0, 45, 0, 45, 0)] [TestCase(false, 0, 0, 0.785398f, 0, 45, 0)] [TestCase(true, 45, 0, 0, 45, 0, 0)] [TestCase(false, 0.785398f, 0, 0, 45, 0, 0)] public void ParseRotationFromEuler(bool useDegrees, float mx, float my, float mz, float ex, float ey, float ez) { MjSceneImportSettings.AnglesInDegrees = useDegrees; var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("euler", $"{mx} {my} {mz}"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); var expectedRotation = Quaternion.Euler(ex, ey, ez); Assert.That(_rootObject.transform.rotation.x, Is.EqualTo(expectedRotation.x).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.y, Is.EqualTo(expectedRotation.y).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.z, Is.EqualTo(expectedRotation.z).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.w, Is.EqualTo(expectedRotation.w).Within(1e-5f)); // Assert.That( // _rootObject.transform.rotation, // Is.EqualTo(Quaternion.Euler(ex, ey, ez)) // .Using(_quaternionComparer)); } [Test] public void ParseRotationFromDirectionVector() { var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("fromto", $"0 0 0 1 1 0"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); var expectedRotation = new Quaternion(0.5f, 0, -0.5f, 0.7071068f); Assert.That(_rootObject.transform.rotation.x, Is.EqualTo(expectedRotation.x).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.y, Is.EqualTo(expectedRotation.y).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.z, Is.EqualTo(expectedRotation.z).Within(1e-5f)); Assert.That(_rootObject.transform.rotation.w, Is.EqualTo(expectedRotation.w).Within(1e-5f)); // Assert.That( // _rootObject.transform.rotation, // Is.EqualTo(new Quaternion(0.5f, 0, -0.5f, 0.7071068f)) // .Using(_quaternionComparer)); } [Test] public void ParsePositionFromDirectionVector() { var mjcf = new XmlDocument().CreateElement("element"); mjcf.SetAttribute("fromto", $"1 2 3 5 7 9"); MjEngineTool.ParseTransformMjcf(mjcf, _rootObject.transform); Assert.That(_rootObject.transform.position, Is.EqualTo(new Vector3(3, 6, 4.5f))); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using CarRentalSystem.Areas.HelpPage.Models; namespace CarRentalSystem.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Reflection; using System.Collections; using System.Runtime.InteropServices; using System.Xml; using Stetic.Wrapper; namespace Stetic { public static class GladeUtils { public const string Glade20SystemId = "http://glade.gnome.org/glade-2.0.dtd"; static Gdk.Atom gladeAtom; public static Gdk.Atom ApplicationXGladeAtom { get { if (gladeAtom == null) gladeAtom = Gdk.Atom.Intern ("application/x-glade", false); return gladeAtom; } } public static XmlDocument XslImportTransform (XmlDocument doc) { /* XmlDocumentType doctype = doc.DocumentType; if (doctype == null || doctype.Name != "glade-interface" || doctype.SystemId != Glade20SystemId) throw new GladeException ("Not a glade file according to doctype"); */ XmlReader reader = Registry.GladeImportXsl.Transform (doc, null, (XmlResolver)null); doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.Load (reader); return doc; } public static XmlDocument XslExportTransform (XmlDocument doc) { XmlReader reader = Registry.GladeExportXsl.Transform (doc, null, (XmlResolver)null); doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.Load (reader); XmlDocumentType doctype = doc.CreateDocumentType ("glade-interface", null, Glade20SystemId, null); doc.PrependChild (doctype); return doc; } public static XmlDocument Export (Gtk.Widget widget) { Stetic.Wrapper.Widget wrapper = Stetic.Wrapper.Widget.Lookup (widget); if (wrapper == null) return null; XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; XmlElement toplevel = doc.CreateElement ("glade-interface"); doc.AppendChild (toplevel); // For toplevel widgets, glade just saves it as-is. For // non-toplevels, it puts the widget into a dummy GtkWindow, // but using the packing attributes of the widget's real // container (so as to preserve expand/fill settings and the // like). XmlElement elem; Stetic.Wrapper.Container parent = wrapper.ParentWrapper; ObjectWriter writer = new ObjectWriter (doc, FileFormat.Glade); if (parent == null) { elem = wrapper.Write (writer); if (elem == null) return null; if (!(widget is Gtk.Window)) { XmlElement window = doc.CreateElement ("widget"); window.SetAttribute ("class", "GtkWindow"); window.SetAttribute ("id", "glade-dummy-container"); XmlElement child = doc.CreateElement ("child"); window.AppendChild (child); child.AppendChild (elem); elem = window; } } else { elem = doc.CreateElement ("widget"); // Set the class correctly (temporarily) so the XSL // transforms will work correctly. ClassDescriptor klass = parent.ClassDescriptor; elem.SetAttribute ("class", klass.CName); elem.AppendChild (parent.WriteContainerChild (writer, wrapper)); } toplevel.AppendChild (elem); doc = XslExportTransform (doc); if (parent != null) { elem = (XmlElement)doc.SelectSingleNode ("glade-interface/widget"); elem.SetAttribute ("class", "GtkWindow"); elem.SetAttribute ("id", "glade-dummy-container"); } return doc; } public static Stetic.Wrapper.Widget Import (IProject project, XmlDocument doc) { try { doc = XslImportTransform (doc); } catch { return null; } ObjectReader reader = new ObjectReader (project, FileFormat.Glade); XmlElement elem = (XmlElement)doc.SelectSingleNode ("glade-interface/widget"); if (elem.GetAttribute ("class") != "GtkWindow" || elem.GetAttribute ("id") != "glade-dummy-container") { // Creating a new toplevel Stetic.Wrapper.Widget toplevel = (Stetic.Wrapper.Widget) Stetic.ObjectWrapper.ReadObject (reader, elem); if (toplevel != null) { project.AddWindow ((Gtk.Window)toplevel.Wrapped); } return toplevel; } return (Stetic.Wrapper.Widget) Stetic.ObjectWrapper.ReadObject (reader, (XmlElement)elem.SelectSingleNode ("child/widget")); } public static void Copy (Gtk.Widget widget, Gtk.SelectionData seldata, bool copyAsText) { XmlDocument doc = Export (widget); if (doc == null) return; if (copyAsText) seldata.Text = doc.OuterXml; else seldata.Set (ApplicationXGladeAtom, 8, System.Text.Encoding.UTF8.GetBytes (doc.OuterXml)); } public static Stetic.Wrapper.Widget Paste (IProject project, Gtk.SelectionData seldata) { if (seldata.Type != ApplicationXGladeAtom) return null; string data = System.Text.Encoding.UTF8.GetString (seldata.Data); XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; try { doc.LoadXml (data); } catch { return null; } return Import (project, doc); } static object GetProperty (XmlElement elem, string selector, object defaultValue, bool extract) { XmlElement prop = (XmlElement)elem.SelectSingleNode (selector); if (prop == null) return defaultValue; if (extract) prop.ParentNode.RemoveChild (prop); return ParseProperty (null, defaultValue.GetType (), prop.InnerText).Val; } public static object GetProperty (XmlElement elem, string name, object defaultValue) { return GetProperty (elem, "./property[@name='" + name + "']", defaultValue, false); } public static object ExtractProperty (XmlElement elem, string name, object defaultValue) { return GetProperty (elem, "./property[@name='" + name + "']", defaultValue, true); } public static object GetChildProperty (XmlElement elem, string name, object defaultValue) { return GetProperty (elem, "./packing/property[@name='" + name + "']", defaultValue, false); } public static object ExtractChildProperty (XmlElement elem, string name, object defaultValue) { return GetProperty (elem, "./packing/property[@name='" + name + "']", defaultValue, true); } public static void SetProperty (XmlElement elem, string name, string value) { XmlElement prop_elem = elem.OwnerDocument.CreateElement ("property"); prop_elem.SetAttribute ("name", name); prop_elem.InnerText = value; elem.AppendChild (prop_elem); } public static void SetChildProperty (XmlElement elem, string name, string value) { XmlElement packing_elem = elem["packing"]; if (packing_elem == null) { packing_elem = elem.OwnerDocument.CreateElement ("packing"); elem.AppendChild (packing_elem); } SetProperty (packing_elem, name, value); } static GLib.Value ParseBasicType (GLib.TypeFundamentals type, string strval) { switch (type) { case GLib.TypeFundamentals.TypeChar: return new GLib.Value (SByte.Parse (strval)); case GLib.TypeFundamentals.TypeUChar: return new GLib.Value (Byte.Parse (strval)); case GLib.TypeFundamentals.TypeBoolean: return new GLib.Value (strval == "True"); case GLib.TypeFundamentals.TypeInt: return new GLib.Value (Int32.Parse (strval)); case GLib.TypeFundamentals.TypeUInt: return new GLib.Value (UInt32.Parse (strval)); case GLib.TypeFundamentals.TypeInt64: return new GLib.Value (Int64.Parse (strval)); case GLib.TypeFundamentals.TypeUInt64: return new GLib.Value (UInt64.Parse (strval)); case GLib.TypeFundamentals.TypeFloat: return new GLib.Value (Single.Parse (strval, System.Globalization.CultureInfo.InvariantCulture)); case GLib.TypeFundamentals.TypeDouble: return new GLib.Value (Double.Parse (strval, System.Globalization.CultureInfo.InvariantCulture)); case GLib.TypeFundamentals.TypeString: return new GLib.Value (strval); default: throw new GladeException ("Could not parse"); } } static GLib.Value ParseEnum (IntPtr gtype, string strval) { IntPtr enum_class = g_type_class_ref (gtype); try { IntPtr enum_value = g_enum_get_value_by_name (enum_class, strval); if (enum_value == IntPtr.Zero) throw new GladeException ("Could not parse"); int eval = Marshal.ReadInt32 (enum_value); return new GLib.Value (Enum.ToObject (GLib.GType.LookupType (gtype), eval)); } finally { g_type_class_unref (enum_class); } } static GLib.Value ParseFlags (IntPtr gtype, string strval) { IntPtr flags_class = g_type_class_ref (gtype); uint fval = 0; try { foreach (string flag in strval.Split ('|')) { if (flag == "") continue; IntPtr flags_value = g_flags_get_value_by_name (flags_class, flag); if (flags_value == IntPtr.Zero) throw new GladeException ("Could not parse"); int bits = Marshal.ReadInt32 (flags_value); fval |= (uint)bits; } return new GLib.Value (Enum.ToObject (GLib.GType.LookupType (gtype), fval)); } finally { g_type_class_unref (flags_class); } } static GLib.Value ParseAdjustment (string strval) { string[] vals = strval.Split (' '); double deflt, min, max, step, page_inc, page_size; deflt = Double.Parse (vals[0]); min = Double.Parse (vals[1]); max = Double.Parse (vals[2]); step = Double.Parse (vals[3]); page_inc = Double.Parse (vals[4]); page_size = Double.Parse (vals[5]); return new GLib.Value (new Gtk.Adjustment (deflt, min, max, step, page_inc, page_size)); } static GLib.Value ParseUnichar (string strval) { return new GLib.Value (strval.Length == 1 ? (uint)strval[0] : 0U); } static GLib.Value ParseProperty (ParamSpec pspec, Type propType, string strval) { IntPtr gtype; if (propType != null) gtype = ((GLib.GType)propType).Val; /* FIXME: ValueType is not supported right now else if (pspec != null) gtype = pspec.ValueType; */ else throw new GladeException ("Bad type"); GLib.TypeFundamentals typef = (GLib.TypeFundamentals)(int)g_type_fundamental (gtype); if (gtype == Gtk.Adjustment.GType.Val) return ParseAdjustment (strval); else if (typef == GLib.TypeFundamentals.TypeEnum) return ParseEnum (gtype, strval); else if (typef == GLib.TypeFundamentals.TypeFlags) return ParseFlags (gtype, strval); // FIXME: Enable when ParamSpec.IsUnichar is implemented. // else if (pspec != null && pspec.IsUnichar) // return ParseUnichar (strval); else return ParseBasicType (typef, strval); } static PropertyInfo FindClrProperty (Type type, string name, bool childprop) { if (childprop) { Type[] types = type.GetNestedTypes (); foreach (Type t in types) { if (typeof(Gtk.Container.ContainerChild).IsAssignableFrom (t)) { type = t; break; } } foreach (PropertyInfo pi in type.GetProperties ()) { Gtk.ChildPropertyAttribute at = (Gtk.ChildPropertyAttribute) Attribute.GetCustomAttribute (pi, typeof(Gtk.ChildPropertyAttribute), false); if (at != null && at.Name == name) return pi; } if (typeof(GLib.Object).IsAssignableFrom (type.BaseType)) return FindClrProperty (type.BaseType, name, true); } foreach (PropertyInfo pi in type.GetProperties ()) { GLib.PropertyAttribute at = (GLib.PropertyAttribute) Attribute.GetCustomAttribute (pi, typeof(GLib.PropertyAttribute), false); if (at != null && at.Name == name) return pi; } return null; } static GLib.Value ParseProperty (Type type, bool childprop, string name, string strval) { ParamSpec pspec; // FIXME: this can be removed when GParamSpec supports ValueType. PropertyInfo pi = FindClrProperty (type, name, childprop); if (pi == null) throw new GladeException ("Unknown property", type.ToString (), childprop, name, strval); if (childprop) pspec = ParamSpec.LookupChildProperty (type, name); else pspec = ParamSpec.LookupObjectProperty (type, name); if (pspec == null) throw new GladeException ("Unknown property", type.ToString (), childprop, name, strval); try { return ParseProperty (pspec, pi.PropertyType, strval); } catch { throw new GladeException ("Could not parse property", type.ToString (), childprop, name, strval); } } static void ParseProperties (Type type, bool childprops, IEnumerable props, out string[] propNames, out GLib.Value[] propVals) { ArrayList names = new ArrayList (); ArrayList values = new ArrayList (); foreach (XmlElement prop in props) { string name = prop.GetAttribute ("name").Replace ("_","-"); string strval = prop.InnerText; // Skip translation context if (prop.GetAttribute ("context") == "yes" && strval.IndexOf ('|') != -1) strval = strval.Substring (strval.IndexOf ('|') + 1); GLib.Value value; try { value = ParseProperty (type, childprops, name, strval); names.Add (name); values.Add (value); } catch (GladeException ge) { Console.Error.WriteLine (ge.Message); } } propNames = (string[])names.ToArray (typeof (string)); propVals = (GLib.Value[])values.ToArray (typeof (GLib.Value)); } static void ExtractProperties (TypedClassDescriptor klass, XmlElement elem, out Hashtable rawProps, out Hashtable overrideProps) { rawProps = new Hashtable (); overrideProps = new Hashtable (); foreach (ItemGroup group in klass.ItemGroups) { foreach (ItemDescriptor item in group) { TypedPropertyDescriptor prop = item as TypedPropertyDescriptor; if (prop == null) continue; prop = prop.GladeProperty; if (prop.GladeName == null) continue; XmlNode prop_node = elem.SelectSingleNode ("property[@name='" + prop.GladeName + "']"); if (prop_node == null) continue; if (prop.GladeOverride) overrideProps[prop] = prop_node; else rawProps[prop] = prop_node; } } } static void ReadSignals (TypedClassDescriptor klass, ObjectWrapper wrapper, XmlElement elem) { Stetic.Wrapper.Widget ob = wrapper as Stetic.Wrapper.Widget; if (ob == null) return; foreach (ItemGroup group in klass.SignalGroups) { foreach (TypedSignalDescriptor signal in group) { if (signal.GladeName == null) continue; XmlElement signal_elem = elem.SelectSingleNode ("signal[@name='" + signal.GladeName + "']") as XmlElement; if (signal_elem == null) continue; string handler = signal_elem.GetAttribute ("handler"); bool after = signal_elem.GetAttribute ("after") == "yes"; ob.Signals.Add (new Signal (signal, handler, after)); } } } static public void ImportWidget (ObjectWrapper wrapper, XmlElement elem) { string className = elem.GetAttribute ("class"); if (className == null) throw new GladeException ("<widget> node with no class name"); ClassDescriptor klassBase = Registry.LookupClassByCName (className); if (klassBase == null) throw new GladeException ("No stetic ClassDescriptor for " + className); TypedClassDescriptor klass = klassBase as TypedClassDescriptor; if (klass == null) throw new GladeException ("The widget class " + className + " is not supported by Glade"); ReadSignals (klass, wrapper, elem); Hashtable rawProps, overrideProps; ExtractProperties (klass, elem, out rawProps, out overrideProps); string[] propNames; GLib.Value[] propVals; ParseProperties (klass.WrappedType, false, rawProps.Values, out propNames, out propVals); Gtk.Widget widget; if (wrapper.Wrapped == null) { IntPtr raw = gtksharp_object_newv (klass.GType.Val, propNames.Length, propNames, propVals); if (raw == IntPtr.Zero) throw new GladeException ("Could not create widget", className); widget = (Gtk.Widget)GLib.Object.GetObject (raw, true); if (widget == null) { gtk_object_sink (raw); throw new GladeException ("Could not create gtk# wrapper", className); } ObjectWrapper.Bind (wrapper.Project, klass, wrapper, widget, true); } else { widget = (Gtk.Widget)wrapper.Wrapped; for (int i = 0; i < propNames.Length; i++) g_object_set_property (widget.Handle, propNames[i], ref propVals[i]); } MarkTranslatables (widget, rawProps); widget.Name = elem.GetAttribute ("id"); SetOverrideProperties (wrapper, overrideProps); MarkTranslatables (widget, overrideProps); } static void SetOverrideProperties (ObjectWrapper wrapper, Hashtable overrideProps) { foreach (TypedPropertyDescriptor prop in overrideProps.Keys) { XmlElement prop_elem = overrideProps[prop] as XmlElement; try { GLib.Value value = ParseProperty (prop.ParamSpec, prop.PropertyType, prop_elem.InnerText); prop.SetValue (wrapper.Wrapped, value.Val); } catch { throw new GladeException ("Could not parse property", wrapper.GetType ().ToString (), wrapper is Stetic.Wrapper.Container.ContainerChild, prop.GladeName, prop_elem.InnerText); } } } static void MarkTranslatables (object obj, Hashtable props) { foreach (PropertyDescriptor prop in props.Keys) { if (!prop.Translatable) continue; XmlElement prop_elem = props[prop] as XmlElement; if (prop_elem.GetAttribute ("translatable") != "yes") { prop.SetTranslated (obj, false); continue; } prop.SetTranslated (obj, true); if (prop_elem.GetAttribute ("context") == "yes") { string strval = prop_elem.InnerText; int bar = strval.IndexOf ('|'); if (bar != -1) prop.SetTranslationContext (obj, strval.Substring (0, bar)); } if (prop_elem.HasAttribute ("comments")) prop.SetTranslationComment (obj, prop_elem.GetAttribute ("comments")); } } static public void SetPacking (Stetic.Wrapper.Container.ContainerChild wrapper, XmlElement child_elem) { XmlElement packing = child_elem["packing"]; if (packing == null) return; Gtk.Container.ContainerChild cc = wrapper.Wrapped as Gtk.Container.ContainerChild; TypedClassDescriptor klass = wrapper.ClassDescriptor as TypedClassDescriptor; if (klass == null) throw new GladeException ("The widget class " + cc.GetType () + " is not supported by Glade"); Hashtable rawProps, overrideProps; ExtractProperties (klass, packing, out rawProps, out overrideProps); string[] propNames; GLib.Value[] propVals; ParseProperties (cc.Parent.GetType (), true, rawProps.Values, out propNames, out propVals); for (int i = 0; i < propNames.Length; i++) cc.Parent.ChildSetProperty (cc.Child, propNames[i], propVals[i]); MarkTranslatables (cc, rawProps); SetOverrideProperties (wrapper, overrideProps); MarkTranslatables (cc, overrideProps); } internal static XmlElement CreatePacking (XmlDocument doc, Stetic.Wrapper.Container.ContainerChild childwrapper) { XmlElement packing_elem = doc.CreateElement ("packing"); GetProps (childwrapper, packing_elem); return packing_elem; } static string PropToString (ObjectWrapper wrapper, TypedPropertyDescriptor prop) { object value; if (!prop.GladeOverride) { Stetic.Wrapper.Container.ContainerChild ccwrap = wrapper as Stetic.Wrapper.Container.ContainerChild; GLib.Value gval; if (ccwrap != null) { Gtk.Container.ContainerChild cc = (Gtk.Container.ContainerChild)ccwrap.Wrapped; gval = new GLib.Value ((GLib.GType) prop.PropertyType); gtk_container_child_get_property (cc.Parent.Handle, cc.Child.Handle, prop.GladeName, ref gval); } else { Gtk.Widget widget = wrapper.Wrapped as Gtk.Widget; gval = new GLib.Value (widget, prop.GladeName); g_object_get_property (widget.Handle, prop.GladeName, ref gval); } value = gval.Val; } else value = prop.GetValue (wrapper.Wrapped); if (value == null) return null; // If the property has its default value, we don't need to write it if (prop.HasDefault && prop.ParamSpec.IsDefaultValue (value)) return null; if (value is Gtk.Adjustment) { Gtk.Adjustment adj = value as Gtk.Adjustment; return String.Format ("{0:G} {1:G} {2:G} {3:G} {4:G} {5:G}", adj.Value, adj.Lower, adj.Upper, adj.StepIncrement, adj.PageIncrement, adj.PageSize); } else if (value is Enum && prop.ParamSpec != null) { IntPtr klass = g_type_class_ref (((GLib.GType)prop.PropertyType).Val); if (prop.PropertyType.IsDefined (typeof (FlagsAttribute), false)) { System.Text.StringBuilder sb = new System.Text.StringBuilder (); uint val = (uint)System.Convert.ChangeType (value, typeof (uint)); while (val != 0) { IntPtr flags_value = g_flags_get_first_value (klass, val); if (flags_value == IntPtr.Zero) break; IntPtr fval = Marshal.ReadIntPtr (flags_value); val &= ~(uint)fval; IntPtr name = Marshal.ReadIntPtr (flags_value, Marshal.SizeOf (typeof (IntPtr))); if (name != IntPtr.Zero) { if (sb.Length != 0) sb.Append ('|'); sb.Append (GLib.Marshaller.Utf8PtrToString (name)); } } g_type_class_unref (klass); return sb.ToString (); } else { int val = (int)System.Convert.ChangeType (value, typeof (int)); IntPtr enum_value = g_enum_get_value (klass, val); g_type_class_unref (klass); IntPtr name = Marshal.ReadIntPtr (enum_value, Marshal.SizeOf (typeof (IntPtr))); return GLib.Marshaller.Utf8PtrToString (name); } } else if (value is bool) return (bool)value ? "True" : "False"; else return value.ToString (); } static public XmlElement ExportWidget (ObjectWrapper wrapper, XmlDocument doc) { XmlElement elem = doc.CreateElement ("widget"); elem.SetAttribute ("class", wrapper.ClassDescriptor.CName); elem.SetAttribute ("id", ((Gtk.Widget)wrapper.Wrapped).Name); GetProps (wrapper, elem); GetSignals (wrapper, elem); return elem; } static public void GetProps (ObjectWrapper wrapper, XmlElement parent_elem) { ClassDescriptor klass = wrapper.ClassDescriptor; foreach (ItemGroup group in klass.ItemGroups) { foreach (ItemDescriptor item in group) { TypedPropertyDescriptor prop = item as TypedPropertyDescriptor; if (prop == null) continue; prop = prop.GladeProperty; if (prop.GladeName == null) continue; if (!prop.VisibleFor (wrapper.Wrapped)) continue; string val = PropToString (wrapper, prop); if (val == null) continue; XmlElement prop_elem = parent_elem.OwnerDocument.CreateElement ("property"); prop_elem.SetAttribute ("name", prop.GladeName); if (val.Length > 0) prop_elem.InnerText = val; if (prop.Translatable && prop.IsTranslated (wrapper.Wrapped)) { prop_elem.SetAttribute ("translatable", "yes"); if (prop.TranslationContext (wrapper.Wrapped) != null) { prop_elem.SetAttribute ("context", "yes"); prop_elem.InnerText = prop.TranslationContext (wrapper.Wrapped) + "|" + prop_elem.InnerText; } if (prop.TranslationComment (wrapper.Wrapped) != null) prop_elem.SetAttribute ("comments", prop.TranslationComment (wrapper.Wrapped)); } parent_elem.AppendChild (prop_elem); } } } static public void GetSignals (ObjectWrapper wrapper, XmlElement parent_elem) { Stetic.Wrapper.Widget ob = wrapper as Stetic.Wrapper.Widget; if (ob == null) return; foreach (Signal signal in ob.Signals) { if (((TypedSignalDescriptor)signal.SignalDescriptor).GladeName == null) continue; if (!signal.SignalDescriptor.VisibleFor (wrapper.Wrapped)) continue; XmlElement signal_elem = parent_elem.OwnerDocument.CreateElement ("signal"); signal_elem.SetAttribute ("name", ((TypedSignalDescriptor)signal.SignalDescriptor).GladeName); signal_elem.SetAttribute ("handler", signal.Handler); if (signal.After) signal_elem.SetAttribute ("after", "yes"); parent_elem.AppendChild (signal_elem); } } [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_type_fundamental (IntPtr gtype); [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_type_class_ref (IntPtr gtype); [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_type_class_unref (IntPtr klass); [DllImport("glibsharpglue-2")] static extern IntPtr gtksharp_object_newv (IntPtr gtype, int n_params, string[] names, GLib.Value[] vals); [DllImport("libgtk-win32-2.0-0.dll")] static extern void gtk_object_sink (IntPtr raw); [DllImport("libgobject-2.0-0.dll")] static extern void g_object_get_property (IntPtr obj, string name, ref GLib.Value val); [DllImport("libgobject-2.0-0.dll")] static extern void g_object_set_property (IntPtr obj, string name, ref GLib.Value val); [DllImport("libgtk-win32-2.0-0.dll")] static extern void gtk_container_child_get_property (IntPtr parent, IntPtr child, string name, ref GLib.Value val); [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_enum_get_value_by_name (IntPtr enum_class, string name); [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_enum_get_value (IntPtr enum_class, int val); [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_flags_get_value_by_name (IntPtr flags_class, string nick); [DllImport("libgobject-2.0-0.dll")] static extern IntPtr g_flags_get_first_value (IntPtr flags_class, uint val); } }
using System; using System.Collections.Generic; using UnityEngine; using KSP.Localization; namespace KERBALISM { public class PassiveShield: PartModule, IPartMassModifier, IKerbalismModule { // config [KSPField] public string title = Local.PassiveShield_Sandbags;//"Sandbags" // GUI name of the status action in the PAW [KSPField] public string engageActionTitle = Local.PassiveShield_fill;//"fill" // what the deploy action should be called [KSPField] public string disengageActionTitle = Local.PassiveShield_empty;//"empty" // what the empty action should be called [KSPField] public string disabledTitle = Local.PassiveShield_stowed;// "stowed" // what to display in the status text while not deployed [KSPField] public bool toggle = true; // true if the effect can be toggled on/off [KSPField] public string animation; // name of animation to play when enabling/disabling [KSPField] public float added_mass = 1.5f; // mass added when deployed, in tons [KSPField] public bool require_eva = true; // true if only accessible by EVA [KSPField] public bool require_landed = true; // true if only deployable when landed [KSPField] public string crew_operate = "true"; // operator crew requirement. true means anyone // persisted for simplicity, so that the values are available in Total() below [KSPField(isPersistant = true)] public double radiation; // radiation effect in rad/s [KSPField(isPersistant = true)] public double ec_rate = 0; // EC consumption rate per-second (optional) // persistent [KSPField(isPersistant = true)] public bool deployed = false; // currently deployed [KSPField(guiActive = true, guiActiveEditor = true, guiName = "_", groupName = "Radiation", groupDisplayName = "#KERBALISM_Group_Radiation")]//Radiation // rmb status public string Status; // rate of radiation emitted/shielded Animator deploy_anim; CrewSpecs deploy_cs; // pseudo-ctor public override void OnStart(StartState state) { // don't break tutorial scenarios if (Lib.DisableScenario(this)) return; // update RMB ui Fields["Status"].guiName = title; Actions["Action"].active = toggle; if(toggle) { Events["Toggle"].guiActiveUnfocused = require_eva; Events["Toggle"].guiActive = !require_eva || Lib.IsEditor(); } // deal with non-toggable if (!toggle) { deployed = true; } // create animator deploy_anim = new Animator(part, animation); // set animation initial state deploy_anim.Still(deployed ? 1.0 : 0.0); deploy_cs = new CrewSpecs(crew_operate); } public void Update() { // update ui Status = deployed ? Lib.BuildString(Local.PassiveShield_absorbing ," ", Lib.HumanReadableRadiation(Math.Abs(radiation))) : disabledTitle;//"absorbing Events["Toggle"].guiName = Lib.StatusToggle(title, deployed ? disengageActionTitle : engageActionTitle); } public void FixedUpdate() { // do nothing else in the editor if (Lib.IsEditor()) return; // allow sandbag filling only when landed bool allowDeploy = vessel.Landed || !require_landed; Events["Toggle"].active = toggle && (allowDeploy || deployed); } /// <summary> /// We're always going to call you for resource handling. You tell us what to produce or consume. Here's how it'll look when your vessel is NOT loaded /// </summary> /// <param name="vessel">the vessel (unloaded)</param> /// <param name="proto_part">proto part snapshot (contains all non-persistant KSPFields)</param> /// <param name="proto_module">proto part module snapshot (contains all non-persistant KSPFields)</param> /// <param name="partModule">proto part module snapshot (contains all non-persistant KSPFields)</param> /// <param name="part">proto part snapshot (contains all non-persistant KSPFields)</param> /// <param name="availableResources">key-value pair containing all available resources and their currently available amount on the vessel. if the resource is not in there, it's not available</param> /// <param name="resourceChangeRequest">key-value pair that contains the resource names and the units per second that you want to produce/consume (produce: positive, consume: negative)</param> /// <param name="elapsed_s">how much time elapsed since the last time. note this can be very long, minutes and hours depending on warp speed</param> /// <returns>the title to be displayed in the resource tooltip</returns> public static string BackgroundUpdate(Vessel vessel, ProtoPartSnapshot proto_part, ProtoPartModuleSnapshot proto_module, PartModule partModule, Part part, Dictionary<string, double> availableResources, List<KeyValuePair<string, double>> resourceChangeRequest, double elapsed_s) { PassiveShield passiveShield = partModule as PassiveShield; if (passiveShield == null) return string.Empty; if (passiveShield.ec_rate > 0) return string.Empty; bool deployed = Lib.Proto.GetBool(proto_module, "deployed"); if(deployed) { resourceChangeRequest.Add(new KeyValuePair<string, double>("ElectricCharge", -passiveShield.ec_rate)); } return passiveShield.title; } public virtual string ResourceUpdate(Dictionary<string, double> availableResources, List<KeyValuePair<string, double>> resourceChangeRequest) { // if there is ec consumption if (deployed && ec_rate > 0) { resourceChangeRequest.Add(new KeyValuePair<string, double>("ElectricCharge", -ec_rate)); } return title; } public string PlannerUpdate(List<KeyValuePair<string, double>> resourceChangeRequest, CelestialBody body, Dictionary<string, double> environment) { return ResourceUpdate(null, resourceChangeRequest); } [KSPEvent(guiActive = true, guiActiveEditor = true, guiName = "_", active = true, groupName = "Radiation", groupDisplayName = "#KERBALISM_Group_Radiation")]//Radiation public void Toggle() { if (Lib.IsFlight()) { // disable for dead eva kerbals Vessel v = FlightGlobals.ActiveVessel; if (v == null || EVA.IsDead(v)) return; if (!deploy_cs.Check(v)) { Message.Post ( Lib.TextVariant ( Local.PassiveShield_MessagePost//"I don't know how this works!" ), deploy_cs.Warning() ); return; } } // switch status deployed = !deployed; // play animation deploy_anim.Play(!deployed, false); // refresh VAB/SPH ui if (Lib.IsEditor()) GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship); } // action groups [KSPAction("Toggle")] public void Action(KSPActionParam param) { Toggle(); } // return total radiation emitted in a vessel public static double Total(Vessel v) { // get resource cache ResourceInfo ec = ResourceCache.GetResource(v, "ElectricCharge"); double total = 0.0; if (v.loaded) { foreach (var shield in Lib.FindModules<PassiveShield>(v)) { if (ec.Amount > 0 || shield.ec_rate <= 0) { if (shield.deployed) total += shield.radiation; } } } else { foreach (ProtoPartModuleSnapshot m in Lib.FindModules(v.protoVessel, "PassiveShield")) { if (ec.Amount > 0 || Lib.Proto.GetDouble(m, "ec_rate") <= 0) { if (Lib.Proto.GetBool(m, "deployed")) { var rad = Lib.Proto.GetDouble(m, "radiation"); total += rad; } } } } return total; } // mass change support public float GetModuleMass(float defaultMass, ModifierStagingSituation sit) { return deployed ? added_mass : 0.0f; } public ModifierChangeWhen GetModuleMassChangeWhen() { return ModifierChangeWhen.CONSTANTLY; } } } // KERBALISM
/* Copyright (c) 2013-2015 Antmicro <www.antmicro.com> Authors: * Mateusz Holenko (mholenko@antmicro.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Linq; using AntShell.Terminal; using AntShell.Commands; using AntShell.Commands.BuiltIn; namespace AntShell { public class Shell : ICommandHandler { public event Action Quitted; public event Action<Shell> Started; public NavigableTerminalEmulator Terminal { get { return term; } set { term = value; line = new CommandLine(term, history, this); line.PreprocessSuggestionsInput = settings.PreprocessSuggestionsInput; line.NormalPrompt = settings.NormalPrompt; line.DirectorySeparatorChar = settings.DirectorySeparator; line.SearchPrompt = settings.SearchPrompt ?? new SearchPrompt("search `{0}`> ", ConsoleColor.Yellow); Writer = new CommandInteraction(term, line); } } private NavigableTerminalEmulator term; private readonly CommandHistory history; private CommandLine line; public List<ICommand> Commands { get; private set; } public string StartupCommand { get; set; } public CommandInteraction Writer { get; private set; } private readonly ICommandHandler externalHandler; private readonly ShellSettings settings; public Shell(ICommandHandler handler, ShellSettings settings) { history = new CommandHistory(); Commands = new List<ICommand>(); this.settings = settings; PrepareCommands(); if(handler != null) { externalHandler = handler; externalHandler.GetInternalCommands = () => Commands.Cast<ICommandDescription>(); } } public void InjectInput(string str) { foreach(var c in str) { term?.InputOutput.Inject(c); } } public void Start(bool stopOnError = false) { if(term == null) { return; } if(settings.HistorySavePath != null) { history.Load(settings.HistorySavePath); } term.Start(settings.ClearScreen); if(settings.BannerProvider != null) { term.Write(settings.BannerProvider()); term.NewLine(); term.NewLine(); term.Calibrate(); } if(StartupCommand != null) { term.Write(string.Format("Executing startup command: {0}", StartupCommand)); term.NewLine(); HandleCommand(StartupCommand, null); term.NewLine(); } line.Start(); var s = Started; if(s != null) { s(this); } term.Run(stopOnError); var q = Quitted; if(q != null) { q(); } } public void Stop() { term?.Stop(); } public void Reset() { term?.ClearScreen(); line.CurrentPrompt.Write(term); } private void PrepareCommands() { RegisterCommand(new CommandFromHistoryCommand(history)); RegisterCommand(new HistoryCommand(history)); if(settings.UseBuiltinSave) { RegisterCommand(new SaveCommand(history)); } if(settings.UseBuiltinQuit) { RegisterCommand(new QuitCommand()); } if(settings.UseBuiltinHelp) { RegisterCommand(new HelpCommand(Commands)); } } public void RegisterCommand(ICommand cmd) { if(Commands.Any(x => x.Name == cmd.Name)) { throw new ArgumentException("Command name is already registered"); } if(Commands.Any(x => x.AlternativeNames != null && x.AlternativeNames.Contains(cmd.Name))) { throw new ArgumentException("Command alternative name is already registered"); } Commands.Add(cmd); } string HandleOnHistorySearch(bool reset, string arg) { if(reset) { history.Reset(); } return history.ReverseSearch(arg); } public string[] SuggestionNeeded(string arg) { var result = Commands.Where(x => x.Name.StartsWith(arg)).Select(x => x.Name).ToList(); if(externalHandler != null) { result.AddRange(externalHandler.SuggestionNeeded(arg)); } return result.ToArray(); } public ICommandInteraction HandleCommand(string cmd, ICommandInteraction ic) { if(cmd != null) { history.Add(cmd); if(settings.HistorySavePath != null) { history.Save(settings.HistorySavePath); } } var param = Regex.Matches(cmd, string.Format(@"(?<match>[{0}]+)|\""(?<match>[{0}]*)""", @"\w\.\-\?\!\~\/")) .Cast<Match>() .Select(m => m.Groups["match"].Value) .ToArray(); var command = param.Length > 0 ? Commands.SingleOrDefault(x => (x.Name == param[0]) || x.AlternativeNames.Contains(param[0]) || ((x is IOperator) ? (param[0].Length > 0 && ((IOperator)x).Operator == param[0][0]) : false) ) : null; if(command == null) { if(externalHandler != null) { return externalHandler.HandleCommand(cmd, Writer); } Writer.WriteError(string.Format("Command {0} not found", param.Length > 0 ? param[0] : cmd)); } else { if(command is IOperator) { var list = new List<string> { param[0][0].ToString(), param[0].Substring(1) }; list.AddRange(param.Skip(1)); param = list.ToArray(); } command.Execute(param, Writer); } return Writer; } string HandleOnHistoryNeeded(int direction) { if(direction < 0) { return history.PreviousCommand(); } else if(direction > 0) { return history.NextCommand(); } else { return null; } } public void SetPrompt(Prompt p) { if(p == null) { line.NormalPrompt = settings.NormalPrompt; } else { line.NormalPrompt = p; } } #region ICommandHandler implementation public Func<IEnumerable<ICommandDescription>> GetInternalCommands { get; set; } #endregion } }
using System; using System.Collections; using System.Diagnostics; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Math.EC.Multiplier; namespace Org.BouncyCastle.Math.EC { /** * base class for points on elliptic curves. */ public abstract class ECPoint { internal readonly ECCurve curve; internal readonly ECFieldElement x, y; internal readonly bool withCompression; internal ECMultiplier multiplier = null; internal PreCompInfo preCompInfo = null; protected internal ECPoint( ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) { if (curve == null) throw new ArgumentNullException("curve"); this.curve = curve; this.x = x; this.y = y; this.withCompression = withCompression; } public ECCurve Curve { get { return curve; } } public ECFieldElement X { get { return x; } } public ECFieldElement Y { get { return y; } } public bool IsInfinity { get { return x == null && y == null; } } public bool IsCompressed { get { return withCompression; } } public override bool Equals( object obj) { if (obj == this) return true; ECPoint o = obj as ECPoint; if (o == null) return false; if (this.IsInfinity) return o.IsInfinity; return x.Equals(o.x) && y.Equals(o.y); } public override int GetHashCode() { if (this.IsInfinity) return 0; return x.GetHashCode() ^ y.GetHashCode(); } // /** // * Mainly for testing. Explicitly set the <code>ECMultiplier</code>. // * @param multiplier The <code>ECMultiplier</code> to be used to multiply // * this <code>ECPoint</code>. // */ // internal void SetECMultiplier( // ECMultiplier multiplier) // { // this.multiplier = multiplier; // } /** * Sets the <code>PreCompInfo</code>. Used by <code>ECMultiplier</code>s * to save the precomputation for this <code>ECPoint</code> to store the * precomputation result for use by subsequent multiplication. * @param preCompInfo The values precomputed by the * <code>ECMultiplier</code>. */ internal void SetPreCompInfo( PreCompInfo preCompInfo) { this.preCompInfo = preCompInfo; } public abstract byte[] GetEncoded(); public abstract ECPoint Add(ECPoint b); public abstract ECPoint Subtract(ECPoint b); public abstract ECPoint Negate(); public abstract ECPoint Twice(); public abstract ECPoint Multiply(BigInteger b); /** * Sets the appropriate <code>ECMultiplier</code>, unless already set. */ internal virtual void AssertECMultiplier() { if (this.multiplier == null) { lock (this) { if (this.multiplier == null) { this.multiplier = new FpNafMultiplier(); } } } } } public abstract class ECPointBase : ECPoint { protected internal ECPointBase( ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { } protected internal abstract bool YTilde { get; } /** * return the field element encoded with point compression. (S 4.3.6) */ public override byte[] GetEncoded() { if (this.IsInfinity) return new byte[1]; // Note: some of the tests rely on calculating byte length from the field element // (since the test cases use mismatching fields for curve/elements) int byteLength = X9IntegerConverter.GetByteLength(x); byte[] X = X9IntegerConverter.IntegerToBytes(this.X.ToBigInteger(), byteLength); byte[] PO; if (withCompression) { PO = new byte[1 + X.Length]; PO[0] = (byte)(YTilde ? 0x03 : 0x02); } else { byte[] Y = X9IntegerConverter.IntegerToBytes(this.Y.ToBigInteger(), byteLength); PO = new byte[1 + X.Length + Y.Length]; PO[0] = 0x04; Y.CopyTo(PO, 1 + X.Length); } X.CopyTo(PO, 1); return PO; } /** * Multiplies this <code>ECPoint</code> by the given number. * @param k The multiplicator. * @return <code>k * this</code>. */ public override ECPoint Multiply( BigInteger k) { if (k.SignValue < 0) throw new ArgumentException("The multiplicator cannot be negative", "k"); if (this.IsInfinity) return this; if (k.SignValue == 0) return this.curve.Infinity; AssertECMultiplier(); return this.multiplier.Multiply(this, k, preCompInfo); } } /** * Elliptic curve points over Fp */ public class FpPoint : ECPointBase { /** * Create a point which encodes with point compression. * * @param curve the curve to use * @param x affine x co-ordinate * @param y affine y co-ordinate */ public FpPoint( ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { } /** * Create a point that encodes with or without point compresion. * * @param curve the curve to use * @param x affine x co-ordinate * @param y affine y co-ordinate * @param withCompression if true encode with point compression */ public FpPoint( ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { if ((x != null && y == null) || (x == null && y != null)) throw new ArgumentException("Exactly one of the field elements is null"); } protected internal override bool YTilde { get { return this.Y.ToBigInteger().TestBit(0); } } // B.3 pg 62 public override ECPoint Add( ECPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return this; // Check if b = this or b = -this if (this.x.Equals(b.x)) { if (this.y.Equals(b.y)) { // this = b, i.e. this must be doubled return this.Twice(); } Debug.Assert(this.y.Equals(b.y.Negate())); // this = -b, i.e. the result is the point at infinity return this.curve.Infinity; } ECFieldElement gamma = b.y.Subtract(this.y).Divide(b.x.Subtract(this.x)); ECFieldElement x3 = gamma.Square().Subtract(this.x).Subtract(b.x); ECFieldElement y3 = gamma.Multiply(this.x.Subtract(x3)).Subtract(this.y); return new FpPoint(curve, x3, y3); } // B.3 pg 62 public override ECPoint Twice() { // Twice identity element (point at infinity) is identity if (this.IsInfinity) return this; // if y1 == 0, then (x1, y1) == (x1, -y1) // and hence this = -this and thus 2(x1, y1) == infinity if (this.y.ToBigInteger().SignValue == 0) return this.curve.Infinity; ECFieldElement TWO = this.curve.FromBigInteger(BigInteger.Two); ECFieldElement THREE = this.curve.FromBigInteger(BigInteger.Three); ECFieldElement gamma = this.x.Square().Multiply(THREE).Add(curve.a).Divide(y.Multiply(TWO)); ECFieldElement x3 = gamma.Square().Subtract(this.x.Multiply(TWO)); ECFieldElement y3 = gamma.Multiply(this.x.Subtract(x3)).Subtract(this.y); return new FpPoint(curve, x3, y3, this.withCompression); } // D.3.2 pg 102 (see Note:) public override ECPoint Subtract( ECPoint b) { if (b.IsInfinity) return this; // Add -b return Add(b.Negate()); } public override ECPoint Negate() { return new FpPoint(this.curve, this.x, this.y.Negate(), this.withCompression); } /** * Sets the default <code>ECMultiplier</code>, unless already set. */ internal override void AssertECMultiplier() { if (this.multiplier == null) { lock (this) { if (this.multiplier == null) { this.multiplier = new WNafMultiplier(); } } } } } /** * Elliptic curve points over F2m */ public class F2mPoint : ECPointBase { /** * @param curve base curve * @param x x point * @param y y point */ public F2mPoint( ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { } /** * @param curve base curve * @param x x point * @param y y point * @param withCompression true if encode with point compression. */ public F2mPoint( ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { if ((x != null && y == null) || (x == null && y != null)) { throw new ArgumentException("Exactly one of the field elements is null"); } if (x != null) { // Check if x and y are elements of the same field F2mFieldElement.CheckFieldElements(this.x, this.y); // Check if x and a are elements of the same field F2mFieldElement.CheckFieldElements(this.x, this.curve.A); } } /** * Constructor for point at infinity */ [Obsolete("Use ECCurve.Infinity property")] public F2mPoint( ECCurve curve) : this(curve, null, null) { } protected internal override bool YTilde { get { // X9.62 4.2.2 and 4.3.6: // if x = 0 then ypTilde := 0, else ypTilde is the rightmost // bit of y * x^(-1) return this.X.ToBigInteger().SignValue != 0 && this.Y.Multiply(this.X.Invert()).ToBigInteger().TestBit(0); } } /** * Check, if two <code>ECPoint</code>s can be added or subtracted. * @param a The first <code>ECPoint</code> to check. * @param b The second <code>ECPoint</code> to check. * @throws IllegalArgumentException if <code>a</code> and <code>b</code> * cannot be added. */ private static void CheckPoints( ECPoint a, ECPoint b) { // Check, if points are on the same curve if (!a.curve.Equals(b.curve)) throw new ArgumentException("Only points on the same curve can be added or subtracted"); // F2mFieldElement.CheckFieldElements(a.x, b.x); } /* (non-Javadoc) * @see org.bouncycastle.math.ec.ECPoint#add(org.bouncycastle.math.ec.ECPoint) */ public override ECPoint Add(ECPoint b) { CheckPoints(this, b); return AddSimple((F2mPoint) b); } /** * Adds another <code>ECPoints.F2m</code> to <code>this</code> without * checking if both points are on the same curve. Used by multiplication * algorithms, because there all points are a multiple of the same point * and hence the checks can be omitted. * @param b The other <code>ECPoints.F2m</code> to add to * <code>this</code>. * @return <code>this + b</code> */ internal F2mPoint AddSimple(F2mPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return this; F2mFieldElement x2 = (F2mFieldElement) b.X; F2mFieldElement y2 = (F2mFieldElement) b.Y; // Check if b == this or b == -this if (this.x.Equals(x2)) { // this == b, i.e. this must be doubled if (this.y.Equals(y2)) return (F2mPoint) this.Twice(); // this = -other, i.e. the result is the point at infinity return (F2mPoint) this.curve.Infinity; } ECFieldElement xSum = this.x.Add(x2); F2mFieldElement lambda = (F2mFieldElement)(this.y.Add(y2)).Divide(xSum); F2mFieldElement x3 = (F2mFieldElement)lambda.Square().Add(lambda).Add(xSum).Add(this.curve.A); F2mFieldElement y3 = (F2mFieldElement)lambda.Multiply(this.x.Add(x3)).Add(x3).Add(this.y); return new F2mPoint(curve, x3, y3, withCompression); } /* (non-Javadoc) * @see org.bouncycastle.math.ec.ECPoint#subtract(org.bouncycastle.math.ec.ECPoint) */ public override ECPoint Subtract( ECPoint b) { CheckPoints(this, b); return SubtractSimple((F2mPoint) b); } /** * Subtracts another <code>ECPoints.F2m</code> from <code>this</code> * without checking if both points are on the same curve. Used by * multiplication algorithms, because there all points are a multiple * of the same point and hence the checks can be omitted. * @param b The other <code>ECPoints.F2m</code> to subtract from * <code>this</code>. * @return <code>this - b</code> */ internal F2mPoint SubtractSimple( F2mPoint b) { if (b.IsInfinity) return this; // Add -b return AddSimple((F2mPoint) b.Negate()); } /* (non-Javadoc) * @see Org.BouncyCastle.Math.EC.ECPoint#twice() */ public override ECPoint Twice() { // Twice identity element (point at infinity) is identity if (this.IsInfinity) return this; // if x1 == 0, then (x1, y1) == (x1, x1 + y1) // and hence this = -this and thus 2(x1, y1) == infinity if (this.x.ToBigInteger().SignValue == 0) return this.curve.Infinity; F2mFieldElement lambda = (F2mFieldElement) this.x.Add(this.y.Divide(this.x)); F2mFieldElement x2 = (F2mFieldElement)lambda.Square().Add(lambda).Add(this.curve.A); ECFieldElement ONE = this.curve.FromBigInteger(BigInteger.One); F2mFieldElement y2 = (F2mFieldElement)this.x.Square().Add( x2.Multiply(lambda.Add(ONE))); return new F2mPoint(this.curve, x2, y2, withCompression); } public override ECPoint Negate() { return new F2mPoint(curve, this.x, this.x.Add(this.y), withCompression); } /** * Sets the appropriate <code>ECMultiplier</code>, unless already set. */ internal override void AssertECMultiplier() { if (this.multiplier == null) { lock (this) { if (this.multiplier == null) { if (((F2mCurve) this.curve).IsKoblitz) { this.multiplier = new WTauNafMultiplier(); } else { this.multiplier = new WNafMultiplier(); } } } } } } }
// Copyright 2009, Novell, Inc. // Copyright 2010, Novell, Inc. // Copyright 2011, 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using MonoMac.Foundation; using MonoMac.ObjCRuntime; namespace MonoMac.AVFoundation { public enum AVAudioQuality { Min = 0, Low = 0x20, Medium = 0x40, High = 0x60, Max = 0x7F } [Since (4,0)] public enum AVAssetExportSessionStatus { Unknown, Waiting, Exporting, Completed, Failed, Cancelled } [Since (4,0)] public enum AVAssetReaderStatus { Unknown = 0, Reading, Completed, Failed, Cancelled, } [Since (4,1)] public enum AVAssetWriterStatus { Unknown = 0, Writing, Completed, Failed, Cancelled, } [Since (4,0)] public enum AVCaptureVideoOrientation { Portrait = 1, PortraitUpsideDown, LandscapeRight, LandscapeLeft, } [Since (4,0)] public enum AVCaptureFlashMode { Off, On, Auto } [Since (4,0)] public enum AVCaptureTorchMode { Off, On, Auto } [Since (4,0)] public enum AVCaptureFocusMode { ModeLocked, ModeAutoFocus, ModeContinuousAutoFocus } [Since (4,0)] public enum AVCaptureDevicePosition { Back = 1, Front = 2 } [Since (4,0)] public enum AVCaptureExposureMode { Locked, AutoExpose, ContinuousAutoExposure } [Since (4,0)] public enum AVCaptureWhiteBalanceMode { Locked, AutoWhiteBalance, ContinuousAutoWhiteBalance } [Flags] [Since (4,0)] public enum AVAudioSessionInterruptionFlags { ShouldResume = 1 } public enum AVError { Unknown = -11800, OutOfMemory = -11801, SessionNotRunning = -11803, DeviceAlreadyUsedByAnotherSession = -11804, NoDataCaptured = -11805, SessionConfigurationChanged = -11806, DiskFull = -11807, DeviceWasDisconnected = -11808, MediaChanged = -11809, MaximumDurationReached = -11810, MaximumFileSizeReached = -11811, MediaDiscontinuity = -11812, MaximumNumberOfSamplesForFileFormatReached = -11813, DeviceNotConnected = -11814, DeviceInUseByAnotherApplication = -11815, DeviceLockedForConfigurationByAnotherProcess = -11817, SessionWasInterrupted = -11818, MediaServicesWereReset = -11819, ExportFailed = -11820, DecodeFailed = -11821, InvalidSourceMedia = - 11822, FileAlreadyExists = -11823, CompositionTrackSegmentsNotContiguous = -11824, InvalidCompositionTrackSegmentDuration = -11825, InvalidCompositionTrackSegmentSourceStartTime= -11826, InvalidCompositionTrackSegmentSourceDuration = -11827, FormatNotRecognized = -11828, FailedToParse = -11829, MaximumStillImageCaptureRequestsExceeded = 11830, ContentIsProtected = -11831, NoImageAtTime = -11832, DecoderNotFound = -11833, EncoderNotFound = -11834, ContentIsNotAuthorized = -11835, ApplicationIsNotAuthorized = -11836, DeviceIsNotAvailableInBackground = -11837, OperationNotSupportedForAsset = -11838, DecoderTemporarilyUnavailable = -11839, EncoderTemporarilyUnavailable = -11840, InvalidVideoComposition = -11841, //[Since (5,1)] ReferenceForbiddenByReferencePolicy = -11842, InvalidOutputURLPathExtension = -11843, ScreenCaptureFailed = -11844, DisplayWasDisabled = -11845, TorchLevelUnavailable = -11846, OperationInterrupted = -11847, IncompatibleAsset = -11848, FailedToLoadMediaData = -11849, ServerIncorrectlyConfigured = -11850, } [Since (4,0)] public enum AVPlayerActionAtItemEnd { Pause = 1, None } [Since (4,0)] public enum AVPlayerItemStatus { Unknown, ReadyToPlay, Failed } [Flags] [Since (4,0)] public enum AVAudioSessionFlags { NotifyOthersOnDeactivation = 1 } [Since (4,0)] public enum AVKeyValueStatus { Unknown, Loading, Loaded, Failed, Cancelled } [Since (4,0)] public enum AVPlayerStatus { Unknown, ReadyToPlay, Failed } public enum AVAssetReferenceRestrictions { ForbidNone = 0, ForbidRemoteReferenceToLocal = (1 << 0), ForbidLocalReferenceToRemote = (1 << 1), ForbidCrossSiteReference = (1 << 2), ForbidLocalReferenceToLocal = (1 << 3), ForbidAll = 0xFFFF, } public enum AVAssetImageGeneratorResult { Succeeded, Failed, Cancelled } public enum AVCaptureDeviceTransportControlsPlaybackMode { NotPlaying, Playing } public enum AVVideoFieldMode { Both, TopOnly, BottomOnly, Deinterlace } [Flags] public enum AVAudioSessionInterruptionOptions { ShouldResume = 1 } [Flags] public enum AVAudioSessionSetActiveOptions { NotifyOthersOnDeactivation = 1 } public enum AVAudioSessionPortOverride { None = 0, Speaker = 0x73706b72 // 'spkr' } public enum AVAudioSessionRouteChangeReason { Unknown, NewDeviceAvailable, OldDeviceUnavailable, CategoryChange, Override, WakeFromSleep, NoSuitableRouteForCategory } [Flags] public enum AVAudioSessionCategoryOptions { MixWithOthers = 1, DuckOthers = 2, AllowBluetooth = 4, DefaultToSpeaker = 8 } public enum AVAudioSessionInterruptionType { Ended, Began } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RouteTablesOperations operations. /// </summary> internal partial class RouteTablesOperations : IServiceOperations<NetworkClient>, IRouteTablesOperations { /// <summary> /// Initializes a new instance of the RouteTablesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RouteTablesOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteTable>(); _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<RouteTable>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or updates a route table in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update route table operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<RouteTable> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all route tables in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _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<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/routeTables").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _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<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified route table. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or updates a route table in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update route table operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (routeTableName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("routeTableName", routeTableName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<RouteTable>(); _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<RouteTable>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteTable>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _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<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all route tables in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<RouteTable>>(); _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<Page<RouteTable>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { class Styles { public const float BaseSpacing = 10f, BrowseButtonWidth = 25f, BroadModeLimit = 500f, NarrowModeLimit = 300f, ModeNotificationDelay = .5f, BroadModeBranchesMinWidth = 200f, BroadModeBranchesRatio = .4f, InitialStateAreaWidth = 200f, LocksEntryHeight = 42f, LocksSummaryHeight = 5f, LocksUserHeight = 5f, LocksDateHeight = 5f, HistoryEntryHeight = 40f, HistorySummaryHeight = 16f, HistoryDetailsHeight = 16f, HistoryEntryPadding = 16f, HistoryChangesIndentation = 17f, CommitAreaMinHeight = 16f, CommitAreaDefaultRatio = .4f, CommitAreaMaxHeight = 12 * 15f, CommitAreaPadding = 5f, PublishViewSpacingHeight = 5f, MinCommitTreePadding = 20f, FoldoutWidth = 11f, FoldoutIndentation = -2f, TreePadding = 12f, TreeIndentation = 12f, TreeRootIndentation = -5f, TreeVerticalSpacing = 3f, CommitIconSize = 16f, CommitIconHorizontalPadding = -5f, BranchListIndentation = 20f, BranchListSeparation = 15f, RemotesTotalHorizontalMargin = 37f, RemotesNameRatio = .2f, RemotesUserRatio = .2f, RemotesHostRation = .5f, RemotesAccessRatio = .1f, GitIgnoreRulesTotalHorizontalMargin = 33f, GitIgnoreRulesSelectorWidth = 14f, GitIgnoreRulesEffectRatio = .2f, GitIgnoreRulesFileRatio = .3f, GitIgnoreRulesLineRatio = .5f; public const int HalfSpacing = (int)(BaseSpacing / 2); private const string WarningLabel = "<b>Warning:</b> {0}"; private static GUIStyle label, boldLabel, centeredErrorLabel, errorLabel, deletedFileLabel, longMessageStyle, headerBoxStyle, headerStyle, headerBranchLabelStyle, headerUrlLabelStyle, headerRepoLabelStyle, fileHistoryLogTitleStyle, headerTitleStyle, headerDescriptionStyle, toolbarButtonStyle, historyLockStyle, historyEntrySummaryStyle, historyEntryDetailsStyle, historyEntryDetailsRightStyle, historyFileTreeBoxStyle, commitFileAreaStyle, commitButtonStyle, textFieldStyle, boldCenteredLabel, centeredLabel, commitDescriptionFieldStyle, toggleMixedStyle, authHeaderBoxStyle, lockedFileRowSelectedStyle, lockedFileRowStyle, genericTableBoxStyle, historyDetailsTitleStyle, historyDetailsMetaInfoStyle, genericBoxStyle, hyperlinkStyle, selectedArea, selectedLabel, progressAreaBackStyle, labelNoWrap, invisibleLabel, locksViewLockedByStyle, locksViewLockedBySelectedStyle; public static Texture2D GetFileStatusIcon(GitFileStatus status, bool isLocked) { if (isLocked) { switch (status) { case GitFileStatus.Modified: return Utility.GetIcon("locked.png", "locked@2x.png"); default: return Utility.GetIcon("locked-by-person.png", "locked-by-person@2x.png"); } } switch (status) { case GitFileStatus.Modified: return Utility.GetIcon("modified.png", "modified@2x.png"); case GitFileStatus.Added: return Utility.GetIcon("added.png", "added@2x.png"); case GitFileStatus.Deleted: return Utility.GetIcon("removed.png", "removed@2x.png"); case GitFileStatus.Renamed: return Utility.GetIcon("renamed.png", "renamed@2x.png"); case GitFileStatus.Untracked: return Utility.GetIcon("untracked.png", "untracked@2x.png"); } return null; } public static void BeginInitialStateArea(string title, string message) { GUILayout.BeginVertical(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginVertical(GUILayout.MaxWidth(InitialStateAreaWidth)); GUILayout.Label(title, EditorStyles.boldLabel); GUILayout.Label(message, LongMessageStyle); } public static void EndInitialStateArea() { GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.EndVertical(); } public static bool InitialStateActionButton(string label) { bool result; GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); result = GUILayout.Button(label, GUILayout.ExpandWidth(false)); GUILayout.EndHorizontal(); return result; } public static void Warning(string message) { GUILayout.BeginHorizontal(EditorStyles.helpBox); GUILayout.Label(string.Format(WarningLabel, message), LongMessageStyle); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } public static GUIStyle HistoryFileTreeBoxStyle { get { if (historyFileTreeBoxStyle == null) { var padding = new RectOffset((int)HistoryChangesIndentation, 0, 0, 0); historyFileTreeBoxStyle = new GUIStyle(); historyFileTreeBoxStyle.padding = padding; } return historyFileTreeBoxStyle; } } public static GUIStyle SelectedArea { get { if (selectedArea == null) { selectedArea = new GUIStyle(GUI.skin.label); selectedArea.name = "SelectedArea"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); selectedArea.normal.background = hierarchyStyle.onFocused.background; selectedArea.focused.background = hierarchyStyle.onFocused.background; } return selectedArea; } } public static GUIStyle Label { get { if (label == null) { label = new GUIStyle(GUI.skin.label); label.name = "CustomLabel"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); label.onNormal.background = hierarchyStyle.onNormal.background; label.onNormal.textColor = hierarchyStyle.onNormal.textColor; label.onFocused.background = hierarchyStyle.onFocused.background; label.onFocused.textColor = hierarchyStyle.onFocused.textColor; label.wordWrap = true; } return label; } } public static GUIStyle LabelNoWrap { get { if (labelNoWrap == null) { labelNoWrap = new GUIStyle(GUI.skin.label); labelNoWrap.name = "LabelNoWrap"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); labelNoWrap.onNormal.background = hierarchyStyle.onNormal.background; labelNoWrap.onNormal.textColor = hierarchyStyle.onNormal.textColor; labelNoWrap.onFocused.background = hierarchyStyle.onFocused.background; labelNoWrap.onFocused.textColor = hierarchyStyle.onFocused.textColor; labelNoWrap.wordWrap = false; } return labelNoWrap; } } public static GUIStyle InvisibleLabel { get { if (invisibleLabel == null) { invisibleLabel = new GUIStyle(GUI.skin.label); invisibleLabel.name = "InvisibleLabel"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); invisibleLabel.onNormal.background = hierarchyStyle.onNormal.background; invisibleLabel.onNormal.textColor = new Color(255, 0, 0, 0); invisibleLabel.onFocused.background = hierarchyStyle.onFocused.background; invisibleLabel.onFocused.textColor = new Color(255, 0, 0, 0); invisibleLabel.wordWrap = true; } return invisibleLabel; } } public static GUIStyle SelectedLabel { get { if (selectedLabel == null) { selectedLabel = new GUIStyle(GUI.skin.label); selectedLabel.name = "SelectedLabel"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); selectedLabel.onNormal.background = hierarchyStyle.onFocused.background; selectedLabel.onNormal.textColor = hierarchyStyle.onFocused.textColor; selectedLabel.onFocused.background = hierarchyStyle.onFocused.background; selectedLabel.onFocused.textColor = hierarchyStyle.onFocused.textColor; selectedLabel.normal.background = hierarchyStyle.onFocused.background; selectedLabel.normal.textColor = hierarchyStyle.onFocused.textColor; selectedLabel.wordWrap = true; } return selectedLabel; } } public static GUIStyle HeaderBranchLabelStyle { get { if (headerBranchLabelStyle == null) { headerBranchLabelStyle = new GUIStyle(EditorStyles.label); headerBranchLabelStyle.name = "HeaderBranchLabelStyle"; headerBranchLabelStyle.margin = new RectOffset(0, 0, 0, 0); headerBranchLabelStyle.wordWrap = true; } return headerBranchLabelStyle; } } public static GUIStyle HeaderRepoLabelStyle { get { if (headerRepoLabelStyle == null) { headerRepoLabelStyle = new GUIStyle(EditorStyles.boldLabel); headerRepoLabelStyle.name = "HeaderRepoLabelStyle"; headerRepoLabelStyle.margin = new RectOffset(0, 0, 0, 0); headerRepoLabelStyle.wordWrap = true; } return headerRepoLabelStyle; } } public static GUIStyle HeaderUrlLabelStyle { get { if (headerUrlLabelStyle == null) { headerUrlLabelStyle = new GUIStyle(EditorStyles.label); headerUrlLabelStyle.name = "HeaderUrlLabelStyle"; headerUrlLabelStyle.margin = new RectOffset(0, 0, 0, 0); headerUrlLabelStyle.fontStyle = FontStyle.Italic; } return headerUrlLabelStyle; } } public static GUIStyle HeaderTitleStyle { get { if (headerTitleStyle == null) { headerTitleStyle = new GUIStyle(EditorStyles.boldLabel); headerTitleStyle.name = "HeaderTitleStyle"; headerTitleStyle.margin = new RectOffset(0, 0, 0, 0); headerTitleStyle.wordWrap = true; } return headerTitleStyle; } } public static GUIStyle HeaderDescriptionStyle { get { if (headerDescriptionStyle == null) { headerDescriptionStyle = new GUIStyle(EditorStyles.wordWrappedLabel); headerDescriptionStyle.name = "HeaderDescriptionStyle"; headerDescriptionStyle.margin = new RectOffset(0, 0, 0, 0); } return headerDescriptionStyle; } } public static GUIStyle HeaderBoxStyle { get { if (headerBoxStyle == null) { headerBoxStyle = new GUIStyle("IN BigTitle"); headerBoxStyle.name = "HeaderBoxStyle"; headerBoxStyle.padding = new RectOffset(5, 5, 5, 5); headerBoxStyle.margin = new RectOffset(0, 0, 0, 0); } return headerBoxStyle; } } public static GUIStyle HeaderStyle { get { if (headerStyle == null) { headerStyle = new GUIStyle("IN BigTitle"); headerStyle.name = "HeaderStyle"; headerStyle.margin = new RectOffset(0, 0, 0, 0); headerStyle.padding = new RectOffset(0, 0, 0, 0); } return headerStyle; } } public static GUIStyle BoldLabel { get { if (boldLabel == null) { boldLabel = new GUIStyle(Label); boldLabel.name = "CustomBoldLabel"; boldLabel.fontStyle = FontStyle.Bold; } return boldLabel; } } public static GUIStyle DeletedFileLabel { get { if (deletedFileLabel == null) { deletedFileLabel = new GUIStyle(EditorStyles.label); deletedFileLabel.name = "DeletedFileLabel"; deletedFileLabel.normal.textColor = Color.gray; } return deletedFileLabel; } } public static GUIStyle ErrorLabel { get { if (errorLabel == null) { errorLabel = new GUIStyle(EditorStyles.wordWrappedLabel); errorLabel.name = "ErrorLabel"; errorLabel.normal.textColor = Color.red; } return errorLabel; } } public static GUIStyle CenteredErrorLabel { get { if (centeredErrorLabel == null) { centeredErrorLabel = new GUIStyle(EditorStyles.wordWrappedLabel); centeredErrorLabel.alignment = TextAnchor.MiddleCenter; centeredErrorLabel.name = "CenteredErrorLabel"; centeredErrorLabel.normal.textColor = Color.red; } return centeredErrorLabel; } } public static GUIStyle LongMessageStyle { get { if (longMessageStyle == null) { longMessageStyle = new GUIStyle(EditorStyles.wordWrappedLabel); longMessageStyle.name = "LongMessageStyle"; longMessageStyle.richText = true; } return longMessageStyle; } } public static GUIStyle ToolbarButtonStyle { get { if (toolbarButtonStyle == null) { toolbarButtonStyle = new GUIStyle(EditorStyles.toolbarButton); toolbarButtonStyle.name = "HistoryToolbarButtonStyle"; toolbarButtonStyle.richText = true; } return toolbarButtonStyle; } } public static GUIStyle LockButtonStyle { get { if (historyLockStyle == null) { historyLockStyle = new GUIStyle(GUI.skin.FindStyle("IN LockButton")); historyLockStyle.name = "LockStyle"; } historyLockStyle.margin = new RectOffset(3, 3, 2, 2); return historyLockStyle; } } public static GUIStyle HistoryEntrySummaryStyle { get { if (historyEntrySummaryStyle == null) { historyEntrySummaryStyle = new GUIStyle(LabelNoWrap); historyEntrySummaryStyle.name = "HistoryEntrySummaryStyle"; historyEntrySummaryStyle.contentOffset = new Vector2(BaseSpacing * 2, 0); } return historyEntrySummaryStyle; } } public static GUIStyle HistoryEntryDetailsStyle { get { if (historyEntryDetailsStyle == null) { historyEntryDetailsStyle = new GUIStyle(EditorStyles.miniLabel); historyEntryDetailsStyle.name = "HistoryEntryDetailsStyle"; var c = EditorStyles.miniLabel.normal.textColor; historyEntryDetailsStyle.normal.textColor = new Color(c.r, c.g, c.b, c.a * 0.7f); historyEntryDetailsStyle.onNormal.background = Label.onNormal.background; historyEntryDetailsStyle.onNormal.textColor = Label.onNormal.textColor; historyEntryDetailsStyle.onFocused.background = Label.onFocused.background; historyEntryDetailsStyle.onFocused.textColor = Label.onFocused.textColor; historyEntryDetailsStyle.contentOffset = new Vector2(BaseSpacing * 2, 0); } return historyEntryDetailsStyle; } } public static GUIStyle HistoryEntryDetailsRightStyle { get { if (historyEntryDetailsRightStyle == null) { historyEntryDetailsRightStyle = new GUIStyle(HistoryEntryDetailsStyle); historyEntryDetailsRightStyle.name = "HistoryEntryDetailsRightStyle"; } historyEntryDetailsRightStyle.alignment = TextAnchor.MiddleRight; return historyEntryDetailsRightStyle; } } public static GUIStyle LockedFileRowStyle { get { if (lockedFileRowStyle == null) { lockedFileRowStyle = new GUIStyle(); lockedFileRowStyle.name = "LockedFileRowStyle"; lockedFileRowStyle.padding = new RectOffset(2, 2, 1, 1); } return lockedFileRowStyle; } } public static GUIStyle LockedFileRowSelectedStyle { get { if (lockedFileRowSelectedStyle == null) { var hierarchyStyle = GUI.skin.FindStyle("PR Label"); lockedFileRowSelectedStyle = new GUIStyle(LockedFileRowStyle); lockedFileRowSelectedStyle.name = "LockedFileRowSelectedStyle"; lockedFileRowSelectedStyle.normal.background = hierarchyStyle.onFocused.background; lockedFileRowSelectedStyle.normal.textColor = hierarchyStyle.onFocused.textColor; } return lockedFileRowSelectedStyle; } } public static GUIStyle GenericTableBoxStyle { get { if (genericTableBoxStyle == null) { genericTableBoxStyle = new GUIStyle(GUI.skin.box); genericTableBoxStyle.name = "GenericTableBoxStyle"; } return genericTableBoxStyle; } } public static GUIStyle HistoryDetailsTitleStyle { get { if (historyDetailsTitleStyle == null) { historyDetailsTitleStyle = new GUIStyle(EditorStyles.boldLabel); historyDetailsTitleStyle.name = "HistoryDetailsTitleStyle"; historyDetailsTitleStyle.wordWrap = true; } return historyDetailsTitleStyle; } } public static GUIStyle HistoryDetailsMetaInfoStyle { get { if (historyDetailsMetaInfoStyle == null) { historyDetailsMetaInfoStyle = new GUIStyle(EditorStyles.miniLabel); historyDetailsMetaInfoStyle.name = "HistoryDetailsMetaInfoStyle"; historyDetailsMetaInfoStyle.normal.textColor = new Color(0f, 0f, 0f, 0.6f); } return historyDetailsMetaInfoStyle; } } public static GUIStyle LocksViewLockedByStyle { get { if (locksViewLockedByStyle == null) { locksViewLockedByStyle = new GUIStyle(EditorStyles.miniLabel); locksViewLockedByStyle.name = "LocksViewLockedByStyle"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); locksViewLockedByStyle.onNormal.background = hierarchyStyle.onNormal.background; locksViewLockedByStyle.onNormal.textColor = hierarchyStyle.onNormal.textColor; locksViewLockedByStyle.onFocused.background = hierarchyStyle.onFocused.background; locksViewLockedByStyle.onFocused.textColor = hierarchyStyle.onFocused.textColor; } return locksViewLockedByStyle; } } public static GUIStyle LocksViewLockedBySelectedStyle { get { if (locksViewLockedBySelectedStyle == null) { locksViewLockedBySelectedStyle = new GUIStyle(EditorStyles.miniLabel); locksViewLockedBySelectedStyle.name = "LocksViewLockedBySelectedStyle"; var hierarchyStyle = GUI.skin.FindStyle("PR Label"); locksViewLockedBySelectedStyle.onNormal.textColor = hierarchyStyle.onNormal.textColor; locksViewLockedBySelectedStyle.onNormal.background = hierarchyStyle.onFocused.background; locksViewLockedBySelectedStyle.onNormal.textColor = hierarchyStyle.onNormal.textColor; locksViewLockedBySelectedStyle.onFocused.background = hierarchyStyle.onFocused.background; locksViewLockedBySelectedStyle.onFocused.textColor = hierarchyStyle.onNormal.textColor; locksViewLockedBySelectedStyle.normal.background = hierarchyStyle.onFocused.background; locksViewLockedBySelectedStyle.normal.textColor = hierarchyStyle.onNormal.textColor; } return locksViewLockedBySelectedStyle; } } public static GUIStyle CommitFileAreaStyle { get { if (commitFileAreaStyle == null) { commitFileAreaStyle = new GUIStyle(GUI.skin.box); commitFileAreaStyle.name = "CommitFileAreaStyle"; commitFileAreaStyle.margin = new RectOffset(0, 0, 0, 0); commitFileAreaStyle.padding = new RectOffset(0, 0, 2, 2); } return commitFileAreaStyle; } } public static GUIStyle CommitButtonStyle { get { if (commitButtonStyle == null) { commitButtonStyle = new GUIStyle(GUI.skin.button); commitButtonStyle.name = "CommitButtonStyle"; commitButtonStyle.richText = true; commitButtonStyle.wordWrap = true; } return commitButtonStyle; } } public static GUIStyle TextFieldStyle { get { if (textFieldStyle == null) { textFieldStyle = new GUIStyle(GUI.skin.textField); textFieldStyle.name = "TextFieldStyle"; textFieldStyle.fixedHeight = 21; textFieldStyle.padding = new RectOffset(HalfSpacing, HalfSpacing, 4, 0); } return textFieldStyle; } } public static GUIStyle ProgressAreaBackStyle { get { if (progressAreaBackStyle == null) { progressAreaBackStyle = new GUIStyle(GUI.skin.FindStyle("ProgressBarBack")); progressAreaBackStyle.name = "ProgressAreaBackStyle"; //progressAreaBackStyle.normal.background = Utility.GetTextureFromColor(new Color(194f/255f, 194f/255f, 194f/255f)); progressAreaBackStyle.margin = new RectOffset(0, 0, 0, 0); progressAreaBackStyle.padding = new RectOffset(0, 0, 0, 0); } return progressAreaBackStyle; } } public static GUIStyle CenteredLabel { get { if (centeredLabel == null) { centeredLabel = new GUIStyle(EditorStyles.wordWrappedLabel); centeredLabel.alignment = TextAnchor.MiddleCenter; } return centeredLabel; } } public static GUIStyle BoldCenteredLabel { get { if (boldCenteredLabel == null) { boldCenteredLabel = new GUIStyle(EditorStyles.boldLabel); boldCenteredLabel.name = "BoldCenteredLabelStyle"; boldCenteredLabel.alignment = TextAnchor.MiddleCenter; boldCenteredLabel.wordWrap = true; } return boldCenteredLabel; } } public static GUIStyle CommitDescriptionFieldStyle { get { if (commitDescriptionFieldStyle == null) { commitDescriptionFieldStyle = new GUIStyle(GUI.skin.textArea); commitDescriptionFieldStyle.name = "CommitDescriptionFieldStyle"; commitDescriptionFieldStyle.padding = new RectOffset(HalfSpacing, HalfSpacing, HalfSpacing, HalfSpacing); commitDescriptionFieldStyle.wordWrap = true; } return commitDescriptionFieldStyle; } } public static GUIStyle ToggleMixedStyle { get { if (toggleMixedStyle == null) { toggleMixedStyle = GUI.skin.FindStyle("ToggleMixed"); } return toggleMixedStyle; } } public static GUIStyle AuthHeaderBoxStyle { get { if (authHeaderBoxStyle == null) { authHeaderBoxStyle = new GUIStyle(HeaderBoxStyle); authHeaderBoxStyle.name = "AuthHeaderBoxStyle"; } return authHeaderBoxStyle; } } public static GUIStyle GenericBoxStyle { get { if (genericBoxStyle == null) { genericBoxStyle = new GUIStyle(); genericBoxStyle.padding = new RectOffset(5, 5, 5, 5); } return genericBoxStyle; } } public static GUIStyle HyperlinkStyle { get { if (hyperlinkStyle == null) { hyperlinkStyle = new GUIStyle(EditorStyles.wordWrappedLabel); hyperlinkStyle.normal.textColor = new Color(0, 0, 0xEE); } return hyperlinkStyle; } } public static GUIStyle FileHistoryLogTitleStyle { get { if (fileHistoryLogTitleStyle == null) { fileHistoryLogTitleStyle = new GUIStyle(EditorStyles.largeLabel); fileHistoryLogTitleStyle.name = "FileHistoryLogTitleStyle"; fileHistoryLogTitleStyle.margin = new RectOffset(0, 0, 0, 0); } return fileHistoryLogTitleStyle; } } public static Texture2D ActiveBranchIcon { get { return Utility.GetIcon("current-branch-indicator.png", "current-branch-indicator@2x.png", Utility.IsDarkTheme); } } public static Texture2D BranchIcon { get { return Utility.GetIcon("branch.png", "branch@2x.png"); } } public static Texture2D TrackingBranchIcon { get { return Utility.GetIcon("tracked-branch-indicator.png"); } } public static Texture2D FavoriteIconOn { get { return Utility.GetIcon("favorite-branch-indicator.png"); } } public static Texture2D FavoriteIconOff { get { return FolderIcon; } } public static Texture2D SmallLogo { get { return Utility.IsDarkTheme ? Utility.GetIcon("small-logo-light.png", "small-logo-light@2x.png") : Utility.GetIcon("small-logo.png", "small-logo@2x.png"); } } public static Texture2D BigLogo { get { return Utility.IsDarkTheme ? Utility.GetIcon("big-logo-light.png", "big-logo-light@2x.png") : Utility.GetIcon("big-logo.png", "big-logo@2x.png"); } } public static Texture2D MergeIcon { get { return Utility.GetIcon("git-merge.png", "git-merge@2x.png"); } } public static Texture2D DotIcon { get { return Utility.GetIcon("dot.png", "dot@2x.png", Utility.IsDarkTheme); } } public static Texture2D LocalCommitIcon { get { return Utility.GetIcon("local-commit-icon.png", "local-commit-icon@2x.png", Utility.IsDarkTheme); } } public static Texture2D FolderIcon { get { return EditorGUIUtility.FindTexture("Folder Icon"); } } public static Texture2D RepoIcon { get { return Utility.GetIcon("repo.png", "repo@2x.png", Utility.IsDarkTheme); } } public static Texture2D LockIcon { get { return Utility.GetIcon("lock.png", "lock@2x.png"); } } public static Texture2D EmptyStateInit { get { return Utility.GetIcon("empty-state-init.png", "empty-state-init@2x.png"); } } public static Texture2D DropdownListIcon { get { return Utility.GetIcon("dropdown-list-icon.png", "dropdown-list-icon@2x.png"); } } public static Texture2D GlobeIcon { get { return Utility.GetIcon("globe.png", "globe@2x.png", Utility.IsDarkTheme); } } public static Texture2D SpinnerInside { get { return Utility.GetIcon("spinner-inside.png", "spinner-inside@2x.png"); } } public static Texture2D SpinnerOutside { get { return Utility.GetIcon("spinner-outside.png", "spinner-outside@2x.png"); } } public static Texture2D Code { get { return Utility.GetIcon("code.png", "code@2x.png"); } } public static Texture2D Rocket { get { return Utility.GetIcon("rocket.png", "rocket@2x.png"); } } public static Texture2D Merge { get { return Utility.GetIcon("merge.png", "merge@2x.png"); } } public static Texture2D SpinnerInsideInverted { get { return Utility.GetIcon("spinner-inside.png", "spinner-inside@2x.png", true); } } public static Texture2D SpinnerOutsideInverted { get { return Utility.GetIcon("spinner-outside.png", "spinner-outside@2x.png", true); } } public static Texture2D CodeInverted { get { return Utility.GetIcon("code.png", "code@2x.png", true); } } public static Texture2D RocketInverted { get { return Utility.GetIcon("rocket.png", "rocket@2x.png", true); } } public static Texture2D MergeInverted { get { return Utility.GetIcon("merge.png", "merge@2x.png", true); } } private static GUIStyle foldout; public static GUIStyle Foldout { get { if (foldout == null) { foldout = new GUIStyle(EditorStyles.foldout); foldout.name = "CustomFoldout"; foldout.focused.textColor = Color.white; foldout.onFocused.textColor = Color.white; foldout.focused.background = foldout.active.background; foldout.onFocused.background = foldout.onActive.background; } return foldout; } } private static GUIStyle treeNode; public static GUIStyle TreeNode { get { if (treeNode == null) { treeNode = new GUIStyle(GUI.skin.label); treeNode.name = "Custom TreeNode"; var greyTexture = Utility.GetTextureFromColor(Color.gray); treeNode.focused.background = greyTexture; treeNode.focused.textColor = Color.white; } return treeNode; } } private static GUIStyle activeTreeNode; public static GUIStyle ActiveTreeNode { get { if (activeTreeNode == null) { activeTreeNode = new GUIStyle(TreeNode); activeTreeNode.name = "Custom Active TreeNode"; activeTreeNode.fontStyle = FontStyle.Bold; } return activeTreeNode; } } private static GUIStyle focusedTreeNode; public static GUIStyle FocusedTreeNode { get { if (focusedTreeNode == null) { focusedTreeNode = new GUIStyle(TreeNode); focusedTreeNode.name = "Custom Focused TreeNode"; var blueColor = new Color(62f / 255f, 125f / 255f, 231f / 255f); var blueTexture = Utility.GetTextureFromColor(blueColor); focusedTreeNode.focused.background = blueTexture; } return focusedTreeNode; } } private static GUIStyle focusedActiveTreeNode; public static GUIStyle FocusedActiveTreeNode { get { if (focusedActiveTreeNode == null) { focusedActiveTreeNode = new GUIStyle(FocusedTreeNode); focusedActiveTreeNode.name = "Custom Focused Active TreeNode"; focusedActiveTreeNode.fontStyle = FontStyle.Bold; } return focusedActiveTreeNode; } } private static GUIStyle lockPathStyle; public static GUIStyle LockPathStyle { get { if (lockPathStyle == null) { lockPathStyle = new GUIStyle(GUI.skin.label); lockPathStyle.name = "Custom LockPathStyle"; lockPathStyle.fontSize = 11; } return lockPathStyle; } } private static GUIStyle lockMetaDataStyle; public static GUIStyle LockMetaDataStyle { get { if (lockMetaDataStyle == null) { lockMetaDataStyle = new GUIStyle(GUI.skin.label); lockMetaDataStyle.name = "Custom LockMetaDataStyle"; lockMetaDataStyle.fontSize = 10; } return lockMetaDataStyle; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Religious Instruction Curricula Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KCIDataSet : EduHubDataSet<KCI> { /// <inheritdoc /> public override string Name { get { return "KCI"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KCIDataSet(EduHubContext Context) : base(Context) { Index_KCIKEY = new Lazy<Dictionary<string, KCI>>(() => this.ToDictionary(i => i.KCIKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KCI" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KCI" /> fields for each CSV column header</returns> internal override Action<KCI, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KCI, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KCIKEY": mapper[i] = (e, v) => e.KCIKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KCI" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KCI" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KCI" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KCI}"/> of entities</returns> internal override IEnumerable<KCI> ApplyDeltaEntities(IEnumerable<KCI> Entities, List<KCI> DeltaEntities) { HashSet<string> Index_KCIKEY = new HashSet<string>(DeltaEntities.Select(i => i.KCIKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KCIKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KCIKEY.Remove(entity.KCIKEY); if (entity.KCIKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KCI>> Index_KCIKEY; #endregion #region Index Methods /// <summary> /// Find KCI by KCIKEY field /// </summary> /// <param name="KCIKEY">KCIKEY value used to find KCI</param> /// <returns>Related KCI entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCI FindByKCIKEY(string KCIKEY) { return Index_KCIKEY.Value[KCIKEY]; } /// <summary> /// Attempt to find KCI by KCIKEY field /// </summary> /// <param name="KCIKEY">KCIKEY value used to find KCI</param> /// <param name="Value">Related KCI entity</param> /// <returns>True if the related KCI entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKCIKEY(string KCIKEY, out KCI Value) { return Index_KCIKEY.Value.TryGetValue(KCIKEY, out Value); } /// <summary> /// Attempt to find KCI by KCIKEY field /// </summary> /// <param name="KCIKEY">KCIKEY value used to find KCI</param> /// <returns>Related KCI entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCI TryFindByKCIKEY(string KCIKEY) { KCI value; if (Index_KCIKEY.Value.TryGetValue(KCIKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCI table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCI]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KCI]( [KCIKEY] varchar(10) NOT NULL, [DESCRIPTION] varchar(40) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KCI_Index_KCIKEY] PRIMARY KEY CLUSTERED ( [KCIKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="KCIDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="KCIDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCI"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KCI"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCI> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KCIKEY = new List<string>(); foreach (var entity in Entities) { Index_KCIKEY.Add(entity.KCIKEY); } builder.AppendLine("DELETE [dbo].[KCI] WHERE"); // Index_KCIKEY builder.Append("[KCIKEY] IN ("); for (int index = 0; index < Index_KCIKEY.Count; index++) { if (index != 0) builder.Append(", "); // KCIKEY var parameterKCIKEY = $"@p{parameterIndex++}"; builder.Append(parameterKCIKEY); command.Parameters.Add(parameterKCIKEY, SqlDbType.VarChar, 10).Value = Index_KCIKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCI data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCI data set</returns> public override EduHubDataSetDataReader<KCI> GetDataSetDataReader() { return new KCIDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCI data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCI data set</returns> public override EduHubDataSetDataReader<KCI> GetDataSetDataReader(List<KCI> Entities) { return new KCIDataReader(new EduHubDataSetLoadedReader<KCI>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KCIDataReader : EduHubDataSetDataReader<KCI> { public KCIDataReader(IEduHubDataSetReader<KCI> Reader) : base (Reader) { } public override int FieldCount { get { return 5; } } public override object GetValue(int i) { switch (i) { case 0: // KCIKEY return Current.KCIKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // LW_DATE return Current.LW_DATE; case 3: // LW_TIME return Current.LW_TIME; case 4: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // LW_DATE return Current.LW_DATE == null; case 3: // LW_TIME return Current.LW_TIME == null; case 4: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KCIKEY return "KCIKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // LW_DATE return "LW_DATE"; case 3: // LW_TIME return "LW_TIME"; case 4: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KCIKEY": return 0; case "DESCRIPTION": return 1; case "LW_DATE": return 2; case "LW_TIME": return 3; case "LW_USER": return 4; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Layout; using Xunit; namespace Avalonia.Controls.UnitTests.Presenters { public class ScrollContentPresenterTests { [Fact] public void Content_Can_Be_Left_Aligned() { Border content; var target = new ScrollContentPresenter { Content = content = new Border { Padding = new Thickness(8), HorizontalAlignment = HorizontalAlignment.Left }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(0, 0, 16, 100), content.Bounds); } [Fact] public void Content_Can_Be_Stretched() { Border content; var target = new ScrollContentPresenter { Content = content = new Border { Padding = new Thickness(8), }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(0, 0, 100, 100), content.Bounds); } [Fact] public void Content_Can_Be_Right_Aligned() { Border content; var target = new ScrollContentPresenter { Content = content = new Border { Padding = new Thickness(8), HorizontalAlignment = HorizontalAlignment.Right }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(84, 0, 16, 100), content.Bounds); } [Fact] public void Content_Can_Be_Bottom_Aligned() { Border content; var target = new ScrollContentPresenter { Content = content = new Border { Padding = new Thickness(8), VerticalAlignment = VerticalAlignment.Bottom, }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(0, 84, 100, 16), content.Bounds); } [Fact] public void Content_Can_Be_TopRight_Aligned() { Border content; var target = new ScrollContentPresenter { Content = content = new Border { Padding = new Thickness(8), HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, }, }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(84, 0, 16, 16), content.Bounds); } [Fact] public void Content_Can_Be_Larger_Than_Viewport() { TestControl content; var target = new ScrollContentPresenter { Content = content = new TestControl(), }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(0, 0, 150, 150), content.Bounds); } [Fact] public void Content_Can_Be_Offset() { Border content; var target = new ScrollContentPresenter { Content = content = new Border { Width = 150, Height = 150, }, Offset = new Vector(25, 25), }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new Rect(-25, -25, 150, 150), content.Bounds); } [Fact] public void Measure_Should_Pass_Bounded_X_If_CannotScrollHorizontally() { var child = new TestControl(); var target = new ScrollContentPresenter { Content = child, [ScrollContentPresenter.CanScrollHorizontallyProperty] = false, }; target.UpdateChild(); target.Measure(new Size(100, 100)); Assert.Equal(new Size(100, double.PositiveInfinity), child.AvailableSize); } [Fact] public void Measure_Should_Pass_Unbounded_X_If_CanScrollHorizontally() { var child = new TestControl(); var target = new ScrollContentPresenter { Content = child, }; target.UpdateChild(); target.Measure(new Size(100, 100)); Assert.Equal(Size.Infinity, child.AvailableSize); } [Fact] public void Arrange_Should_Set_Viewport_And_Extent_In_That_Order() { var target = new ScrollContentPresenter { Content = new Border { Width = 40, Height = 50 } }; var set = new List<string>(); target.UpdateChild(); target.Measure(new Size(100, 100)); target.GetObservable(ScrollViewer.ViewportProperty).Skip(1).Subscribe(_ => set.Add("Viewport")); target.GetObservable(ScrollViewer.ExtentProperty).Skip(1).Subscribe(_ => set.Add("Extent")); target.Arrange(new Rect(0, 0, 100, 100)); Assert.Equal(new[] { "Viewport", "Extent" }, set); } [Fact] public void Setting_Offset_Should_Invalidate_Arrange() { var target = new ScrollContentPresenter { Content = new Border { Width = 140, Height = 150 } }; target.UpdateChild(); target.Measure(new Size(100, 100)); target.Arrange(new Rect(0, 0, 100, 100)); target.Offset = new Vector(10, 100); Assert.True(target.IsMeasureValid); Assert.False(target.IsArrangeValid); } [Fact] public void BringDescendantIntoView_Should_Update_Offset() { var target = new ScrollContentPresenter { Width = 100, Height = 100, Content = new Border { Width = 200, Height = 200, } }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); target.BringDescendantIntoView(target.Child, new Rect(200, 200, 0, 0)); Assert.Equal(new Vector(100, 100), target.Offset); } [Fact] public void BringDescendantIntoView_Should_Handle_Child_Margin() { Border border; var target = new ScrollContentPresenter { Width = 100, Height = 100, Content = new Decorator { Margin = new Thickness(50), Child = border = new Border { Width = 200, Height = 200, } } }; target.UpdateChild(); target.Measure(Size.Infinity); target.Arrange(new Rect(0, 0, 100, 100)); target.BringDescendantIntoView(border, new Rect(200, 200, 0, 0)); Assert.Equal(new Vector(150, 150), target.Offset); } private class TestControl : Control { public Size AvailableSize { get; private set; } protected override Size MeasureOverride(Size availableSize) { AvailableSize = availableSize; return new Size(150, 150); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.Net { public abstract class WebRequest { internal class WebRequestPrefixElement { public string Prefix; public IWebRequestCreate Creator; public WebRequestPrefixElement(string P, IWebRequestCreate C) { Prefix = P; Creator = C; } } private static volatile List<WebRequestPrefixElement> s_prefixList; private static object s_internalSyncObject = new object(); // Create a WebRequest. // // This is the main creation routine. We take a Uri object, look // up the Uri in the prefix match table, and invoke the appropriate // handler to create the object. We also have a parameter that // tells us whether or not to use the whole Uri or just the // scheme portion of it. // // Input: // requestUri - Uri object for request. // useUriBase - True if we're only to look at the scheme portion of the Uri. // // Returns: // Newly created WebRequest. private static WebRequest Create(Uri requestUri, bool useUriBase) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Requests, "WebRequest", "Create", requestUri.ToString()); } string LookupUri; WebRequestPrefixElement Current = null; bool Found = false; if (!useUriBase) { LookupUri = requestUri.AbsoluteUri; } else { // schemes are registered as <schemeName>":", so add the separator // to the string returned from the Uri object LookupUri = requestUri.Scheme + ':'; } int LookupLength = LookupUri.Length; // Copy the prefix list so that if it is updated it will // not affect us on this thread. List<WebRequestPrefixElement> prefixList = PrefixList; // Look for the longest matching prefix. // Walk down the list of prefixes. The prefixes are kept longest // first. When we find a prefix that is shorter or the same size // as this Uri, we'll do a compare to see if they match. If they // do we'll break out of the loop and call the creator. for (int i = 0; i < prefixList.Count; i++) { Current = prefixList[i]; // See if this prefix is short enough. if (LookupLength >= Current.Prefix.Length) { // It is. See if these match. if (String.Compare(Current.Prefix, 0, LookupUri, 0, Current.Prefix.Length, StringComparison.OrdinalIgnoreCase) == 0) { // These match. Remember that we found it and break // out. Found = true; break; } } } WebRequest webRequest = null; if (Found) { // We found a match, so just call the creator and return what it does. webRequest = Current.Creator.Create(requestUri); if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Requests, "WebRequest", "Create", webRequest); } return webRequest; } if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Requests, "WebRequest", "Create", null); } // Otherwise no match, throw an exception. throw new NotSupportedException(SR.net_unknown_prefix); } // Create - Create a WebRequest. // // An overloaded utility version of the real Create that takes a // string instead of an Uri object. // // Input: // RequestString - Uri string to create. // // Returns: // Newly created WebRequest. public static WebRequest Create(string requestUriString) { if (requestUriString == null) { throw new ArgumentNullException(nameof(requestUriString)); } return Create(new Uri(requestUriString), false); } // Create - Create a WebRequest. // // Another overloaded version of the Create function that doesn't // take the UseUriBase parameter. // // Input: // requestUri - Uri object for request. // // Returns: // Newly created WebRequest. public static WebRequest Create(Uri requestUri) { if (requestUri == null) { throw new ArgumentNullException(nameof(requestUri)); } return Create(requestUri, false); } // CreateDefault - Create a default WebRequest. // // This is the creation routine that creates a default WebRequest. // We take a Uri object and pass it to the base create routine, // setting the useUriBase parameter to true. // // Input: // RequestUri - Uri object for request. // // Returns: // Newly created WebRequest. internal static WebRequest CreateDefault(Uri requestUri) { if (requestUri == null) { throw new ArgumentNullException(nameof(requestUri)); } return Create(requestUri, true); } public static HttpWebRequest CreateHttp(string requestUriString) { if (requestUriString == null) { throw new ArgumentNullException(nameof(requestUriString)); } return CreateHttp(new Uri(requestUriString)); } public static HttpWebRequest CreateHttp(Uri requestUri) { if (requestUri == null) { throw new ArgumentNullException(nameof(requestUri)); } if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https")) { throw new NotSupportedException(SR.net_unknown_prefix); } return (HttpWebRequest)CreateDefault(requestUri); } // RegisterPrefix - Register an Uri prefix for creating WebRequests. // // This function registers a prefix for creating WebRequests. When an // user wants to create a WebRequest, we scan a table looking for a // longest prefix match for the Uri they're passing. We then invoke // the sub creator for that prefix. This function puts entries in // that table. // // We don't allow duplicate entries, so if there is a dup this call // will fail. // // Input: // Prefix - Represents Uri prefix being registered. // Creator - Interface for sub creator. // // Returns: // True if the registration worked, false otherwise. public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) { bool Error = false; int i; WebRequestPrefixElement Current; if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } if (creator == null) { throw new ArgumentNullException(nameof(creator)); } // Lock this object, then walk down PrefixList looking for a place to // to insert this prefix. lock (s_internalSyncObject) { // Clone the object and update the clone, thus // allowing other threads to still read from the original. List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(PrefixList); // As AbsoluteUri is used later for Create, account for formating changes // like Unicode escaping, default ports, etc. Uri tempUri; if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri)) { String cookedUri = tempUri.AbsoluteUri; // Special case for when a partial host matching is requested, drop the added trailing slash // IE: http://host could match host or host.domain if (!prefix.EndsWith("/", StringComparison.Ordinal) && tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped) .Equals("/")) { cookedUri = cookedUri.Substring(0, cookedUri.Length - 1); } prefix = cookedUri; } i = 0; // The prefix list is sorted with longest entries at the front. We // walk down the list until we find a prefix shorter than this // one, then we insert in front of it. Along the way we check // equal length prefixes to make sure this isn't a dupe. while (i < prefixList.Count) { Current = prefixList[i]; // See if the new one is longer than the one we're looking at. if (prefix.Length > Current.Prefix.Length) { // It is. Break out of the loop here. break; } // If these are of equal length, compare them. if (prefix.Length == Current.Prefix.Length) { // They're the same length. if (string.Equals(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase)) { // ...and the strings are identical. This is an error. Error = true; break; } } i++; } // When we get here either i contains the index to insert at or // we've had an error, in which case Error is true. if (!Error) { // No error, so insert. prefixList.Insert(i, new WebRequestPrefixElement(prefix, creator)); // Assign the clone to the static object. Other threads using it // will have copied the original object already. PrefixList = prefixList; } } return !Error; } internal class HttpRequestCreator : IWebRequestCreate { // Create - Create an HttpWebRequest. // // This is our method to create an HttpWebRequest. We register // for HTTP and HTTPS Uris, and this method is called when a request // needs to be created for one of those. // // // Input: // uri - Uri for request being created. // // Returns: // The newly created HttpWebRequest. public WebRequest Create(Uri Uri) { return new HttpWebRequest(Uri); } } // PrefixList - Returns And Initialize our prefix list. // // // This is the method that initializes the prefix list. We create // an List for the PrefixList, then an HttpRequestCreator object, // and then we register the HTTP and HTTPS prefixes. // // Returns: // true internal static List<WebRequestPrefixElement> PrefixList { get { // GetConfig() might use us, so we have a circular dependency issue // that causes us to nest here. We grab the lock only if we haven't // initialized. if (s_prefixList == null) { lock (s_internalSyncObject) { if (s_prefixList == null) { List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(); prefixList.Add(new WebRequestPrefixElement("http:", new HttpRequestCreator())); prefixList.Add(new WebRequestPrefixElement("https:", new HttpRequestCreator())); prefixList.Add(new WebRequestPrefixElement("file:", new HttpRequestCreator())); prefixList.Add(new WebRequestPrefixElement("ftp:", new HttpRequestCreator())); s_prefixList = prefixList; } } } return s_prefixList; } set { s_prefixList = value; } } protected WebRequest() { } public abstract string Method { get; set; } public abstract Uri RequestUri { get; } public abstract WebHeaderCollection Headers { get; set; } public abstract string ContentType { get; set; } public virtual ICredentials Credentials { get { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); } set { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); } } public virtual bool UseDefaultCredentials { get { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); } set { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); } } public abstract IAsyncResult BeginGetResponse(AsyncCallback callback, object state); public abstract WebResponse EndGetResponse(IAsyncResult asyncResult); public abstract IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state); public abstract Stream EndGetRequestStream(IAsyncResult asyncResult); public virtual Task<Stream> GetRequestStreamAsync() { // Offload to a different thread to avoid blocking the caller during request submission. // We use Task.Run rather than Task.Factory.StartNew even though StartNew would let us pass 'this' // as a state argument to avoid the closure to capture 'this' and the associated delegate. // This is because the task needs to call FromAsync and marshal the inner Task out, and // Task.Run's implementation of this is sufficiently more efficient than what we can do with // Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate. return Task.Run(() => Task<Stream>.Factory.FromAsync( (callback, state) => ((WebRequest)state).BeginGetRequestStream(callback, state), iar => ((WebRequest)iar.AsyncState).EndGetRequestStream(iar), this)); } public virtual Task<WebResponse> GetResponseAsync() { // See comment in GetRequestStreamAsync(). Same logic applies here. return Task.Run(() => Task<WebResponse>.Factory.FromAsync( (callback, state) => ((WebRequest)state).BeginGetResponse(callback, state), iar => ((WebRequest)iar.AsyncState).EndGetResponse(iar), this)); } public abstract void Abort(); // Default Web Proxy implementation. private static IWebProxy s_DefaultWebProxy; private static bool s_DefaultWebProxyInitialized; public static IWebProxy DefaultWebProxy { get { lock (s_internalSyncObject) { if (!s_DefaultWebProxyInitialized) { s_DefaultWebProxy = SystemWebProxy.Get(); s_DefaultWebProxyInitialized = true; } return s_DefaultWebProxy; } } set { lock (s_internalSyncObject) { s_DefaultWebProxy = value; s_DefaultWebProxyInitialized = true; } } } public virtual IWebProxy Proxy { get { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); } set { throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException); } } } }
/*************************************************************************** * GiverService.cs * * Copyright (C) 2007 Novell, Inc. * Written by Calvin Gaisford <calvinrg@gmail.com> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using Mono.Zeroconf; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Giver { // public delegate void ClientConnectedHandler (TcpClient client); public delegate void ClientConnectedHandler (HttpListenerContext context); public class GiverService { #region Private Types private RegisterService client; private HttpListener listener; private Thread listnerThread; private bool running; private int port; //private string host; #endregion public event ClientConnectedHandler ClientConnected; public GiverService() { Logger.Debug("New GiverService was created"); running = true; int desired_port_num = Application.Preferences.PortNumber; if (desired_port_num < 0) //any port desired_port_num = 0; if (desired_port_num < IPEndPoint.MinPort || desired_port_num > IPEndPoint.MaxPort) { Logger.Debug ("Error: Port number must be between 0 and 65535. Trying to bind to any available port."); desired_port_num = 0; } port = desired_port_num; if (desired_port_num == 0 && !TryBindFixedOrAnyPort (desired_port_num, out port)) ThrowUnableToBindAnyPort (); try { Logger.Debug ("Starting listener on port {0}", port); listener = CreateListener (port); listener.Start (); } catch (HttpListenerException hle) { Logger.Debug ("Error starting a http listener on port {0} : {1}", port, hle.Message); listener = TryBindAndListenAgain (desired_port_num, out port); } catch (SocketException se) { Logger.Debug ("Error starting a http listener on port {0} : {1}", port, se.Message); listener = TryBindAndListenAgain (desired_port_num, out port); } if (port != Application.Preferences.PortNumber) Logger.Debug ("We have the port : {0}", port); listnerThread = new Thread(TcpServerThread); listnerThread.Start(); Logger.Debug("About to start the Zeroconf Service"); client = new RegisterService(); AdvertiseService(); } private HttpListener CreateListener (int actual_port) { HttpListener listener = new HttpListener (); listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; listener.Prefixes.Add (String.Format ("http://+:{0}/", actual_port)); return listener; } // Tries to bind to @desired_port, if that fails // then it tries to bind to _any_ port // @actual_port contains a valid available port number private bool TryBindFixedOrAnyPort (int desired_port, out int actual_port) { actual_port = -1; TcpListener server = new TcpListener (IPAddress.Any, desired_port); try { server.Start (); } catch (SocketException se) { if (port > 0) { // user requested port Logger.Debug ("Unable to bind to requested port number {0}. Error: {1}. " + "Trying to bind to any other available port", desired_port, se.Message); try { server = new TcpListener (IPAddress.Any, 0); server.Start (); } catch (SocketException se2) { Logger.Debug ("Unable to bind to any port, error: {0}", se2.Message); return false; } } } actual_port = ((IPEndPoint) server.LocalEndpoint).Port; server.Stop (); return true; } // Tries to start a http listener at @desired_port, if that fails // then it tries to listen on _any_ port // @actual_port will have the listener's port number private HttpListener TryBindAndListenAgain (int desired_port_num, out int actual_port) { actual_port = 0; if (desired_port_num <= 0) ThrowUnableToBindAnyPort (); Logger.Debug ("Trying to bind to any available port"); if (!TryBindFixedOrAnyPort (0, out actual_port)) ThrowUnableToBindAnyPort (); HttpListener listener = CreateListener (actual_port); listener.Start (); return listener; } public void Stop () { running = false; listener.Stop(); //server.Stop(); if (client != null) { client.Dispose (); client = null; } } private void AdvertiseService () { try { Logger.Debug("Adding Zeroconf Service _giver._tcp"); TxtRecord txt = new TxtRecord(); txt.Add("User Name", Application.Preferences.UserName); txt.Add("Machine Name", Environment.MachineName); txt.Add("Version", Defines.Version); if( Application.Preferences.PhotoType.CompareTo(Preferences.Local) == 0) { txt.Add("PhotoType", Preferences.Local); txt.Add("Photo", "none"); } else if( Application.Preferences.PhotoType.CompareTo(Preferences.Gravatar) == 0) { txt.Add("PhotoType", Preferences.Gravatar); txt.Add("Photo", Giver.Utilities.GetMd5Sum(Application.Preferences.PhotoLocation)); } else if( Application.Preferences.PhotoType.CompareTo(Preferences.Uri) == 0) { txt.Add("PhotoType", Preferences.Uri); txt.Add("Photo", Application.Preferences.PhotoLocation); } else { txt.Add("PhotoType", Preferences.None); txt.Add("Photo", "none"); } client.Name = "giver on " + Application.Preferences.UserName + "@" + Environment.MachineName; client.RegType = "_giver._tcp"; client.ReplyDomain = "local."; client.Port = (short)port; client.TxtRecord = txt; client.Register(); Logger.Debug("Avahi Service _giver._tcp is added"); } catch (Exception e) { Logger.Debug("Exception adding service: {0}", e.Message); Logger.Debug("Exception is: {0}", e); } } private void TcpServerThread() { while(running) { //Logger.Debug("RECEIVE: GiverService: Waiting for a connection... "); try { HttpListenerContext context = listener.GetContext(); //TcpClient client = server.AcceptTcpClient(); // Logger.Debug("RECEIVE: GiverService: Connected!"); // Fire off an event here and hand off the connected TcpClient to be handled if(ClientConnected != null) { ClientConnected(context); //ClientConnected(client); } else { context.Response.StatusCode = (int)HttpStatusCode.Gone; context.Response.Close(); //client.Close(); } } catch(HttpListenerException le) { // if the exception is not a listener being close, log it if(le.ErrorCode != 0) { Logger.Debug("Exception in GiverService {0} : {1}", le.ErrorCode, le.Message); } } catch(Exception e) { // this will happen when we close down the service Logger.Debug("GiverService: {0}", e.ToString ()); } } } void ThrowUnableToBindAnyPort () { throw new Exception ("Unable to bind to any port. See .giver.log file in your home directory for details."); } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class RemoteViews : java.lang.Object, android.os.Parcelable, android.view.LayoutInflater.Filter { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected RemoteViews(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class ActionException : java.lang.RuntimeException { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ActionException(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public ActionException(java.lang.Exception arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RemoteViews.ActionException._m0.native == global::System.IntPtr.Zero) global::android.widget.RemoteViews.ActionException._m0 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.ActionException.staticClass, "<init>", "(Ljava/lang/Exception;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.ActionException.staticClass, global::android.widget.RemoteViews.ActionException._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m1; public ActionException(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RemoteViews.ActionException._m1.native == global::System.IntPtr.Zero) global::android.widget.RemoteViews.ActionException._m1 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.ActionException.staticClass, "<init>", "(Ljava/lang/String;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.ActionException.staticClass, global::android.widget.RemoteViews.ActionException._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static ActionException() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RemoteViews.ActionException.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RemoteViews$ActionException")); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.RemoteViews.RemoteView_))] public partial interface RemoteView : java.lang.annotation.Annotation { } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.RemoteViews.RemoteView))] internal sealed partial class RemoteView_ : java.lang.Object, RemoteView { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal RemoteView_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool java.lang.annotation.Annotation.equals(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.RemoteViews.RemoteView_.staticClass, "equals", "(Ljava/lang/Object;)Z", ref global::android.widget.RemoteViews.RemoteView_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; global::java.lang.String java.lang.annotation.Annotation.toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.widget.RemoteViews.RemoteView_.staticClass, "toString", "()Ljava/lang/String;", ref global::android.widget.RemoteViews.RemoteView_._m1) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m2; int java.lang.annotation.Annotation.hashCode() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.RemoteViews.RemoteView_.staticClass, "hashCode", "()I", ref global::android.widget.RemoteViews.RemoteView_._m2); } private static global::MonoJavaBridge.MethodId _m3; global::java.lang.Class java.lang.annotation.Annotation.annotationType() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Class>(this, global::android.widget.RemoteViews.RemoteView_.staticClass, "annotationType", "()Ljava/lang/Class;", ref global::android.widget.RemoteViews.RemoteView_._m3) as java.lang.Class; } static RemoteView_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RemoteViews.RemoteView_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RemoteViews$RemoteView")); } } public new global::java.lang.String Package { get { return getPackage(); } } private static global::MonoJavaBridge.MethodId _m0; public virtual global::java.lang.String getPackage() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.widget.RemoteViews.staticClass, "getPackage", "()Ljava/lang/String;", ref global::android.widget.RemoteViews._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual void setBoolean(int arg0, java.lang.String arg1, bool arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setBoolean", "(ILjava/lang/String;Z)V", ref global::android.widget.RemoteViews._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m2; public virtual void setByte(int arg0, java.lang.String arg1, byte arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setByte", "(ILjava/lang/String;B)V", ref global::android.widget.RemoteViews._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void setChar(int arg0, java.lang.String arg1, char arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setChar", "(ILjava/lang/String;C)V", ref global::android.widget.RemoteViews._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void setShort(int arg0, java.lang.String arg1, short arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setShort", "(ILjava/lang/String;S)V", ref global::android.widget.RemoteViews._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void setInt(int arg0, java.lang.String arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setInt", "(ILjava/lang/String;I)V", ref global::android.widget.RemoteViews._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void setLong(int arg0, java.lang.String arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setLong", "(ILjava/lang/String;J)V", ref global::android.widget.RemoteViews._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m7; public virtual void setFloat(int arg0, java.lang.String arg1, float arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setFloat", "(ILjava/lang/String;F)V", ref global::android.widget.RemoteViews._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m8; public virtual void setDouble(int arg0, java.lang.String arg1, double arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setDouble", "(ILjava/lang/String;D)V", ref global::android.widget.RemoteViews._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m9; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.widget.RemoteViews._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m10; public virtual int describeContents() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.RemoteViews.staticClass, "describeContents", "()I", ref global::android.widget.RemoteViews._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual void addView(int arg0, android.widget.RemoteViews arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "addView", "(ILandroid/widget/RemoteViews;)V", ref global::android.widget.RemoteViews._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m12; public virtual void setBitmap(int arg0, java.lang.String arg1, android.graphics.Bitmap arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setBitmap", "(ILjava/lang/String;Landroid/graphics/Bitmap;)V", ref global::android.widget.RemoteViews._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m13; public virtual void removeAllViews(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "removeAllViews", "(I)V", ref global::android.widget.RemoteViews._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public virtual void setTextColor(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setTextColor", "(II)V", ref global::android.widget.RemoteViews._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new int LayoutId { get { return getLayoutId(); } } private static global::MonoJavaBridge.MethodId _m15; public virtual int getLayoutId() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.RemoteViews.staticClass, "getLayoutId", "()I", ref global::android.widget.RemoteViews._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setViewVisibility(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setViewVisibility", "(II)V", ref global::android.widget.RemoteViews._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; public virtual void setTextViewText(int arg0, java.lang.CharSequence arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setTextViewText", "(ILjava/lang/CharSequence;)V", ref global::android.widget.RemoteViews._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public void setTextViewText(int arg0, string arg1) { setTextViewText(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1); } private static global::MonoJavaBridge.MethodId _m18; public virtual void setImageViewResource(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setImageViewResource", "(II)V", ref global::android.widget.RemoteViews._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m19; public virtual void setImageViewUri(int arg0, android.net.Uri arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setImageViewUri", "(ILandroid/net/Uri;)V", ref global::android.widget.RemoteViews._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m20; public virtual void setImageViewBitmap(int arg0, android.graphics.Bitmap arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setImageViewBitmap", "(ILandroid/graphics/Bitmap;)V", ref global::android.widget.RemoteViews._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m21; public virtual void setChronometer(int arg0, long arg1, java.lang.String arg2, bool arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setChronometer", "(IJLjava/lang/String;Z)V", ref global::android.widget.RemoteViews._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m22; public virtual void setProgressBar(int arg0, int arg1, int arg2, bool arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setProgressBar", "(IIIZ)V", ref global::android.widget.RemoteViews._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m23; public virtual void setOnClickPendingIntent(int arg0, android.app.PendingIntent arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setOnClickPendingIntent", "(ILandroid/app/PendingIntent;)V", ref global::android.widget.RemoteViews._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m24; public virtual void setString(int arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setString", "(ILjava/lang/String;Ljava/lang/String;)V", ref global::android.widget.RemoteViews._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m25; public virtual void setCharSequence(int arg0, java.lang.String arg1, java.lang.CharSequence arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setCharSequence", "(ILjava/lang/String;Ljava/lang/CharSequence;)V", ref global::android.widget.RemoteViews._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public void setCharSequence(int arg0, java.lang.String arg1, string arg2) { setCharSequence(arg0, arg1, (global::java.lang.CharSequence)(global::java.lang.String)arg2); } private static global::MonoJavaBridge.MethodId _m26; public virtual void setUri(int arg0, java.lang.String arg1, android.net.Uri arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setUri", "(ILjava/lang/String;Landroid/net/Uri;)V", ref global::android.widget.RemoteViews._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m27; public virtual void setBundle(int arg0, java.lang.String arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "setBundle", "(ILjava/lang/String;Landroid/os/Bundle;)V", ref global::android.widget.RemoteViews._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m28; public virtual global::android.view.View apply(android.content.Context arg0, android.view.ViewGroup arg1) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.RemoteViews.staticClass, "apply", "(Landroid/content/Context;Landroid/view/ViewGroup;)Landroid/view/View;", ref global::android.widget.RemoteViews._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.view.View; } private static global::MonoJavaBridge.MethodId _m29; public virtual void reapply(android.content.Context arg0, android.view.View arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.RemoteViews.staticClass, "reapply", "(Landroid/content/Context;Landroid/view/View;)V", ref global::android.widget.RemoteViews._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m30; public virtual bool onLoadClass(java.lang.Class arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.RemoteViews.staticClass, "onLoadClass", "(Ljava/lang/Class;)Z", ref global::android.widget.RemoteViews._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public RemoteViews(java.lang.String arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RemoteViews._m31.native == global::System.IntPtr.Zero) global::android.widget.RemoteViews._m31 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "<init>", "(Ljava/lang/String;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m32; public RemoteViews(android.os.Parcel arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.RemoteViews._m32.native == global::System.IntPtr.Zero) global::android.widget.RemoteViews._m32 = @__env.GetMethodIDNoThrow(global::android.widget.RemoteViews.staticClass, "<init>", "(Landroid/os/Parcel;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RemoteViews.staticClass, global::android.widget.RemoteViews._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _CREATOR6102; public static global::android.os.Parcelable_Creator CREATOR { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.widget.RemoteViews.staticClass, _CREATOR6102)) as android.os.Parcelable_Creator; } } static RemoteViews() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RemoteViews.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RemoteViews")); global::android.widget.RemoteViews._CREATOR6102 = @__env.GetStaticFieldIDNoThrow(global::android.widget.RemoteViews.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;"); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; #if NET_45 using System.Collections.Generic; #endif namespace Octokit { /// <summary> /// A client for GitHub's Repositories API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details. /// </remarks> public interface IRepositoriesClient { /// <summary> /// Client for managing pull requests. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details /// </remarks> IPullRequestsClient PullRequest { get; } /// <summary> /// Client for managing branches in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/branches/">Branches API documentation</a> for more details /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] IRepositoryBranchesClient Branch { get; } /// <summary> /// Client for managing commit comments in a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information. /// </remarks> IRepositoryCommentsClient Comment { get; } /// <summary> /// Client for managing deploy keys in a repository. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information. /// </remarks> IRepositoryDeployKeysClient DeployKeys { get; } /// <summary> /// Client for managing the contents of a repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information. /// </remarks> IRepositoryContentsClient Content { get; } /// <summary> /// Creates a new repository for the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository.</returns> Task<Repository> Create(NewRepository newRepository); /// <summary> /// Creates a new repository in the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information. /// </remarks> /// <param name="organizationLogin">Login of the organization in which to create the repository</param> /// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/> instance for the created repository</returns> Task<Repository> Create(string organizationLogin, NewRepository newRepository); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(string owner, string name); /// <summary> /// Deletes the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information. /// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required. /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> Task Delete(long repositoryId); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(string owner, string name); /// <summary> /// Gets the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information. /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="Repository"/></returns> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")] Task<Repository> Get(long repositoryId); /// <summary> /// Gets all public repositories. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllPublic(); /// <summary> /// Gets all public repositories since the integer Id of the last Repository that you've seen. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters of the last repository seen</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllPublic(PublicRepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Makes a network request")] Task<IReadOnlyList<Repository>> GetAllForCurrent(); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(ApiOptions options); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request); /// <summary> /// Gets all repositories owned by the current user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information. /// </remarks> /// <param name="request">Search parameters to filter results on</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="login">The account name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login); /// <summary> /// Gets all repositories owned by the specified user. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information. /// </remarks> /// <param name="login">The account name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForUser(string login, ApiOptions options); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// The default page size on GitHub.com is 30. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization); /// <summary> /// Gets all repositories owned by the specified organization. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information. /// </remarks> /// <param name="organization">The organization name to search for</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns> Task<IReadOnlyList<Repository>> GetAllForOrg(string organization, ApiOptions options); /// <summary> /// A client for GitHub's Commit Status API. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more /// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a> /// that announced this feature. /// </remarks> ICommitStatusClient Status { get; } /// <summary> /// A client for GitHub's Repository Hooks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks> IRepositoryHooksClient Hooks { get; } /// <summary> /// A client for GitHub's Repository Forks API. /// </summary> /// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks> IRepositoryForksClient Forks { get; } /// <summary> /// A client for GitHub's Repo Collaborators. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details /// </remarks> IRepoCollaboratorsClient Collaborator { get; } /// <summary> /// Client for GitHub's Repository Deployments API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/deployment/">Collaborators API documentation</a> for more details /// </remarks> IDeploymentsClient Deployment { get; } /// <summary> /// Client for GitHub's Repository Statistics API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details ///</remarks> IStatisticsClient Statistics { get; } /// <summary> /// Client for GitHub's Repository Commits API /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details ///</remarks> IRepositoryCommitsClient Commit { get; } /// <summary> /// Access GitHub's Releases API. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/repos/releases/ /// </remarks> IReleasesClient Release { get; } /// <summary> /// Client for GitHub's Repository Merging API /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details ///</remarks> IMergingClient Merging { get; } /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(long repositoryId); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name, ApiOptions options); /// <summary> /// Gets all the branches for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns> [Obsolete("Please use RepositoriesClient.Branch.GetAll() instead. This method will be removed in a future version")] Task<IReadOnlyList<Branch>> GetAllBranches(long repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. Does not include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, bool includeAnonymous); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all contributors for the specified repository. With the option to include anonymous contributors. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param> /// <param name="options">Options for changing the API response</param> /// <returns>All contributors of the repository.</returns> Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(long repositoryId, bool includeAnonymous, ApiOptions options); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name); /// <summary> /// Gets all languages for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All languages used in the repository and the number of bytes of each language.</returns> Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(long repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(long repositoryId); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name, ApiOptions options); /// <summary> /// Gets all teams for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns> Task<IReadOnlyList<Team>> GetAllTeams(long repositoryId, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(long repositoryId); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name, ApiOptions options); /// <summary> /// Gets all tags for the specified repository. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="options">Options for changing the API response</param> /// <returns>All of the repositories tags.</returns> Task<IReadOnlyList<RepositoryTag>> GetAllTags(long repositoryId, ApiOptions options); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> [Obsolete("Please use RepositoriesClient.Branch.Get() instead. This method will be removed in a future version")] Task<Branch> GetBranch(string owner, string name, string branchName); /// <summary> /// Gets the specified branch. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details /// </remarks> /// <param name="repositoryId">The Id of the repository</param> /// <param name="branchName">The name of the branch</param> /// <returns>The specified <see cref="T:Octokit.Branch"/></returns> [Obsolete("Please use RepositoriesClient.Branch.Get() instead. This method will be removed in a future version")] Task<Branch> GetBranch(long repositoryId, string branchName); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(string owner, string name, RepositoryUpdate update); /// <summary> /// Updates the specified repository with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The Id of the repository</param> /// <param name="update">New values to update the repository with</param> /// <returns>The updated <see cref="T:Octokit.Repository"/></returns> Task<Repository> Edit(long repositoryId, RepositoryUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="owner">The owner of the repository</param> /// <param name="name">The name of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> [Obsolete("This existing implementation will cease to work when the Branch Protection API preview period ends. Please use the RepositoryBranchesClient methods instead.")] Task<Branch> EditBranch(string owner, string name, string branch, BranchUpdate update); /// <summary> /// Edit the specified branch with the values given in <paramref name="update"/> /// </summary> /// <param name="repositoryId">The Id of the repository</param> /// <param name="branch">The name of the branch</param> /// <param name="update">New values to update the branch with</param> /// <returns>The updated <see cref="T:Octokit.Branch"/></returns> [Obsolete("This existing implementation will cease to work when the Branch Protection API preview period ends. Please use the RepositoryBranchesClient methods instead.")] Task<Branch> EditBranch(long repositoryId, string branch, BranchUpdate update); /// <summary> /// A client for GitHub's Repository Pages API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/pages/">Repository Pages API documentation</a> for more information. /// </remarks> IRepositoryPagesClient Page { get; } /// <summary> /// A client for GitHub's Repository Invitations API. /// </summary> /// <remarks> /// See the <a href="https://developer.github.com/v3/repos/invitations/">Repository Invitations API documentation</a> for more information. /// </remarks> IRepositoryInvitationsClient Invitation { get; } } }
using System; using System.CodeDom; using System.Collections; using System.Xml; namespace Stetic.Wrapper { public class Notebook : Container { ArrayList tabs = new ArrayList (); public override void Wrap (object obj, bool initialized) { base.Wrap (obj, initialized); if (!initialized && AllowPlaceholders) { if (notebook.Children.Length != 0) { // Remove the dummy page Container.Wrap added notebook.Remove (notebook.Children[0]); } InsertPage (0); } notebook.SwitchPage += OnPageChanged; } public override void Dispose () { notebook.SwitchPage -= OnPageChanged; base.Dispose (); } protected override ObjectWrapper ReadChild (ObjectReader reader, XmlElement child_elem) { if ((string)GladeUtils.GetChildProperty (child_elem, "type", "") == "tab") { ObjectWrapper wrapper = reader.ReadObject (child_elem["widget"]); Gtk.Widget widget = (Gtk.Widget)wrapper.Wrapped; notebook.SetTabLabel (notebook.GetNthPage (notebook.NPages - 1), widget); tabs.Add (widget); return wrapper; } else return base.ReadChild (reader, child_elem); } protected override XmlElement WriteChild (ObjectWriter writer, Widget wrapper) { XmlElement child_elem = base.WriteChild (writer, wrapper); if (tabs.Contains (wrapper.Wrapped)) GladeUtils.SetChildProperty (child_elem, "type", "tab"); return child_elem; } public override void Read (ObjectReader reader, XmlElement element) { object cp = GladeUtils.ExtractProperty (element, "CurrentPage", 0); base.Read (reader, element); notebook.CurrentPage = (int) cp; } protected override void GenerateChildBuildCode (GeneratorContext ctx, CodeExpression parentExp, Widget wrapper) { Gtk.Widget child = (Gtk.Widget) wrapper.Wrapped; if (notebook.PageNum (child) == -1) { // It's a tab ctx.Statements.Add (new CodeCommentStatement ("Notebook tab")); Gtk.Widget page = null; CodeExpression pageVar; // Look for the page widget contained in this tab for (int n=0; n < notebook.NPages; n++) { if (notebook.GetTabLabel (notebook.GetNthPage (n)) == child) { page = notebook.GetNthPage (n); break; } } // If the page contains a placeholder, generate a dummy page if (page is Stetic.Placeholder) { CodeVariableDeclarationStatement dvar = new CodeVariableDeclarationStatement ( "Gtk.Label", ctx.NewId (), new CodeObjectCreateExpression ("Gtk.Label") ); ctx.Statements.Add (dvar); ctx.Statements.Add ( new CodeAssignStatement ( new CodePropertyReferenceExpression ( new CodeVariableReferenceExpression (dvar.Name), "Visible" ), new CodePrimitiveExpression (true) ) ); ctx.Statements.Add ( new CodeMethodInvokeExpression ( parentExp, "Add", new CodeVariableReferenceExpression (dvar.Name) ) ); pageVar = new CodeVariableReferenceExpression (dvar.Name); } else pageVar = ctx.WidgetMap.GetWidgetExp (page); // Generate code for the tab CodeExpression var = ctx.GenerateNewInstanceCode (wrapper); // Assign the tab to the page CodeMethodInvokeExpression invoke = new CodeMethodInvokeExpression ( parentExp, "SetTabLabel", pageVar, var ); ctx.Statements.Add (invoke); // Workaround for GTK bug. ShowAll is not propagated to tab labels. invoke = new CodeMethodInvokeExpression ( var, "ShowAll" ); ctx.Statements.Add (invoke); } else base.GenerateChildBuildCode (ctx, parentExp, wrapper); } private Gtk.Notebook notebook { get { return (Gtk.Notebook)Wrapped; } } public override void Select (Gtk.Widget widget) { if (widget != null) { int index = tabs.IndexOf (widget); if (index != -1 && index != notebook.CurrentPage) notebook.CurrentPage = index; } base.Select (widget); } protected override void ReplaceChild (Gtk.Widget oldChild, Gtk.Widget newChild) { int index = tabs.IndexOf (oldChild); if (index != -1) { tabs[index] = newChild; Gtk.Widget page = notebook.GetNthPage (index); notebook.SetTabLabel (page, newChild); } else { Gtk.Widget tab = notebook.GetTabLabel (oldChild); int current = notebook.CurrentPage; base.ReplaceChild (oldChild, newChild); notebook.CurrentPage = current; notebook.SetTabLabel (newChild, tab); Widget ww = Widget.Lookup (tab); if (ww != null) ww.RequiresUndoStatusUpdate = true; } } int InsertPage (int position) { Gtk.Label label = (Gtk.Label)Registry.NewInstance ("Gtk.Label", proj); label.LabelProp = "page" + (notebook.NPages + 1).ToString (); tabs.Insert (position, label); Placeholder ph = CreatePlaceholder (); int i = notebook.InsertPage (ph, label, position); NotifyChildAdded (ph); return i; } internal void PreviousPage () { notebook.PrevPage (); } internal bool CheckPreviousPage () { return notebook.CurrentPage > 0; } internal void NextPage () { notebook.NextPage (); } internal bool CheckNextPage () { return notebook.CurrentPage < notebook.NPages - 1; } internal void DeletePage () { tabs.RemoveAt (notebook.CurrentPage); notebook.RemovePage (notebook.CurrentPage); } internal bool CheckDeletePage () { return notebook.NPages > 0; } internal void SwapPrevious () { object ob = tabs [notebook.CurrentPage]; tabs [notebook.CurrentPage] = tabs [notebook.CurrentPage - 1]; tabs [notebook.CurrentPage - 1] = ob; Gtk.Widget cp = notebook.GetNthPage (notebook.CurrentPage); notebook.ReorderChild (cp, notebook.CurrentPage - 1); } internal void SwapNext () { object ob = tabs [notebook.CurrentPage]; tabs [notebook.CurrentPage] = tabs [notebook.CurrentPage + 1]; tabs [notebook.CurrentPage + 1] = ob; Gtk.Widget cp = notebook.GetNthPage (notebook.CurrentPage); notebook.ReorderChild (cp, notebook.CurrentPage + 1); } internal void InsertBefore () { notebook.CurrentPage = InsertPage (notebook.CurrentPage); } internal bool CheckInsertBefore () { return notebook.NPages > 0; } internal void InsertAfter () { notebook.CurrentPage = InsertPage (notebook.CurrentPage + 1); } public override bool HExpandable { get { foreach (Gtk.Widget w in notebook) { if (ChildHExpandable (w)) return true; } return false; } } public override bool VExpandable { get { foreach (Gtk.Widget w in notebook) { if (ChildVExpandable (w)) return true; } return false; } } void OnPageChanged (object s, Gtk.SwitchPageArgs args) { EmitNotify ("CurrentPage"); } } }
// 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.Diagnostics.Contracts; using System.Runtime; using System.Threading.Tasks; using System.ServiceModel.Diagnostics; namespace System.ServiceModel.Channels { public abstract class CommunicationObject : ICommunicationObject, IAsyncCommunicationObject { private bool _aborted; private bool _closeCalled; private object _mutex; private bool _onClosingCalled; private bool _onClosedCalled; private bool _onOpeningCalled; private bool _onOpenedCalled; private bool _raisedClosed; private bool _raisedClosing; private bool _raisedFaulted; private bool _traceOpenAndClose; private object _eventSender; private CommunicationState _state; protected CommunicationObject() : this(new object()) { } protected CommunicationObject(object mutex) { _mutex = mutex; _eventSender = this; _state = CommunicationState.Created; } internal bool Aborted { get { return _aborted; } } internal object EventSender { get { return _eventSender; } set { _eventSender = value; } } protected bool IsDisposed { get { return _state == CommunicationState.Closed; } } public CommunicationState State { get { return _state; } } protected object ThisLock { get { return _mutex; } } protected abstract TimeSpan DefaultCloseTimeout { get; } protected abstract TimeSpan DefaultOpenTimeout { get; } internal TimeSpan InternalCloseTimeout { get { return this.DefaultCloseTimeout; } } internal TimeSpan InternalOpenTimeout { get { return this.DefaultOpenTimeout; } } public event EventHandler Closed; public event EventHandler Closing; public event EventHandler Faulted; public event EventHandler Opened; public event EventHandler Opening; public void Abort() { lock (ThisLock) { if (_aborted || _state == CommunicationState.Closed) return; _aborted = true; _state = CommunicationState.Closing; } try { OnClosing(); if (!_onClosingCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); OnAbort(); OnClosed(); if (!_onClosedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } finally { } } public IAsyncResult BeginClose(AsyncCallback callback, object state) { return this.BeginClose(this.DefaultCloseTimeout, callback, state); } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return CloseAsyncInternal(timeout).ToApm(callback, state); } public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return this.BeginOpen(this.DefaultOpenTimeout, callback, state); } public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return OpenAsyncInternal(timeout).ToApm(callback, state); } public void Close() { this.Close(this.DefaultCloseTimeout); } public void Close(TimeSpan timeout) { CloseAsyncInternal(timeout).WaitForCompletion(); } private async Task CloseAsyncInternal(TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await ((IAsyncCommunicationObject)this).CloseAsync(timeout); } async Task IAsyncCommunicationObject.CloseAsync(TimeSpan timeout) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SRServiceModel.SFxTimeoutOutOfRange0)); CommunicationState originalState; lock (ThisLock) { originalState = _state; if (originalState != CommunicationState.Closed) _state = CommunicationState.Closing; _closeCalled = true; } switch (originalState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: this.Abort(); if (originalState == CommunicationState.Faulted) { throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); } break; case CommunicationState.Opened: { bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnClosing(); if (!_onClosingCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); await OnCloseAsync(actualTimeout.RemainingTime()); OnClosed(); if (!_onClosedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); throwing = false; } finally { if (throwing) { Abort(); } } break; } case CommunicationState.Closing: case CommunicationState.Closed: break; default: throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState"); } } private Exception CreateNotOpenException() { return new InvalidOperationException(string.Format(SRServiceModel.CommunicationObjectCannotBeUsed, this.GetCommunicationObjectType().ToString(), _state.ToString())); } private Exception CreateImmutableException() { return new InvalidOperationException(string.Format(SRServiceModel.CommunicationObjectCannotBeModifiedInState, this.GetCommunicationObjectType().ToString(), _state.ToString())); } private Exception CreateBaseClassMethodNotCalledException(string method) { return new InvalidOperationException(string.Format(SRServiceModel.CommunicationObjectBaseClassMethodNotCalled, this.GetCommunicationObjectType().ToString(), method)); } internal Exception CreateClosedException() { if (!_closeCalled) { return CreateAbortedException(); } else { return new ObjectDisposedException(this.GetCommunicationObjectType().ToString()); } } internal Exception CreateFaultedException() { string message = string.Format(SRServiceModel.CommunicationObjectFaulted1, this.GetCommunicationObjectType().ToString()); return new CommunicationObjectFaultedException(message); } internal Exception CreateAbortedException() { return new CommunicationObjectAbortedException(string.Format(SRServiceModel.CommunicationObjectAborted1, this.GetCommunicationObjectType().ToString())); } internal bool DoneReceivingInCurrentState() { this.ThrowPending(); switch (_state) { case CommunicationState.Created: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opened: return false; case CommunicationState.Closing: return true; case CommunicationState.Closed: return true; case CommunicationState.Faulted: return true; default: throw Fx.AssertAndThrow("DoneReceivingInCurrentState: Unknown CommunicationObject.state"); } } public void EndClose(IAsyncResult result) { result.ToApmEnd(); } public void EndOpen(IAsyncResult result) { result.ToApmEnd(); } protected void Fault() { lock (ThisLock) { if (_state == CommunicationState.Closed || _state == CommunicationState.Closing) return; if (_state == CommunicationState.Faulted) return; _state = CommunicationState.Faulted; } OnFaulted(); } public void Open() { this.Open(this.DefaultOpenTimeout); } public void Open(TimeSpan timeout) { OpenAsyncInternal(timeout).WaitForCompletion(); } private async Task OpenAsyncInternal(TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await ((IAsyncCommunicationObject)this).OpenAsync(timeout); } async Task IAsyncCommunicationObject.OpenAsync(TimeSpan timeout) { if (timeout < TimeSpan.Zero) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SRServiceModel.SFxTimeoutOutOfRange0)); lock (ThisLock) { ThrowIfDisposedOrImmutable(); _state = CommunicationState.Opening; } bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnOpening(); if (!_onOpeningCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpening"), Guid.Empty, this); TimeSpan remainingTime = actualTimeout.RemainingTime(); await OnOpenAsync(remainingTime); OnOpened(); if (!_onOpenedCalled) throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnOpened"), Guid.Empty, this); throwing = false; } finally { if (throwing) { Fault(); } } } protected virtual void OnClosed() { _onClosedCalled = true; lock (ThisLock) { if (_raisedClosed) return; _raisedClosed = true; _state = CommunicationState.Closed; } EventHandler handler = Closed; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnClosing() { _onClosingCalled = true; lock (ThisLock) { if (_raisedClosing) return; _raisedClosing = true; } EventHandler handler = Closing; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnFaulted() { lock (ThisLock) { if (_raisedFaulted) return; _raisedFaulted = true; } EventHandler handler = Faulted; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnOpened() { _onOpenedCalled = true; lock (ThisLock) { if (_aborted || _state != CommunicationState.Opening) return; _state = CommunicationState.Opened; } EventHandler handler = Opened; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } protected virtual void OnOpening() { _onOpeningCalled = true; EventHandler handler = Opening; if (handler != null) { try { handler(_eventSender, EventArgs.Empty); } catch (Exception exception) { if (Fx.IsFatal(exception)) throw; throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(exception); } } } internal void ThrowIfFaulted() { this.ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: break; case CommunicationState.Closing: break; case CommunicationState.Closed: break; case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfFaulted: Unknown CommunicationObject.state"); } } internal void ThrowIfAborted() { if (_aborted && !_closeCalled) { throw TraceUtility.ThrowHelperError(CreateAbortedException(), Guid.Empty, this); } } internal bool TraceOpenAndClose { get { return _traceOpenAndClose; } set { _traceOpenAndClose = value && DiagnosticUtility.ShouldUseActivity; } } internal void ThrowIfClosed() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: break; case CommunicationState.Closing: break; case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfClosed: Unknown CommunicationObject.state"); } } protected virtual Type GetCommunicationObjectType() { return this.GetType(); } protected internal void ThrowIfDisposed() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: break; case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfDisposed: Unknown CommunicationObject.state"); } } internal void ThrowIfClosedOrOpened() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: break; case CommunicationState.Opened: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfClosedOrOpened: Unknown CommunicationObject.state"); } } protected internal void ThrowIfDisposedOrImmutable() { ThrowPending(); switch (_state) { case CommunicationState.Created: break; case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Opened: throw TraceUtility.ThrowHelperError(this.CreateImmutableException(), Guid.Empty, this); case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfDisposedOrImmutable: Unknown CommunicationObject.state"); } } protected internal void ThrowIfDisposedOrNotOpen() { ThrowPending(); switch (_state) { case CommunicationState.Created: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opened: break; case CommunicationState.Closing: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfDisposedOrNotOpen: Unknown CommunicationObject.state"); } } internal void ThrowIfNotOpened() { if (_state == CommunicationState.Created || _state == CommunicationState.Opening) throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); } internal void ThrowIfClosedOrNotOpen() { ThrowPending(); switch (_state) { case CommunicationState.Created: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opening: throw TraceUtility.ThrowHelperError(this.CreateNotOpenException(), Guid.Empty, this); case CommunicationState.Opened: break; case CommunicationState.Closing: break; case CommunicationState.Closed: throw TraceUtility.ThrowHelperError(this.CreateClosedException(), Guid.Empty, this); case CommunicationState.Faulted: throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); default: throw Fx.AssertAndThrow("ThrowIfClosedOrNotOpen: Unknown CommunicationObject.state"); } } internal void ThrowPending() { } // // State callbacks // protected abstract void OnAbort(); protected abstract void OnClose(TimeSpan timeout); protected abstract IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state); protected abstract void OnEndClose(IAsyncResult result); protected abstract void OnOpen(TimeSpan timeout); protected abstract IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state); protected abstract void OnEndOpen(IAsyncResult result); internal protected virtual Task OnCloseAsync(TimeSpan timeout) { Contract.Requires(false, "OnCloseAsync needs to be implemented on derived classes"); return TaskHelpers.CompletedTask(); } internal protected virtual Task OnOpenAsync(TimeSpan timeout) { Contract.Requires(false, "OnOpenAsync needs to be implemented on derived classes"); return TaskHelpers.CompletedTask(); } } // This helper class exists to expose non-contract API's to other ServiceModel projects public static class CommunicationObjectInternal { public static void ThrowIfClosed(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfClosed(); } public static void ThrowIfClosedOrOpened(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfClosedOrOpened(); } public static void ThrowIfDisposedOrNotOpen(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfDisposedOrNotOpen(); } public static void ThrowIfDisposed(CommunicationObject communicationObject) { Contract.Assert(communicationObject != null); communicationObject.ThrowIfDisposed(); } public static TimeSpan GetInternalCloseTimeout(this CommunicationObject communicationObject) { return communicationObject.InternalCloseTimeout; } public static void OnClose(CommunicationObject communicationObject, TimeSpan timeout) { OnCloseAsyncInternal(communicationObject, timeout).WaitForCompletion(); } public static IAsyncResult OnBeginClose(CommunicationObject communicationObject, TimeSpan timeout, AsyncCallback callback, object state) { return communicationObject.OnCloseAsync(timeout).ToApm(callback, state); } public static void OnEnd(IAsyncResult result) { result.ToApmEnd(); } public static void OnOpen(CommunicationObject communicationObject, TimeSpan timeout) { OnOpenAsyncInternal(communicationObject, timeout).WaitForCompletion(); } public static IAsyncResult OnBeginOpen(CommunicationObject communicationObject, TimeSpan timeout, AsyncCallback callback, object state) { return communicationObject.OnOpenAsync(timeout).ToApm(callback, state); } public static async Task OnCloseAsyncInternal(CommunicationObject communicationObject, TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await communicationObject.OnCloseAsync(timeout); } public static async Task OnOpenAsyncInternal(CommunicationObject communicationObject, TimeSpan timeout) { await TaskHelpers.EnsureDefaultTaskScheduler(); await communicationObject.OnOpenAsync(timeout); } } }
namespace XenAdmin.Wizards.NewSRWizard_Pages.Frontends { partial class NetApp { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NetApp)); this.nudFlexvols = new System.Windows.Forms.NumericUpDown(); this.labelFlexvols = new System.Windows.Forms.Label(); this.toolTipContainerDedup = new XenAdmin.Controls.ToolTipContainer(); this.checkBoxDedup = new System.Windows.Forms.CheckBox(); this.checkBoxThin = new System.Windows.Forms.CheckBox(); this.checkBoxHttps = new System.Windows.Forms.CheckBox(); this.labelPort = new System.Windows.Forms.Label(); this.helplinkFlexvols = new System.Windows.Forms.LinkLabel(); this.textBoxPort = new System.Windows.Forms.TextBox(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.colAggregate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colSize = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colDisks = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colRaidType = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAsis = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.listBoxSRs = new XenAdmin.Controls.SRListBox(); this.radioButtonNew = new System.Windows.Forms.RadioButton(); this.radioButtonReattach = new System.Windows.Forms.RadioButton(); this.panel1 = new System.Windows.Forms.Panel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); ((System.ComponentModel.ISupportInitialize)(this.nudFlexvols)).BeginInit(); this.toolTipContainerDedup.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.panel1.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // nudFlexvols // resources.ApplyResources(this.nudFlexvols, "nudFlexvols"); this.nudFlexvols.Maximum = new decimal(new int[] { 32, 0, 0, 0}); this.nudFlexvols.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.nudFlexvols.Name = "nudFlexvols"; this.nudFlexvols.Value = new decimal(new int[] { 8, 0, 0, 0}); // // labelFlexvols // resources.ApplyResources(this.labelFlexvols, "labelFlexvols"); this.labelFlexvols.Name = "labelFlexvols"; // // toolTipContainerDedup // resources.ApplyResources(this.toolTipContainerDedup, "toolTipContainerDedup"); this.toolTipContainerDedup.Controls.Add(this.checkBoxDedup); this.toolTipContainerDedup.Name = "toolTipContainerDedup"; // // checkBoxDedup // resources.ApplyResources(this.checkBoxDedup, "checkBoxDedup"); this.checkBoxDedup.Name = "checkBoxDedup"; this.checkBoxDedup.UseVisualStyleBackColor = true; // // checkBoxThin // resources.ApplyResources(this.checkBoxThin, "checkBoxThin"); this.checkBoxThin.Name = "checkBoxThin"; this.checkBoxThin.UseVisualStyleBackColor = true; this.checkBoxThin.CheckedChanged += new System.EventHandler(this.checkBoxThin_CheckedChanged); // // checkBoxHttps // resources.ApplyResources(this.checkBoxHttps, "checkBoxHttps"); this.checkBoxHttps.Name = "checkBoxHttps"; this.checkBoxHttps.UseVisualStyleBackColor = true; this.checkBoxHttps.CheckedChanged += new System.EventHandler(this.checkBoxHttps_CheckedChanged); // // labelPort // resources.ApplyResources(this.labelPort, "labelPort"); this.labelPort.Name = "labelPort"; // // helplinkFlexvols // resources.ApplyResources(this.helplinkFlexvols, "helplinkFlexvols"); this.helplinkFlexvols.Name = "helplinkFlexvols"; this.helplinkFlexvols.TabStop = true; this.helplinkFlexvols.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.helplinkFlexvols_LinkClicked); // // textBoxPort // resources.ApplyResources(this.textBoxPort, "textBoxPort"); this.textBoxPort.Name = "textBoxPort"; this.textBoxPort.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBoxPort_KeyDown); this.textBoxPort.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxPort_KeyPress); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToResizeRows = false; resources.ApplyResources(this.dataGridView1, "dataGridView1"); this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colAggregate, this.colSize, this.colDisks, this.colRaidType, this.colAsis}); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged); // // colAggregate // this.colAggregate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.colAggregate, "colAggregate"); this.colAggregate.Name = "colAggregate"; this.colAggregate.ReadOnly = true; // // colSize // this.colSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.colSize, "colSize"); this.colSize.Name = "colSize"; this.colSize.ReadOnly = true; // // colDisks // this.colDisks.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.colDisks, "colDisks"); this.colDisks.Name = "colDisks"; this.colDisks.ReadOnly = true; // // colRaidType // this.colRaidType.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.colRaidType, "colRaidType"); this.colRaidType.Name = "colRaidType"; this.colRaidType.ReadOnly = true; // // colAsis // this.colAsis.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.colAsis, "colAsis"); this.colAsis.Name = "colAsis"; this.colAsis.ReadOnly = true; // // listBoxSRs // resources.ApplyResources(this.listBoxSRs, "listBoxSRs"); this.listBoxSRs.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.listBoxSRs.FormattingEnabled = true; this.listBoxSRs.Name = "listBoxSRs"; this.listBoxSRs.Sorted = true; this.listBoxSRs.SelectedIndexChanged += new System.EventHandler(this.listBoxSRs_SelectedIndexChanged); // // radioButtonNew // resources.ApplyResources(this.radioButtonNew, "radioButtonNew"); this.radioButtonNew.Name = "radioButtonNew"; this.radioButtonNew.TabStop = true; this.radioButtonNew.UseVisualStyleBackColor = true; this.radioButtonNew.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // radioButtonReattach // resources.ApplyResources(this.radioButtonReattach, "radioButtonReattach"); this.radioButtonReattach.Name = "radioButtonReattach"; this.radioButtonReattach.TabStop = true; this.radioButtonReattach.UseVisualStyleBackColor = true; this.radioButtonReattach.CheckedChanged += new System.EventHandler(this.radioButton_CheckedChanged); // // panel1 // this.panel1.Controls.Add(this.nudFlexvols); this.panel1.Controls.Add(this.labelFlexvols); this.panel1.Controls.Add(this.checkBoxThin); this.panel1.Controls.Add(this.toolTipContainerDedup); this.panel1.Controls.Add(this.checkBoxHttps); this.panel1.Controls.Add(this.textBoxPort); this.panel1.Controls.Add(this.labelPort); this.panel1.Controls.Add(this.helplinkFlexvols); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.radioButtonReattach, 0, 0); this.tableLayoutPanel1.Controls.Add(this.listBoxSRs, 0, 1); this.tableLayoutPanel1.Controls.Add(this.radioButtonNew, 0, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 3); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 4); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // NetApp // this.Controls.Add(this.tableLayoutPanel1); this.Name = "NetApp"; resources.ApplyResources(this, "$this"); ((System.ComponentModel.ISupportInitialize)(this.nudFlexvols)).EndInit(); this.toolTipContainerDedup.ResumeLayout(false); this.toolTipContainerDedup.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.NumericUpDown nudFlexvols; private System.Windows.Forms.Label labelFlexvols; private XenAdmin.Controls.ToolTipContainer toolTipContainerDedup; private System.Windows.Forms.CheckBox checkBoxDedup; private System.Windows.Forms.CheckBox checkBoxThin; private System.Windows.Forms.Label labelPort; private System.Windows.Forms.CheckBox checkBoxHttps; private System.Windows.Forms.LinkLabel helplinkFlexvols; private System.Windows.Forms.TextBox textBoxPort; private System.Windows.Forms.DataGridView dataGridView1; private XenAdmin.Controls.SRListBox listBoxSRs; private System.Windows.Forms.RadioButton radioButtonNew; private System.Windows.Forms.RadioButton radioButtonReattach; private System.Windows.Forms.DataGridViewTextBoxColumn colAggregate; private System.Windows.Forms.DataGridViewTextBoxColumn colSize; private System.Windows.Forms.DataGridViewTextBoxColumn colDisks; private System.Windows.Forms.DataGridViewTextBoxColumn colRaidType; private System.Windows.Forms.DataGridViewTextBoxColumn colAsis; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using gcoc = Google.Cloud.OsLogin.Common; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.OsLogin.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedOsLoginServiceClientTest { [xunit::FactAttribute] public void DeletePosixAccountRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeletePosixAccount(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePosixAccountRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePosixAccountAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePosixAccountAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePosixAccount() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeletePosixAccount(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePosixAccountAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePosixAccountAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePosixAccountAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePosixAccountResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeletePosixAccount(request.PosixAccountName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePosixAccountResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = gcoc::PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePosixAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeletePosixAccountAsync(request.PosixAccountName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePosixAccountAsync(request.PosixAccountName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeleteSshPublicKey(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSshPublicKeyAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSshPublicKey() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeleteSshPublicKey(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSshPublicKeyAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSshPublicKeyAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteSshPublicKeyResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); client.DeleteSshPublicKey(request.SshPublicKeyName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteSshPublicKeyResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetLoginProfileRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), ProjectId = "project_id43ad98b0", SystemId = "system_id43548ac1", }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile response = client.GetLoginProfile(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetLoginProfileRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), ProjectId = "project_id43ad98b0", SystemId = "system_id43548ac1", }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetLoginProfile() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile response = client.GetLoginProfile(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetLoginProfileAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetLoginProfileResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile response = client.GetLoginProfile(request.UserName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetLoginProfileResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = gcoc::UserName.FromUser("[USER]"), }; LoginProfile expectedResponse = new LoginProfile { Name = "name1c9368b0", PosixAccounts = { new gcoc::PosixAccount(), }, SshPublicKeys = { { "key8a0b6e3c", new gcoc::SshPublicKey() }, }, }; mockGrpcClient.Setup(x => x.GetLoginProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<LoginProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); LoginProfile responseCallSettings = await client.GetLoginProfileAsync(request.UserName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); LoginProfile responseCancellationToken = await client.GetLoginProfileAsync(request.UserName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.GetSshPublicKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSshPublicKey() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.GetSshPublicKey(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSshPublicKeyAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSshPublicKeyResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.GetSshPublicKey(request.SshPublicKeyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSshPublicKeyResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.GetSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.GetSshPublicKeyAsync(request.SshPublicKeyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey1() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey1Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey1ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey1ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey2() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.Parent, request.SshPublicKey, request.ProjectId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey2Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.Parent, request.SshPublicKey, request.ProjectId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ImportSshPublicKey2ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse response = client.ImportSshPublicKey(request.ParentAsUserName, request.SshPublicKey, request.ProjectId); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ImportSshPublicKey2ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = gcoc::UserName.FromUser("[USER]"), SshPublicKey = new gcoc::SshPublicKey(), ProjectId = "project_id43ad98b0", }; ImportSshPublicKeyResponse expectedResponse = new ImportSshPublicKeyResponse { LoginProfile = new LoginProfile(), }; mockGrpcClient.Setup(x => x.ImportSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ImportSshPublicKeyResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); ImportSshPublicKeyResponse responseCallSettings = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ImportSshPublicKeyResponse responseCancellationToken = await client.ImportSshPublicKeyAsync(request.ParentAsUserName, request.SshPublicKey, request.ProjectId, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKeyRequestObject() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKeyRequestObjectAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey1() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey1Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey1ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey1ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey2() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.Name, request.SshPublicKey, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey2Async() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.Name, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateSshPublicKey2ResourceNames() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKey(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey response = client.UpdateSshPublicKey(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateSshPublicKey2ResourceNamesAsync() { moq::Mock<OsLoginService.OsLoginServiceClient> mockGrpcClient = new moq::Mock<OsLoginService.OsLoginServiceClient>(moq::MockBehavior.Strict); UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new gcoc::SshPublicKey(), UpdateMask = new wkt::FieldMask(), }; gcoc::SshPublicKey expectedResponse = new gcoc::SshPublicKey { Key = "key8a0b6e3c", ExpirationTimeUsec = -3860803259883837145L, Fingerprint = "fingerprint009e6052", SshPublicKeyName = gcoc::SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; mockGrpcClient.Setup(x => x.UpdateSshPublicKeyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gcoc::SshPublicKey>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OsLoginServiceClient client = new OsLoginServiceClientImpl(mockGrpcClient.Object, null); gcoc::SshPublicKey responseCallSettings = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gcoc::SshPublicKey responseCancellationToken = await client.UpdateSshPublicKeyAsync(request.SshPublicKeyName, request.SshPublicKey, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentDictionaryTests { [Fact] public static void TestBasicScenarios() { ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>(); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { var ret = cd.TryAdd(1, 11); if (!ret) { ret = cd.TryUpdate(1, 11, 111); Assert.True(ret); } ret = cd.TryAdd(2, 22); if (!ret) { ret = cd.TryUpdate(2, 22, 222); Assert.True(ret); } }); tks[1] = Task.Run(() => { var ret = cd.TryAdd(2, 222); if (!ret) { ret = cd.TryUpdate(2, 222, 22); Assert.True(ret); } ret = cd.TryAdd(1, 111); if (!ret) { ret = cd.TryUpdate(1, 111, 11); Assert.True(ret); } }); Task.WaitAll(tks); } [Fact] public static void TestAdd1() { TestAdd1(1, 1, 1, 10000); TestAdd1(5, 1, 1, 10000); TestAdd1(1, 1, 2, 5000); TestAdd1(1, 1, 5, 2000); TestAdd1(4, 0, 4, 2000); TestAdd1(16, 31, 4, 2000); TestAdd1(64, 5, 5, 5000); TestAdd1(5, 5, 5, 2500); } private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread) { ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1); IDictionary<int, int> dict = dictConcurrent; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread)); } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); int itemCount = threads * addsPerThread; for (int i = 0; i < itemCount; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine + "TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread) ); } // Finally, let's verify that the count is reported correctly. int expectedCount = threads * addsPerThread; Assert.Equal(expectedCount, dict.Count); Assert.Equal(expectedCount, dictConcurrent.ToArray().Length); } [Fact] public static void TestUpdate1() { TestUpdate1(1, 1, 10000); TestUpdate1(5, 1, 10000); TestUpdate1(1, 2, 5000); TestUpdate1(1, 5, 2001); TestUpdate1(4, 4, 2001); TestUpdate1(15, 5, 2001); TestUpdate1(64, 5, 5000); TestUpdate1(5, 5, 25000); } private static void TestUpdate1(int cLevel, int threads, int updatesPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 1; i <= updatesPerThread; i++) dict[i] = i; int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 1; j <= updatesPerThread; j++) { dict[j] = (ii + 2) * j; } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { var div = pair.Value / pair.Key; var rem = pair.Value % pair.Key; Assert.Equal(0, rem); Assert.True(div > 1 && div <= threads + 1, String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div)); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 1; i <= updatesPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine + "TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread) ); } } [Fact] public static void TestRead1() { TestRead1(1, 1, 10000); TestRead1(5, 1, 10000); TestRead1(1, 2, 5000); TestRead1(1, 5, 2001); TestRead1(4, 4, 2001); TestRead1(15, 5, 2001); TestRead1(64, 5, 5000); TestRead1(5, 5, 25000); } private static void TestRead1(int cLevel, int threads, int readsPerThread) { IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); for (int i = 0; i < readsPerThread; i += 2) dict[i] = i; int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < readsPerThread; j++) { int val = 0; if (dict.TryGetValue(j, out val)) { Assert.Equal(0, j % 2); Assert.Equal(j, val); } else { Assert.Equal(1, j % 2); } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } } [Fact] public static void TestRemove1() { TestRemove1(1, 1, 10000); TestRemove1(5, 1, 1000); TestRemove1(1, 5, 2001); TestRemove1(4, 4, 2001); TestRemove1(15, 5, 2001); TestRemove1(64, 5, 5000); } private static void TestRemove1(int cLevel, int threads, int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread); int N = 2 * threads * removesPerThread; for (int i = 0; i < N; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys int running = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < removesPerThread; j++) { int value; int key = 2 * (ii + j * threads); Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters); Assert.Equal(-key, value); } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < (threads * removesPerThread); i++) expectKeys.Add(2 * i + 1); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters); } // Finally, let's verify that the count is reported correctly. Assert.Equal(expectKeys.Count, dict.Count); Assert.Equal(expectKeys.Count, dict.ToArray().Length); } [Fact] public static void TestRemove2() { TestRemove2(1); TestRemove2(10); TestRemove2(5000); } private static void TestRemove2(int removesPerThread) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); for (int i = 0; i < removesPerThread; i++) dict[i] = -i; // The dictionary contains keys [0..N), each key mapped to a value equal to the key. // Threads will cooperatively remove all even keys. const int SIZE = 2; int running = SIZE; bool[][] seen = new bool[SIZE][]; for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread]; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int t = 0; t < SIZE; t++) { int thread = t; Task.Run( () => { for (int key = 0; key < removesPerThread; key++) { int value; if (dict.TryRemove(key, out value)) { seen[thread][key] = true; Assert.Equal(-key, value); } } if (Interlocked.Decrement(ref running) == 0) mre.Set(); }); } mre.WaitOne(); } Assert.Equal(0, dict.Count); for (int i = 0; i < removesPerThread; i++) { Assert.False(seen[0][i] == seen[1][i], String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread) ); } } [Fact] public static void TestRemove3() { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(); dict[99] = -99; ICollection<KeyValuePair<int, int>> col = dict; // Make sure we cannot "remove" a key/value pair which is not in the dictionary for (int i = 0; i < 200; i++) { if (i != 99) { Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)"); Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)"); } } // Can we remove a key/value pair successfully? Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair"); // Make sure the key/value pair is gone Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed"); // And that the dictionary is empty. We will check the count in a few different ways: Assert.Equal(0, dict.Count); Assert.Equal(0, dict.ToArray().Length); } [Fact] public static void TestGetOrAdd() { TestGetOrAddOrUpdate(1, 1, 1, 10000, true); TestGetOrAddOrUpdate(5, 1, 1, 10000, true); TestGetOrAddOrUpdate(1, 1, 2, 5000, true); TestGetOrAddOrUpdate(1, 1, 5, 2000, true); TestGetOrAddOrUpdate(4, 0, 4, 2000, true); TestGetOrAddOrUpdate(16, 31, 4, 2000, true); TestGetOrAddOrUpdate(64, 5, 5, 5000, true); TestGetOrAddOrUpdate(5, 5, 5, 25000, true); } [Fact] public static void TestAddOrUpdate() { TestGetOrAddOrUpdate(1, 1, 1, 10000, false); TestGetOrAddOrUpdate(5, 1, 1, 10000, false); TestGetOrAddOrUpdate(1, 1, 2, 5000, false); TestGetOrAddOrUpdate(1, 1, 5, 2000, false); TestGetOrAddOrUpdate(4, 0, 4, 2000, false); TestGetOrAddOrUpdate(16, 31, 4, 2000, false); TestGetOrAddOrUpdate(64, 5, 5, 5000, false); TestGetOrAddOrUpdate(5, 5, 5, 25000, false); } private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd) { ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1); int count = threads; using (ManualResetEvent mre = new ManualResetEvent(false)) { for (int i = 0; i < threads; i++) { int ii = i; Task.Run( () => { for (int j = 0; j < addsPerThread; j++) { if (isAdd) { //call either of the two overloads of GetOrAdd if (j + ii % 2 == 0) { dict.GetOrAdd(j, -j); } else { dict.GetOrAdd(j, x => -x); } } else { if (j + ii % 2 == 0) { dict.AddOrUpdate(j, -j, (k, v) => -j); } else { dict.AddOrUpdate(j, (k) => -k, (k, v) => -k); } } } if (Interlocked.Decrement(ref count) == 0) mre.Set(); }); } mre.WaitOne(); } foreach (var pair in dict) { Assert.Equal(pair.Key, -pair.Value); } List<int> gotKeys = new List<int>(); foreach (var pair in dict) gotKeys.Add(pair.Key); gotKeys.Sort(); List<int> expectKeys = new List<int>(); for (int i = 0; i < addsPerThread; i++) expectKeys.Add(i); Assert.Equal(expectKeys.Count, gotKeys.Count); for (int i = 0; i < expectKeys.Count; i++) { Assert.True(expectKeys[i].Equals(gotKeys[i]), String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine + "> FAILED. The set of keys in the dictionary is are not the same as the expected.", cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate")); } // Finally, let's verify that the count is reported correctly. Assert.Equal(addsPerThread, dict.Count); Assert.Equal(addsPerThread, dict.ToArray().Length); } [Fact] public static void TestBugFix669376() { var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer()); cd["test"] = 10; Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work"); } private class OrdinalStringComparer : IEqualityComparer<string> { public bool Equals(string x, string y) { var xlower = x.ToLowerInvariant(); var ylower = y.ToLowerInvariant(); return string.CompareOrdinal(xlower, ylower) == 0; } public int GetHashCode(string obj) { return 0; } } [Fact] public static void TestConstructor() { var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }); Assert.False(dictionary.IsEmpty); Assert.Equal(1, dictionary.Keys.Count); Assert.Equal(1, dictionary.Values.Count); } [Fact] public static void TestDebuggerAttributes() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>()); } [Fact] public static void TestConstructor_Negative() { Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) })); // "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed"); Assert.Throws<ArgumentException>( () => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) })); // "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed"); Assert.Throws<ArgumentNullException>( () => new ConcurrentDictionary<int, int>(1, 1, null)); // "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(0, 10)); // "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed"); Assert.Throws<ArgumentOutOfRangeException>( () => new ConcurrentDictionary<int, int>(-1, 0)); // "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed"); } [Fact] public static void TestExceptions() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryAdd(null, 0)); // "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.ContainsKey(null)); // "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed"); int item; Assert.Throws<ArgumentNullException>( () => dictionary.TryRemove(null, out item)); // "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.TryGetValue(null, out item)); // "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => { var x = dictionary[null]; }); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<KeyNotFoundException>( () => { var x = dictionary["1"]; }); // "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 1); // "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, (k) => 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd("1", null)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.GetOrAdd(null, 0)); // "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate("1", null, (k, v) => 0)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.AddOrUpdate(null, (k) => 0, null)); // "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed"); dictionary.TryAdd("1", 1); Assert.Throws<ArgumentException>( () => ((IDictionary<string, int>)dictionary).Add("1", 2)); // "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed"); } [Fact] public static void TestIDictionary() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.False(dictionary.IsReadOnly); // Empty dictionary should not enumerate Assert.Empty(dictionary); const int SIZE = 10; for (int i = 0; i < SIZE; i++) dictionary.Add(i.ToString(), i); Assert.Equal(SIZE, dictionary.Count); //test contains Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain returned true for incorrect key type"); Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain returned true for incorrect key"); Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain returned false for correct key"); //test GetEnumerator int count = 0; foreach (var obj in dictionary) { DictionaryEntry entry = (DictionaryEntry)obj; string key = (string)entry.Key; int value = (int)entry.Value; int expectedValue = int.Parse(key); Assert.True(value == expectedValue, String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue)); count++; } Assert.Equal(SIZE, count); Assert.Equal(SIZE, dictionary.Keys.Count); Assert.Equal(SIZE, dictionary.Values.Count); //Test Remove dictionary.Remove("9"); Assert.Equal(SIZE - 1, dictionary.Count); //Test this[] for (int i = 0; i < dictionary.Count; i++) Assert.Equal(i, (int)dictionary[i.ToString()]); dictionary["1"] = 100; // try a valid setter Assert.Equal(100, (int)dictionary["1"]); //nonsexist key Assert.Null(dictionary["NotAKey"]); } [Fact] public static void TestIDictionary_Negative() { IDictionary dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.Add(null, 1)); // "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed"); Assert.Throws<ArgumentException>( () => dictionary.Add(1, 1)); // "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed"); Assert.Throws<ArgumentException>( () => dictionary.Add("1", "1")); // "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed"); Assert.Throws<ArgumentNullException>( () => dictionary.Contains(null)); // "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed"); //Test Remove Assert.Throws<ArgumentNullException>( () => dictionary.Remove(null)); // "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed"); //Test this[] Assert.Throws<ArgumentNullException>( () => { object val = dictionary[null]; }); // "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentNullException>( () => dictionary[null] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed"); Assert.Throws<ArgumentException>( () => dictionary[1] = 0); // "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed"); Assert.Throws<ArgumentException>( () => dictionary["1"] = "0"); // "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed"); } [Fact] public static void IDicionary_Remove_NullKeyInKeyValuePair_ThrowsArgumentNullException() { IDictionary<string, int> dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>(() => dictionary.Remove(new KeyValuePair<string, int>(null, 0))); } [Fact] public static void TestICollection() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); int key = -1; int value = +1; //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value); var objectArray = new Object[1]; dictionary.CopyTo(objectArray, 0); Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key); Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value); var keyValueArray = new KeyValuePair<int, int>[1]; dictionary.CopyTo(keyValueArray, 0); Assert.Equal(key, keyValueArray[0].Key); Assert.Equal(value, keyValueArray[0].Value); var entryArray = new DictionaryEntry[1]; dictionary.CopyTo(entryArray, 0); Assert.Equal(key, (int)entryArray[0].Key); Assert.Equal(value, (int)entryArray[0].Value); } [Fact] public static void TestICollection_Negative() { ICollection dictionary = new ConcurrentDictionary<int, int>(); Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!"); Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; }); // "TestICollection: FAILED. SyncRoot property didn't throw"); Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0)); // "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed"); Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1)); // "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed"); //add one item to the dictionary ((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1); Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0)); // "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count"); } [Fact] public static void TestClear() { var dictionary = new ConcurrentDictionary<int, int>(); for (int i = 0; i < 10; i++) dictionary.TryAdd(i, i); Assert.Equal(10, dictionary.Count); dictionary.Clear(); Assert.Equal(0, dictionary.Count); int item; Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear"); Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear"); } [Fact] public static void TestTryUpdate() { var dictionary = new ConcurrentDictionary<string, int>(); Assert.Throws<ArgumentNullException>( () => dictionary.TryUpdate(null, 0, 0)); // "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed"); for (int i = 0; i < 10; i++) dictionary.TryAdd(i.ToString(), i); for (int i = 0; i < 10; i++) { Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!"); Assert.Equal(i + 1, dictionary[i.ToString()]); } //test TryUpdate concurrently dictionary.Clear(); for (int i = 0; i < 1000; i++) dictionary.TryAdd(i.ToString(), i); var mres = new ManualResetEventSlim(); Task[] tasks = new Task[10]; ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true); for (int i = 0; i < tasks.Length; i++) { // We are creating the Task using TaskCreationOptions.LongRunning because... // there is no guarantee that the Task will be created on another thread. // There is also no guarantee that using this TaskCreationOption will force // it to be run on another thread. tasks[i] = Task.Factory.StartNew((obj) => { mres.Wait(); int index = (((int)obj) + 1) + 1000; updatedKeys.Value = new ThreadData(); updatedKeys.Value.ThreadIndex = index; for (int j = 0; j < dictionary.Count; j++) { if (dictionary.TryUpdate(j.ToString(), index, j)) { if (dictionary[j.ToString()] != index) { updatedKeys.Value.Succeeded = false; return; } updatedKeys.Value.Keys.Add(j.ToString()); } } }, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } mres.Set(); Task.WaitAll(tasks); int numberSucceeded = 0; int totalKeysUpdated = 0; foreach (var threadData in updatedKeys.Values) { totalKeysUpdated += threadData.Keys.Count; if (threadData.Succeeded) numberSucceeded++; } Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!"); Assert.True(totalKeysUpdated == dictionary.Count, String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated)); foreach (var value in updatedKeys.Values) { for (int i = 0; i < value.Keys.Count; i++) Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex, String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]])); } //test TryUpdate with non atomic values (intPtr > 8) var dict = new ConcurrentDictionary<int, Struct16>(); dict.TryAdd(1, new Struct16(1, -1)); Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)"); } #region Helper Classes and Methods private class ThreadData { public int ThreadIndex; public bool Succeeded = true; public List<string> Keys = new List<string>(); } private struct Struct16 : IEqualityComparer<Struct16> { public long L1, L2; public Struct16(long l1, long l2) { L1 = l1; L2 = l2; } public bool Equals(Struct16 x, Struct16 y) { return x.L1 == y.L1 && x.L2 == y.L2; } public int GetHashCode(Struct16 obj) { return (int)L1; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing { using System.Runtime.InteropServices; using System.Diagnostics; using System.ComponentModel; using System.Drawing.Drawing2D; using System.Drawing.Imaging; /** * Represent a Texture brush object */ /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush"]/*' /> /// <devdoc> /// Encapsulates a <see cref='System.Drawing.Brush'/> that uses an fills the /// interior of a shape with an image. /// </devdoc> public sealed class TextureBrush : Brush { /** * Create a new texture brush object * * @notes Should the rectangle parameter be Rectangle or RectF? * We'll use Rectangle to specify pixel unit source image * rectangle for now. Eventually, we'll need a mechanism * to specify areas of an image in a resolution-independent way. * * @notes We'll make a copy of the bitmap object passed in. */ // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> /// class with the specified image. /// </devdoc> public TextureBrush(Image bitmap) : this(bitmap, System.Drawing.Drawing2D.WrapMode.Tile) { } // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush1"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> /// class with the specified image and wrap mode. /// </para> /// </devdoc> public TextureBrush(Image image, WrapMode wrapMode) { if (image == null) throw new ArgumentNullException("image"); //validate the WrapMode enum //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp)) { throw new InvalidEnumArgumentException("wrapMode", unchecked((int)wrapMode), typeof(WrapMode)); } IntPtr brush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateTexture(new HandleRef(image, image.nativeImage), (int)wrapMode, out brush); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeBrushInternal(brush); } // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. // float version /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush2"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> /// class with the specified image, wrap mode, and bounding rectangle. /// </para> /// </devdoc> public TextureBrush(Image image, WrapMode wrapMode, RectangleF dstRect) { if (image == null) throw new ArgumentNullException("image"); //validate the WrapMode enum //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp)) { throw new InvalidEnumArgumentException("wrapMode", unchecked((int)wrapMode), typeof(WrapMode)); } IntPtr brush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateTexture2(new HandleRef(image, image.nativeImage), unchecked((int)wrapMode), dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, out brush); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeBrushInternal(brush); } // int version // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush3"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> /// class with the specified image, wrap mode, and bounding rectangle. /// </para> /// </devdoc> public TextureBrush(Image image, WrapMode wrapMode, Rectangle dstRect) { if (image == null) throw new ArgumentNullException("image"); //validate the WrapMode enum //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp)) { throw new InvalidEnumArgumentException("wrapMode", unchecked((int)wrapMode), typeof(WrapMode)); } IntPtr brush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateTexture2I(new HandleRef(image, image.nativeImage), unchecked((int)wrapMode), dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, out brush); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } SetNativeBrushInternal(brush); } // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush4"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> class with the specified image /// and bounding rectangle. /// </para> /// </devdoc> public TextureBrush(Image image, RectangleF dstRect) : this(image, dstRect, (ImageAttributes)null) { } // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush5"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> class with the specified /// image, bounding rectangle, and image attributes. /// </para> /// </devdoc> public TextureBrush(Image image, RectangleF dstRect, ImageAttributes imageAttr) { if (image == null) throw new ArgumentNullException("image"); IntPtr brush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateTextureIA(new HandleRef(image, image.nativeImage), new HandleRef(imageAttr, (imageAttr == null) ? IntPtr.Zero : imageAttr.nativeImageAttributes), dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, out brush); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } SetNativeBrushInternal(brush); } // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush6"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> class with the specified image /// and bounding rectangle. /// </para> /// </devdoc> public TextureBrush(Image image, Rectangle dstRect) : this(image, dstRect, (ImageAttributes)null) { } // When creating a texture brush from a metafile image, the dstRect // is used to specify the size that the metafile image should be // rendered at in the device units of the destination graphics. // It is NOT used to crop the metafile image, so only the width // and height values matter for metafiles. /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TextureBrush7"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.TextureBrush'/> class with the specified /// image, bounding rectangle, and image attributes. /// </para> /// </devdoc> public TextureBrush(Image image, Rectangle dstRect, ImageAttributes imageAttr) { if (image == null) throw new ArgumentNullException("image"); IntPtr brush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateTextureIAI(new HandleRef(image, image.nativeImage), new HandleRef(imageAttr, (imageAttr == null) ? IntPtr.Zero : imageAttr.nativeImageAttributes), dstRect.X, dstRect.Y, dstRect.Width, dstRect.Height, out brush); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } SetNativeBrushInternal(brush); } /// <devdoc> /// Constructor to initialized this object to be owned by GDI+. /// </devdoc> internal TextureBrush(IntPtr nativeBrush) { Debug.Assert(nativeBrush != IntPtr.Zero, "Initializing native brush with null."); SetNativeBrushInternal(nativeBrush); } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.Clone"]/*' /> /// <devdoc> /// Creates an exact copy of this <see cref='System.Drawing.TextureBrush'/>. /// </devdoc> public override Object Clone() { IntPtr cloneBrush = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out cloneBrush); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new TextureBrush(cloneBrush); } /** * Set/get brush transform */ private void _SetTransform(Matrix matrix) { int status = SafeNativeMethods.Gdip.GdipSetTextureTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix)); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } private Matrix _GetTransform() { Matrix matrix = new Matrix(); int status = SafeNativeMethods.Gdip.GdipGetTextureTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix)); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } return matrix; } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.Transform"]/*' /> /// <devdoc> /// <para> /// Gets or sets a <see cref='System.Drawing.Drawing2D.Matrix'/> that defines a local geometrical /// transform for this <see cref='System.Drawing.TextureBrush'/>. /// </para> /// </devdoc> public Matrix Transform { get { return _GetTransform(); } set { if (value == null) { throw new ArgumentNullException("value"); } _SetTransform(value); } } /** * Set/get brush wrapping mode */ private void _SetWrapMode(WrapMode wrapMode) { int status = SafeNativeMethods.Gdip.GdipSetTextureWrapMode(new HandleRef(this, NativeBrush), unchecked((int)wrapMode)); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } private WrapMode _GetWrapMode() { int mode = 0; int status = SafeNativeMethods.Gdip.GdipGetTextureWrapMode(new HandleRef(this, NativeBrush), out mode); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } return (WrapMode)mode; } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.WrapMode"]/*' /> /// <devdoc> /// <para> /// Gets or sets a <see cref='System.Drawing.Drawing2D.WrapMode'/> that indicates the wrap mode for this /// <see cref='System.Drawing.TextureBrush'/>. /// </para> /// </devdoc> public WrapMode WrapMode { get { return _GetWrapMode(); } set { //validate the WrapMode enum //valid values are 0x0 to 0x4 if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)WrapMode.Tile, (int)WrapMode.Clamp)) { throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(WrapMode)); } _SetWrapMode(value); } } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.Image"]/*' /> /// <devdoc> /// <para> /// Gets the <see cref='System.Drawing.Image'/> associated with this <see cref='System.Drawing.TextureBrush'/>. /// </para> /// </devdoc> public Image Image { get { IntPtr image; int status = SafeNativeMethods.Gdip.GdipGetTextureImage(new HandleRef(this, NativeBrush), out image); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } return Image.CreateImageObject(image); } } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.ResetTransform"]/*' /> /// <devdoc> /// <para> /// Resets the <see cref='System.Drawing.Drawing2D.LinearGradientBrush.Transform'/> property to /// identity. /// </para> /// </devdoc> public void ResetTransform() { int status = SafeNativeMethods.Gdip.GdipResetTextureTransform(new HandleRef(this, NativeBrush)); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.MultiplyTransform"]/*' /> /// <devdoc> /// <para> /// Multiplies the <see cref='System.Drawing.Drawing2D.Matrix'/> that represents the local geometrical /// transform of this <see cref='System.Drawing.TextureBrush'/> by the specified <see cref='System.Drawing.Drawing2D.Matrix'/> by prepending the specified <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </para> /// </devdoc> public void MultiplyTransform(Matrix matrix) { MultiplyTransform(matrix, MatrixOrder.Prepend); } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.MultiplyTransform1"]/*' /> /// <devdoc> /// <para> /// Multiplies the <see cref='System.Drawing.Drawing2D.Matrix'/> that represents the local geometrical /// transform of this <see cref='System.Drawing.TextureBrush'/> by the specified <see cref='System.Drawing.Drawing2D.Matrix'/> in the specified order. /// </para> /// </devdoc> public void MultiplyTransform(Matrix matrix, MatrixOrder order) { if (matrix == null) { throw new ArgumentNullException("matrix"); } int status = SafeNativeMethods.Gdip.GdipMultiplyTextureTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix), order); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TranslateTransform"]/*' /> /// <devdoc> /// <para> /// Translates the local geometrical transform by the specified dimmensions. This /// method prepends the translation to the transform. /// </para> /// </devdoc> public void TranslateTransform(float dx, float dy) { TranslateTransform(dx, dy, MatrixOrder.Prepend); } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.TranslateTransform1"]/*' /> /// <devdoc> /// <para> /// Translates the local geometrical transform by the specified dimmensions in /// the specified order. /// </para> /// </devdoc> public void TranslateTransform(float dx, float dy, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipTranslateTextureTransform(new HandleRef(this, NativeBrush), dx, dy, order); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.ScaleTransform"]/*' /> /// <devdoc> /// <para> /// Scales the local geometric transform by the specified amounts. This method /// prepends the scaling matrix to the transform. /// </para> /// </devdoc> public void ScaleTransform(float sx, float sy) { ScaleTransform(sx, sy, MatrixOrder.Prepend); } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.ScaleTransform1"]/*' /> /// <devdoc> /// <para> /// Scales the local geometric transform by the specified amounts in the /// specified order. /// </para> /// </devdoc> public void ScaleTransform(float sx, float sy, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipScaleTextureTransform(new HandleRef(this, NativeBrush), sx, sy, order); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.RotateTransform"]/*' /> /// <devdoc> /// <para> /// Rotates the local geometric transform by the specified amount. This method /// prepends the rotation to the transform. /// </para> /// </devdoc> public void RotateTransform(float angle) { RotateTransform(angle, MatrixOrder.Prepend); } /// <include file='doc\TextureBrush.uex' path='docs/doc[@for="TextureBrush.RotateTransform1"]/*' /> /// <devdoc> /// <para> /// Rotates the local geometric transform by the specified amount in the /// specified order. /// </para> /// </devdoc> public void RotateTransform(float angle, MatrixOrder order) { int status = SafeNativeMethods.Gdip.GdipRotateTextureTransform(new HandleRef(this, NativeBrush), angle, order); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } } }
//Copyright 2010 Microsoft Corporation // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. #if ASTORIA_CLIENT namespace System.Data.Services.Client #else namespace System.Data.Services #endif { using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; internal static class HttpProcessUtility { internal static readonly UTF8Encoding EncodingUtf8NoPreamble = new UTF8Encoding(false, true); internal static Encoding FallbackEncoding { get { return EncodingUtf8NoPreamble; } } private static Encoding MissingEncoding { get { #if ASTORIA_LIGHT return Encoding.UTF8; #else return Encoding.GetEncoding("ISO-8859-1", new EncoderExceptionFallback(), new DecoderExceptionFallback()); #endif } } #if !ASTORIA_CLIENT internal static string BuildContentType(string mime, Encoding encoding) { Debug.Assert(mime != null, "mime != null"); if (encoding == null) { return mime; } else { return mime + ";charset=" + encoding.WebName; } } internal static string SelectMimeType(string acceptTypesText, string[] availableTypes) { Debug.Assert(availableTypes != null, "acceptableTypes != null"); string selectedContentType = null; int selectedMatchingParts = -1; int selectedQualityValue = 0; int selectedPreferenceIndex = Int32.MaxValue; bool acceptable = false; bool acceptTypesEmpty = true; if (!String.IsNullOrEmpty(acceptTypesText)) { IEnumerable<MediaType> acceptTypes = MimeTypesFromAcceptHeader(acceptTypesText); foreach (MediaType acceptType in acceptTypes) { acceptTypesEmpty = false; for (int i = 0; i < availableTypes.Length; i++) { string availableType = availableTypes[i]; int matchingParts = acceptType.GetMatchingParts(availableType); if (matchingParts < 0) { continue; } if (matchingParts > selectedMatchingParts) { selectedContentType = availableType; selectedMatchingParts = matchingParts; selectedQualityValue = acceptType.SelectQualityValue(); selectedPreferenceIndex = i; acceptable = selectedQualityValue != 0; } else if (matchingParts == selectedMatchingParts) { int candidateQualityValue = acceptType.SelectQualityValue(); if (candidateQualityValue > selectedQualityValue) { selectedContentType = availableType; selectedQualityValue = candidateQualityValue; selectedPreferenceIndex = i; acceptable = selectedQualityValue != 0; } else if (candidateQualityValue == selectedQualityValue) { if (i < selectedPreferenceIndex) { selectedContentType = availableType; selectedPreferenceIndex = i; } } } } } } if (acceptTypesEmpty) { selectedContentType = availableTypes[0]; } else if (!acceptable) { selectedContentType = null; } return selectedContentType; } internal static string SelectRequiredMimeType( string acceptTypesText, string[] exactContentType, string inexactContentType) { Debug.Assert(exactContentType != null && exactContentType.Length != 0, "exactContentType != null && exactContentType.Length != 0"); Debug.Assert(inexactContentType != null, "inexactContentType != null"); string selectedContentType = null; int selectedMatchingParts = -1; int selectedQualityValue = 0; bool acceptable = false; bool acceptTypesEmpty = true; bool foundExactMatch = false; if (!String.IsNullOrEmpty(acceptTypesText)) { IEnumerable<MediaType> acceptTypes = MimeTypesFromAcceptHeader(acceptTypesText); foreach (MediaType acceptType in acceptTypes) { acceptTypesEmpty = false; for (int i = 0; i < exactContentType.Length; i++) { if (WebUtil.CompareMimeType(acceptType.MimeType, exactContentType[i])) { selectedContentType = exactContentType[i]; selectedQualityValue = acceptType.SelectQualityValue(); acceptable = selectedQualityValue != 0; foundExactMatch = true; break; } } if (foundExactMatch) { break; } int matchingParts = acceptType.GetMatchingParts(inexactContentType); if (matchingParts < 0) { continue; } if (matchingParts > selectedMatchingParts) { selectedContentType = inexactContentType; selectedMatchingParts = matchingParts; selectedQualityValue = acceptType.SelectQualityValue(); acceptable = selectedQualityValue != 0; } else if (matchingParts == selectedMatchingParts) { int candidateQualityValue = acceptType.SelectQualityValue(); if (candidateQualityValue > selectedQualityValue) { selectedContentType = inexactContentType; selectedQualityValue = candidateQualityValue; acceptable = selectedQualityValue != 0; } } } } if (!acceptable && !acceptTypesEmpty) { throw Error.HttpHeaderFailure(415, Strings.DataServiceException_UnsupportedMediaType); } if (acceptTypesEmpty) { Debug.Assert(selectedContentType == null, "selectedContentType == null - otherwise accept types were not empty"); selectedContentType = inexactContentType; } Debug.Assert(selectedContentType != null, "selectedContentType != null - otherwise no selection was made"); return selectedContentType; } internal static Encoding EncodingFromAcceptCharset(string acceptCharset) { Encoding result = null; if (!string.IsNullOrEmpty(acceptCharset)) { List<CharsetPart> parts = new List<CharsetPart>(AcceptCharsetParts(acceptCharset)); parts.Sort(delegate(CharsetPart x, CharsetPart y) { return y.Quality - x.Quality; }); var encoderFallback = new EncoderExceptionFallback(); var decoderFallback = new DecoderExceptionFallback(); foreach (CharsetPart part in parts) { if (part.Quality > 0) { if (String.Compare("utf-8", part.Charset, StringComparison.OrdinalIgnoreCase) == 0) { result = FallbackEncoding; break; } else { try { result = Encoding.GetEncoding(part.Charset, encoderFallback, decoderFallback); break; } catch (ArgumentException) { } } } } } if (result == null) { result = FallbackEncoding; } return result; } #endif internal static KeyValuePair<string, string>[] ReadContentType(string contentType, out string mime, out Encoding encoding) { if (String.IsNullOrEmpty(contentType)) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_ContentTypeMissing); } MediaType mediaType = ReadMediaType(contentType); mime = mediaType.MimeType; encoding = mediaType.SelectEncoding(); return mediaType.Parameters; } #if !ASTORIA_CLIENT internal static string GetParameterValue(KeyValuePair<string, string>[] parameters, string parameterName) { if (parameters == null) { return null; } foreach (KeyValuePair<string, string> parameterInfo in parameters) { if (parameterInfo.Key == parameterName) { return parameterInfo.Value; } } return null; } #endif internal static bool TryReadVersion(string text, out KeyValuePair<Version, string> result) { Debug.Assert(text != null, "text != null"); int separator = text.IndexOf(';'); string versionText, libraryName; if (separator >= 0) { versionText = text.Substring(0, separator); libraryName = text.Substring(separator + 1).Trim(); } else { versionText = text; libraryName = null; } result = default(KeyValuePair<Version, string>); versionText = versionText.Trim(); bool dotFound = false; for (int i = 0; i < versionText.Length; i++) { if (versionText[i] == '.') { if (dotFound) { return false; } dotFound = true; } else if (versionText[i] < '0' || versionText[i] > '9') { return false; } } try { result = new KeyValuePair<Version, string>(new Version(versionText), libraryName); return true; } catch (Exception e) { if (e is FormatException || e is OverflowException || e is ArgumentException) { return false; } throw; } } private static Encoding EncodingFromName(string name) { if (name == null) { return MissingEncoding; } name = name.Trim(); if (name.Length == 0) { return MissingEncoding; } else { try { #if ASTORIA_LIGHT return Encoding.UTF8; #else return Encoding.GetEncoding(name); #endif } catch (ArgumentException) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_EncodingNotSupported(name)); } } } #if !ASTORIA_CLIENT private static DataServiceException CreateParsingException(string message) { return Error.HttpHeaderFailure(400, message); } #endif private static void ReadMediaTypeAndSubtype(string text, ref int textIndex, out string type, out string subType) { Debug.Assert(text != null, "text != null"); int textStart = textIndex; if (ReadToken(text, ref textIndex)) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeUnspecified); } if (text[textIndex] != '/') { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSlash); } type = text.Substring(textStart, textIndex - textStart); textIndex++; int subTypeStart = textIndex; ReadToken(text, ref textIndex); if (textIndex == subTypeStart) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSubType); } subType = text.Substring(subTypeStart, textIndex - subTypeStart); } private static MediaType ReadMediaType(string text) { Debug.Assert(text != null, "text != null"); string type; string subType; int textIndex = 0; ReadMediaTypeAndSubtype(text, ref textIndex, out type, out subType); KeyValuePair<string, string>[] parameters = null; while (!SkipWhitespace(text, ref textIndex)) { if (text[textIndex] != ';') { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter); } textIndex++; if (SkipWhitespace(text, ref textIndex)) { break; } ReadMediaTypeParameter(text, ref textIndex, ref parameters); } return new MediaType(type, subType, parameters); } private static bool ReadToken(string text, ref int textIndex) { while (textIndex < text.Length && IsHttpToken(text[textIndex])) { textIndex++; } return (textIndex == text.Length); } private static bool SkipWhitespace(string text, ref int textIndex) { Debug.Assert(text != null, "text != null"); Debug.Assert(text.Length >= 0, "text >= 0"); Debug.Assert(textIndex <= text.Length, "text <= text.Length"); while (textIndex < text.Length && Char.IsWhiteSpace(text, textIndex)) { textIndex++; } return (textIndex == text.Length); } #if !ASTORIA_CLIENT private static bool IsHttpElementSeparator(char c) { return c == ',' || c == ' ' || c == '\t'; } private static bool ReadLiteral(string text, int textIndex, string literal) { if (String.Compare(text, textIndex, literal, 0, literal.Length, StringComparison.Ordinal) != 0) { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } return textIndex + literal.Length == text.Length; } private static int DigitToInt32(char c) { if (c >= '0' && c <= '9') { return (int)(c - '0'); } else { if (IsHttpElementSeparator(c)) { return -1; } else { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } } } private static IEnumerable<MediaType> MimeTypesFromAcceptHeader(string text) { Debug.Assert(!String.IsNullOrEmpty(text), "!String.IsNullOrEmpty(text)"); List<MediaType> mediaTypes = new List<MediaType>(); int textIndex = 0; while (!SkipWhitespace(text, ref textIndex)) { string type; string subType; ReadMediaTypeAndSubtype(text, ref textIndex, out type, out subType); KeyValuePair<string, string>[] parameters = null; while (!SkipWhitespace(text, ref textIndex)) { if (text[textIndex] == ',') { textIndex++; break; } if (text[textIndex] != ';') { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeRequiresSemicolonBeforeParameter); } textIndex++; if (SkipWhitespace(text, ref textIndex)) { break; } ReadMediaTypeParameter(text, ref textIndex, ref parameters); } mediaTypes.Add(new MediaType(type, subType, parameters)); } return mediaTypes; } #endif private static void ReadMediaTypeParameter(string text, ref int textIndex, ref KeyValuePair<string, string>[] parameters) { int startIndex = textIndex; if (ReadToken(text, ref textIndex)) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeMissingValue); } string parameterName = text.Substring(startIndex, textIndex - startIndex); if (text[textIndex] != '=') { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_MediaTypeMissingValue); } textIndex++; string parameterValue = ReadQuotedParameterValue(parameterName, text, ref textIndex); if (parameters == null) { parameters = new KeyValuePair<string, string>[1]; } else { KeyValuePair<string, string>[] grow = new KeyValuePair<string, string>[parameters.Length + 1]; Array.Copy(parameters, grow, parameters.Length); parameters = grow; } parameters[parameters.Length - 1] = new KeyValuePair<string, string>(parameterName, parameterValue); } private static string ReadQuotedParameterValue(string parameterName, string headerText, ref int textIndex) { StringBuilder parameterValue = new StringBuilder(); bool valueIsQuoted = false; if (textIndex < headerText.Length) { if (headerText[textIndex] == '\"') { textIndex++; valueIsQuoted = true; } } while (textIndex < headerText.Length) { char currentChar = headerText[textIndex]; if (currentChar == '\\' || currentChar == '\"') { if (!valueIsQuoted) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_EscapeCharWithoutQuotes(parameterName)); } textIndex++; if (currentChar == '\"') { valueIsQuoted = false; break; } if (textIndex >= headerText.Length) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_EscapeCharAtEnd(parameterName)); } currentChar = headerText[textIndex]; } else if (!IsHttpToken(currentChar)) { break; } parameterValue.Append(currentChar); textIndex++; } if (valueIsQuoted) { throw Error.HttpHeaderFailure(400, Strings.HttpProcessUtility_ClosingQuoteNotFound(parameterName)); } return parameterValue.ToString(); } #if !ASTORIA_CLIENT private static void ReadQualityValue(string text, ref int textIndex, out int qualityValue) { char digit = text[textIndex++]; if (digit == '0') { qualityValue = 0; } else if (digit == '1') { qualityValue = 1; } else { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } if (textIndex < text.Length && text[textIndex] == '.') { textIndex++; int adjustFactor = 1000; while (adjustFactor > 1 && textIndex < text.Length) { char c = text[textIndex]; int charValue = DigitToInt32(c); if (charValue >= 0) { textIndex++; adjustFactor /= 10; qualityValue *= 10; qualityValue += charValue; } else { break; } } qualityValue = qualityValue *= adjustFactor; if (qualityValue > 1000) { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } } else { qualityValue *= 1000; } } private static IEnumerable<CharsetPart> AcceptCharsetParts(string headerValue) { Debug.Assert(!String.IsNullOrEmpty(headerValue), "!String.IsNullOrEmpty(headerValuer)"); bool commaRequired = false; int headerIndex = 0; int headerStart; int headerNameEnd; int headerEnd; int qualityValue; while (headerIndex < headerValue.Length) { if (SkipWhitespace(headerValue, ref headerIndex)) { yield break; } if (headerValue[headerIndex] == ',') { commaRequired = false; headerIndex++; continue; } if (commaRequired) { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } headerStart = headerIndex; headerNameEnd = headerStart; bool endReached = ReadToken(headerValue, ref headerNameEnd); if (headerNameEnd == headerIndex) { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } if (endReached) { qualityValue = 1000; headerEnd = headerNameEnd; } else { char afterNameChar = headerValue[headerNameEnd]; if (IsHttpSeparator(afterNameChar)) { if (afterNameChar == ';') { if (ReadLiteral(headerValue, headerNameEnd, ";q=")) { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } headerEnd = headerNameEnd + 3; ReadQualityValue(headerValue, ref headerEnd, out qualityValue); } else { qualityValue = 1000; headerEnd = headerNameEnd; } } else { throw CreateParsingException(Strings.HttpContextServiceHost_MalformedHeaderValue); } } yield return new CharsetPart(headerValue.Substring(headerStart, headerNameEnd - headerStart), qualityValue); commaRequired = true; headerIndex = headerEnd; } } #endif private static bool IsHttpSeparator(char c) { return c == '(' || c == ')' || c == '<' || c == '>' || c == '@' || c == ',' || c == ';' || c == ':' || c == '\\' || c == '"' || c == '/' || c == '[' || c == ']' || c == '?' || c == '=' || c == '{' || c == '}' || c == ' ' || c == '\x9'; } private static bool IsHttpToken(char c) { return c < '\x7F' && c > '\x1F' && !IsHttpSeparator(c); } #if !ASTORIA_CLIENT private struct CharsetPart { internal readonly string Charset; internal readonly int Quality; internal CharsetPart(string charset, int quality) { Debug.Assert(charset != null, "charset != null"); Debug.Assert(charset.Length > 0, "charset.Length > 0"); Debug.Assert(0 <= quality && quality <= 1000, "0 <= quality && quality <= 1000"); this.Charset = charset; this.Quality = quality; } } #endif [DebuggerDisplay("MediaType [{type}/{subType}]")] private sealed class MediaType { private readonly KeyValuePair<string, string>[] parameters; private readonly string subType; private readonly string type; internal MediaType(string type, string subType, KeyValuePair<string, string>[] parameters) { Debug.Assert(type != null, "type != null"); Debug.Assert(subType != null, "subType != null"); this.type = type; this.subType = subType; this.parameters = parameters; } internal string MimeType { get { return this.type + "/" + this.subType; } } internal KeyValuePair<string, string>[] Parameters { get { return this.parameters; } } #if !ASTORIA_CLIENT internal int GetMatchingParts(string candidate) { Debug.Assert(candidate != null, "candidate must not be null."); int result = -1; if (candidate.Length > 0) { if (this.type == "*") { result = 0; } else { int separatorIdx = candidate.IndexOf('/'); if (separatorIdx >= 0) { string candidateType = candidate.Substring(0, separatorIdx); if (WebUtil.CompareMimeType(this.type, candidateType)) { if (this.subType == "*") { result = 1; } else { string candidateSubType = candidate.Substring(candidateType.Length + 1); if (WebUtil.CompareMimeType(this.subType, candidateSubType)) { result = 2; } } } } } } return result; } internal int SelectQualityValue() { if (this.parameters != null) { foreach (KeyValuePair<string, string> parameter in this.parameters) { if (String.Equals(parameter.Key, XmlConstants.HttpQValueParameter, StringComparison.OrdinalIgnoreCase)) { string qvalueText = parameter.Value.Trim(); if (qvalueText.Length > 0) { int result; int textIndex = 0; ReadQualityValue(qvalueText, ref textIndex, out result); return result; } } } } return 1000; } #endif internal Encoding SelectEncoding() { if (this.parameters != null) { foreach (KeyValuePair<string, string> parameter in this.parameters) { if (String.Equals(parameter.Key, XmlConstants.HttpCharsetParameter, StringComparison.OrdinalIgnoreCase)) { string encodingName = parameter.Value.Trim(); if (encodingName.Length > 0) { return EncodingFromName(parameter.Value); } } } } if (String.Equals(this.type, XmlConstants.MimeTextType, StringComparison.OrdinalIgnoreCase)) { if (String.Equals(this.subType, XmlConstants.MimeXmlSubType, StringComparison.OrdinalIgnoreCase)) { return null; } else { return MissingEncoding; } } else if (String.Equals(this.type, XmlConstants.MimeApplicationType, StringComparison.OrdinalIgnoreCase) && String.Equals(this.subType, XmlConstants.MimeJsonSubType, StringComparison.OrdinalIgnoreCase)) { return FallbackEncoding; } else { return null; } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ReSharper disable MemberCanBeProtected.Global // ReSharper disable UnassignedField.Global // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace Apache.Ignite.Core.Tests { using System; using System.Collections; using System.Collections.Generic; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Lifecycle beans test. /// </summary> public class LifecycleTest { /** Configuration: without Java beans. */ private const string CfgNoBeans = "config//lifecycle//lifecycle-no-beans.xml"; /** Configuration: with Java beans. */ private const string CfgBeans = "config//lifecycle//lifecycle-beans.xml"; /** Whether to throw an error on lifecycle event. */ internal static bool ThrowErr; /** Events: before start. */ internal static IList<Event> BeforeStartEvts; /** Events: after start. */ internal static IList<Event> AfterStartEvts; /** Events: before stop. */ internal static IList<Event> BeforeStopEvts; /** Events: after stop. */ internal static IList<Event> AfterStopEvts; /// <summary> /// Set up routine. /// </summary> [SetUp] public void SetUp() { ThrowErr = false; BeforeStartEvts = new List<Event>(); AfterStartEvts = new List<Event>(); BeforeStopEvts = new List<Event>(); AfterStopEvts = new List<Event>(); } /// <summary> /// Tear down routine. /// </summary> [TearDown] public void TearDown() { Ignition.StopAll(true); } /// <summary> /// Test without Java beans. /// </summary> [Test] public void TestWithoutBeans() { // 1. Test start events. IIgnite grid = Start(CfgNoBeans); Assert.AreEqual(2, grid.GetConfiguration().LifecycleHandlers.Count); Assert.AreEqual(2, BeforeStartEvts.Count); CheckEvent(BeforeStartEvts[0], null, null, 0, null); CheckEvent(BeforeStartEvts[1], null, null, 0, null); Assert.AreEqual(2, AfterStartEvts.Count); CheckEvent(AfterStartEvts[0], grid, grid, 0, null); CheckEvent(AfterStartEvts[1], grid, grid, 0, null); // 2. Test stop events. var stoppingCnt = 0; var stoppedCnt = 0; grid.Stopping += (sender, args) => { stoppingCnt++; }; grid.Stopped += (sender, args) => { stoppedCnt++; }; Ignition.Stop(grid.Name, false); Assert.AreEqual(1, stoppingCnt); Assert.AreEqual(1, stoppedCnt); Assert.AreEqual(2, BeforeStartEvts.Count); Assert.AreEqual(2, AfterStartEvts.Count); Assert.AreEqual(2, BeforeStopEvts.Count); CheckEvent(BeforeStopEvts[0], grid, grid, 0, null); CheckEvent(BeforeStopEvts[1], grid, grid, 0, null); Assert.AreEqual(2, AfterStopEvts.Count); CheckEvent(AfterStopEvts[0], grid, grid, 0, null); CheckEvent(AfterStopEvts[1], grid, grid, 0, null); } /// <summary> /// Test with Java beans. /// </summary> [Test] public void TestWithBeans() { // 1. Test .Net start events. IIgnite grid = Start(CfgBeans); Assert.AreEqual(2, grid.GetConfiguration().LifecycleHandlers.Count); Assert.AreEqual(4, BeforeStartEvts.Count); CheckEvent(BeforeStartEvts[0], null, null, 0, null); CheckEvent(BeforeStartEvts[1], null, null, 1, "1"); CheckEvent(BeforeStartEvts[2], null, null, 0, null); CheckEvent(BeforeStartEvts[3], null, null, 0, null); Assert.AreEqual(4, AfterStartEvts.Count); CheckEvent(AfterStartEvts[0], grid, grid, 0, null); CheckEvent(AfterStartEvts[1], grid, grid, 1, "1"); CheckEvent(AfterStartEvts[2], grid, grid, 0, null); CheckEvent(AfterStartEvts[3], grid, grid, 0, null); // 2. Test Java start events. var res = grid.GetCompute().ExecuteJavaTask<IList>( "org.apache.ignite.platform.lifecycle.PlatformJavaLifecycleTask", null); Assert.AreEqual(2, res.Count); Assert.AreEqual(3, res[0]); Assert.AreEqual(3, res[1]); // 3. Test .Net stop events. Ignition.Stop(grid.Name, false); Assert.AreEqual(4, BeforeStartEvts.Count); Assert.AreEqual(4, AfterStartEvts.Count); Assert.AreEqual(4, BeforeStopEvts.Count); CheckEvent(BeforeStopEvts[0], grid, grid, 0, null); CheckEvent(BeforeStopEvts[1], grid, grid, 1, "1"); CheckEvent(BeforeStopEvts[2], grid, grid, 0, null); CheckEvent(BeforeStopEvts[3], grid, grid, 0, null); Assert.AreEqual(4, AfterStopEvts.Count); CheckEvent(AfterStopEvts[0], grid, grid, 0, null); CheckEvent(AfterStopEvts[1], grid, grid, 1, "1"); CheckEvent(AfterStopEvts[2], grid, grid, 0, null); CheckEvent(AfterStopEvts[3], grid, grid, 0, null); } /// <summary> /// Test behavior when error is thrown from lifecycle beans. /// </summary> [Test] public void TestError() { ThrowErr = true; var ex = Assert.Throws<IgniteException>(() => Start(CfgNoBeans)); Assert.AreEqual("Lifecycle exception.", ex.Message); } /// <summary> /// Start grid. /// </summary> /// <param name="cfgPath">Spring configuration path.</param> /// <returns>Grid.</returns> private static IIgnite Start(string cfgPath) { return Ignition.Start(new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = cfgPath, LifecycleHandlers = new List<ILifecycleHandler> {new Bean(), new Bean()} }); } /// <summary> /// Check event. /// </summary> /// <param name="evt">Event.</param> /// <param name="expGrid1">Expected grid 1.</param> /// <param name="expGrid2">Expected grid 2.</param> /// <param name="expProp1">Expected property 1.</param> /// <param name="expProp2">Expected property 2.</param> private static void CheckEvent(Event evt, IIgnite expGrid1, IIgnite expGrid2, int expProp1, string expProp2) { Assert.AreEqual(expGrid1, evt.Grid1); Assert.AreEqual(expGrid2, evt.Grid2); Assert.AreEqual(expProp1, evt.Prop1); Assert.AreEqual(expProp2, evt.Prop2); } } public abstract class AbstractBean { [InstanceResource] public IIgnite Grid1; public int Property1 { get; set; } } public class Bean : AbstractBean, ILifecycleHandler { [InstanceResource] public IIgnite Grid2; public string Property2 { get; set; } /** <inheritDoc /> */ public void OnLifecycleEvent(LifecycleEventType evtType) { if (LifecycleTest.ThrowErr) throw new Exception("Lifecycle exception."); Event evt = new Event { Grid1 = Grid1, Grid2 = Grid2, Prop1 = Property1, Prop2 = Property2 }; switch (evtType) { case LifecycleEventType.BeforeNodeStart: LifecycleTest.BeforeStartEvts.Add(evt); break; case LifecycleEventType.AfterNodeStart: LifecycleTest.AfterStartEvts.Add(evt); break; case LifecycleEventType.BeforeNodeStop: LifecycleTest.BeforeStopEvts.Add(evt); break; case LifecycleEventType.AfterNodeStop: LifecycleTest.AfterStopEvts.Add(evt); break; } } } public class Event { public IIgnite Grid1; public IIgnite Grid2; public int Prop1; public string Prop2; } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; namespace Avalonia.Controls { /// <summary> /// A control scrolls its content if the content is bigger than the space available. /// </summary> public class ScrollViewer : ContentControl, IScrollable { /// <summary> /// Defines the <see cref="CanScrollHorizontally"/> property. /// </summary> public static readonly StyledProperty<bool> CanScrollHorizontallyProperty = AvaloniaProperty.Register<ScrollViewer, bool>(nameof(CanScrollHorizontally), true); /// <summary> /// Defines the <see cref="Extent"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ExtentProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Extent), o => o.Extent, (o, v) => o.Extent = v); /// <summary> /// Defines the <see cref="Offset"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Vector>( nameof(Offset), o => o.Offset, (o, v) => o.Offset = v); /// <summary> /// Defines the <see cref="Viewport"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ViewportProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Viewport), o => o.Viewport, (o, v) => o.Viewport = v); /// <summary> /// Defines the HorizontalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarMaximum), o => o.HorizontalScrollBarMaximum); /// <summary> /// Defines the HorizontalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarValue), o => o.HorizontalScrollBarValue, (o, v) => o.HorizontalScrollBarValue = v); /// <summary> /// Defines the HorizontalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarViewportSize), o => o.HorizontalScrollBarViewportSize); /// <summary> /// Defines the <see cref="HorizontalScrollBarVisibility"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(HorizontalScrollBarVisibility), ScrollBarVisibility.Auto); /// <summary> /// Defines the VerticalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarMaximum), o => o.VerticalScrollBarMaximum); /// <summary> /// Defines the VerticalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarValue), o => o.VerticalScrollBarValue, (o, v) => o.VerticalScrollBarValue = v); /// <summary> /// Defines the VerticalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarViewportSize), o => o.VerticalScrollBarViewportSize); /// <summary> /// Defines the <see cref="VerticalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(VerticalScrollBarVisibility), ScrollBarVisibility.Auto); private Size _extent; private Vector _offset; private Size _viewport; /// <summary> /// Initializes static members of the <see cref="ScrollViewer"/> class. /// </summary> static ScrollViewer() { AffectsValidation(ExtentProperty, OffsetProperty); AffectsValidation(ViewportProperty, OffsetProperty); } /// <summary> /// Initializes a new instance of the <see cref="ScrollViewer"/> class. /// </summary> public ScrollViewer() { Observable.CombineLatest( this.GetObservable(ExtentProperty), this.GetObservable(ViewportProperty)) .Select(x => new { Extent = x[0], Viewport = x[1] }); } /// <summary> /// Gets the extent of the scrollable content. /// </summary> public Size Extent { get { return _extent; } private set { if (SetAndRaise(ExtentProperty, ref _extent, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets or sets the current scroll offset. /// </summary> public Vector Offset { get { return _offset; } set { value = ValidateOffset(this, value); if (SetAndRaise(OffsetProperty, ref _offset, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the size of the viewport on the scrollable content. /// </summary> public Size Viewport { get { return _viewport; } private set { if (SetAndRaise(ViewportProperty, ref _viewport, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets a value indicating whether the content can be scrolled horizontally. /// </summary> public bool CanScrollHorizontally { get { return GetValue(CanScrollHorizontallyProperty); } set { SetValue(CanScrollHorizontallyProperty, value); } } /// <summary> /// Gets or sets the horizontal scrollbar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get { return GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets or sets the vertical scrollbar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get { return GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets the maximum horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarMaximum { get { return Max(_extent.Width - _viewport.Width, 0); } } /// <summary> /// Gets or sets the horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarValue { get { return _offset.X; } set { if (_offset.X != value) { var old = Offset.X; Offset = Offset.WithX(value); RaisePropertyChanged(HorizontalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the horizontal scrollbar viewport. /// </summary> protected double HorizontalScrollBarViewportSize { get { return Max((_viewport.Width / _extent.Width) * (_extent.Width - _viewport.Width), 0); } } /// <summary> /// Gets the maximum vertical scrollbar value. /// </summary> protected double VerticalScrollBarMaximum { get { return Max(_extent.Height - _viewport.Height, 0); } } /// <summary> /// Gets or sets the vertical scrollbar value. /// </summary> protected double VerticalScrollBarValue { get { return _offset.Y; } set { if (_offset.Y != value) { var old = Offset.Y; Offset = Offset.WithY(value); RaisePropertyChanged(VerticalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the vertical scrollbar viewport. /// </summary> protected double VerticalScrollBarViewportSize { get { return Max((_viewport.Height / _extent.Height) * (_extent.Height - _viewport.Height), 0); } } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public ScrollBarVisibility GetHorizontalScrollBarVisibility(Control control) { return control.GetValue(HorizontalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public void SetHorizontalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public ScrollBarVisibility GetVerticalScrollBarVisibility(Control control) { return control.GetValue(VerticalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public void SetVerticalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(VerticalScrollBarVisibilityProperty, value); } internal static Vector CoerceOffset(Size extent, Size viewport, Vector offset) { var maxX = Math.Max(extent.Width - viewport.Width, 0); var maxY = Math.Max(extent.Height - viewport.Height, 0); return new Vector(Clamp(offset.X, 0, maxX), Clamp(offset.Y, 0, maxY)); } private static double Clamp(double value, double min, double max) { return (value < min) ? min : (value > max) ? max : value; } private static double Max(double x, double y) { var result = Math.Max(x, y); return double.IsNaN(result) ? 0 : result; } private static Vector ValidateOffset(AvaloniaObject o, Vector value) { ScrollViewer scrollViewer = o as ScrollViewer; if (scrollViewer != null) { var extent = scrollViewer.Extent; var viewport = scrollViewer.Viewport; return CoerceOffset(extent, viewport, value); } else { return value; } } private void CalculatedPropertiesChanged() { // Pass old values of 0 here because we don't have the old values at this point, // and it shouldn't matter as only the template uses these properies. RaisePropertyChanged(HorizontalScrollBarMaximumProperty, 0, HorizontalScrollBarMaximum); RaisePropertyChanged(HorizontalScrollBarValueProperty, 0, HorizontalScrollBarValue); RaisePropertyChanged(HorizontalScrollBarViewportSizeProperty, 0, HorizontalScrollBarViewportSize); RaisePropertyChanged(VerticalScrollBarMaximumProperty, 0, VerticalScrollBarMaximum); RaisePropertyChanged(VerticalScrollBarValueProperty, 0, VerticalScrollBarValue); RaisePropertyChanged(VerticalScrollBarViewportSizeProperty, 0, VerticalScrollBarViewportSize); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; namespace System { // The class designed as to keep working set of Uri class as minimal. // The idea is to stay with static helper methods and strings internal class DomainNameHelper { private DomainNameHelper() { } internal const string Localhost = "localhost"; internal const string Loopback = "loopback"; internal static string ParseCanonicalName(string str, int start, int end, ref bool loopback) { string res = null; for (int i = end - 1; i >= start; --i) { if (str[i] >= 'A' && str[i] <= 'Z') { res = str.Substring(start, end - start).ToLowerInvariant(); break; } if (str[i] == ':') end = i; } if (res == null) { res = str.Substring(start, end - start); } if (res == Localhost || res == Loopback) { loopback = true; return Localhost; } return res; } // // IsValid // // Determines whether a string is a valid domain name // // subdomain -> <label> | <label> "." <subdomain> // // Inputs: // - name as Name to test // - starting position // - ending position // // Outputs: // The end position of a valid domain name string, the canonical flag if found so // // Returns: // bool // // Remarks: Optimized for speed as a most common case, // MUST NOT be used unless all input indexes are verified and trusted. // internal unsafe static bool IsValid(char* name, ushort pos, ref int returnedEnd, ref bool notCanonical, bool notImplicitFile) { char* curPos = name + pos; char* newPos = curPos; char* end = name + returnedEnd; for (; newPos < end; ++newPos) { char ch = *newPos; if (ch > 0x7f) return false; // not ascii if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#'))) { end = newPos; break; } } if (end == curPos) { return false; } do { // Determines whether a string is a valid domain name label. In keeping // with RFC 1123, section 2.1, the requirement that the first character // of a label be alphabetic is dropped. Therefore, Domain names are // formed as: // // <label> -> <alphanum> [<alphanum> | <hyphen> | <underscore>] * 62 //find the dot or hit the end newPos = curPos; while (newPos < end) { if (*newPos == '.') break; ++newPos; } //check the label start/range if (curPos == newPos || newPos - curPos > 63 || !IsASCIILetterOrDigit(*curPos++, ref notCanonical)) { return false; } //check the label content while (curPos < newPos) { if (!IsValidDomainLabelCharacter(*curPos++, ref notCanonical)) { return false; } } ++curPos; } while (curPos < end); returnedEnd = (ushort)(end - name); return true; } // // Checks if the domain name is valid according to iri // There are pretty much no restrictions and we effectively return the end of the // domain name. // internal unsafe static bool IsValidByIri(char* name, ushort pos, ref int returnedEnd, ref bool notCanonical, bool notImplicitFile) { char* curPos = name + pos; char* newPos = curPos; char* end = name + returnedEnd; int count = 0; // count number of octets in a label; for (; newPos < end; ++newPos) { char ch = *newPos; if (ch == '/' || ch == '\\' || (notImplicitFile && (ch == ':' || ch == '?' || ch == '#'))) { end = newPos; break; } } if (end == curPos) { return false; } do { // Determines whether a string is a valid domain name label. In keeping // with RFC 1123, section 2.1, the requirement that the first character // of a label be alphabetic is dropped. Therefore, Domain names are // formed as: // // <label> -> <alphanum> [<alphanum> | <hyphen> | <underscore>] * 62 //find the dot or hit the end newPos = curPos; count = 0; bool labelHasUnicode = false; // if label has unicode we need to add 4 to label count for xn-- while (newPos < end) { if ((*newPos == '.') || (*newPos == '\u3002') || //IDEOGRAPHIC FULL STOP (*newPos == '\uFF0E') || //FULLWIDTH FULL STOP (*newPos == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP break; count++; if (*newPos > 0xFF) count++; // counts for two octets if (*newPos >= 0xA0) labelHasUnicode = true; ++newPos; } //check the label start/range if (curPos == newPos || (labelHasUnicode ? count + 4 : count) > 63 || ((*curPos++ < 0xA0) && !IsASCIILetterOrDigit(*(curPos - 1), ref notCanonical))) { return false; } //check the label content while (curPos < newPos) { if ((*curPos++ < 0xA0) && !IsValidDomainLabelCharacter(*(curPos - 1), ref notCanonical)) { return false; } } ++curPos; } while (curPos < end); returnedEnd = (ushort)(end - name); return true; } internal static string IdnEquivalent(string hostname) { bool allAscii = true; bool atLeastOneValidIdn = false; unsafe { fixed (char* host = hostname) { return IdnEquivalent(host, 0, hostname.Length, ref allAscii, ref atLeastOneValidIdn); } } } // // Will convert a host name into its idn equivalent + tell you if it had a valid idn label // internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn) { string bidiStrippedHost = null; string idnEquivalent = IdnEquivalent(hostname, start, end, ref allAscii, ref bidiStrippedHost); if (idnEquivalent != null) { string strippedHost = (allAscii ? idnEquivalent : bidiStrippedHost); fixed (char* strippedHostPtr = strippedHost) { int length = strippedHost.Length; int newPos = 0; int curPos = 0; bool foundAce = false; bool checkedAce = false; bool foundDot = false; do { foundAce = false; checkedAce = false; foundDot = false; //find the dot or hit the end newPos = curPos; while (newPos < length) { char c = strippedHostPtr[newPos]; if (!checkedAce) { checkedAce = true; if ((newPos + 3 < length) && IsIdnAce(strippedHostPtr, newPos)) { newPos += 4; foundAce = true; continue; } } if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP (c == '\uFF0E') || //FULLWIDTH FULL STOP (c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP { foundDot = true; break; } ++newPos; } if (foundAce) { // check ace validity try { IdnMapping map = new IdnMapping(); map.GetUnicode(new string(strippedHostPtr, curPos, newPos - curPos)); atLeastOneValidIdn = true; break; } catch (ArgumentException) { // not valid ace so treat it as a normal ascii label } } curPos = newPos + (foundDot ? 1 : 0); } while (curPos < length); } } else { atLeastOneValidIdn = false; } return idnEquivalent; } // // Will convert a host name into its idn equivalent // internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref string bidiStrippedHost) { string idn = null; if (end <= start) return idn; // indexes are validated int newPos = start; allAscii = true; while (newPos < end) { // check if only ascii chars // special case since idnmapping will not lowercase if only ascii present if (hostname[newPos] > '\x7F') { allAscii = false; break; } ++newPos; } if (allAscii) { // just lowercase for ascii string unescapedHostname = new string(hostname, start, end - start); return unescapedHostname.ToLowerInvariant(); } else { IdnMapping map = new IdnMapping(); string asciiForm; bidiStrippedHost = UriHelper.StripBidiControlCharacter(hostname, start, end - start); try { asciiForm = map.GetAscii(bidiStrippedHost); } catch (ArgumentException) { throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn); } return asciiForm; } } private unsafe static bool IsIdnAce(string input, int index) { if ((input[index] == 'x') && (input[index + 1] == 'n') && (input[index + 2] == '-') && (input[index + 3] == '-')) return true; else return false; } private unsafe static bool IsIdnAce(char* input, int index) { if ((input[index] == 'x') && (input[index + 1] == 'n') && (input[index + 2] == '-') && (input[index + 3] == '-')) return true; else return false; } // // Will convert a host name into its unicode equivalent expanding any existing idn names present // internal unsafe static string UnicodeEquivalent(string idnHost, char* hostname, int start, int end) { IdnMapping map = new IdnMapping(); // Test common scenario first for perf // try to get unicode equivalent try { return map.GetUnicode(idnHost); } catch (ArgumentException) { } // Here because something threw in GetUnicode above // Need to now check individual labels of they had an ace label that was not valid Idn name // or if there is a label with invalid Idn char. bool dummy = true; return UnicodeEquivalent(hostname, start, end, ref dummy, ref dummy); } internal unsafe static string UnicodeEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn) { IdnMapping map = new IdnMapping(); // hostname already validated allAscii = true; atLeastOneValidIdn = false; string idn = null; if (end <= start) return idn; string unescapedHostname = UriHelper.StripBidiControlCharacter(hostname, start, (end - start)); string unicodeEqvlHost = null; int curPos = 0; int newPos = 0; int length = unescapedHostname.Length; bool asciiLabel = true; bool foundAce = false; bool checkedAce = false; bool foundDot = false; // We run a loop where for every label // a) if label is ascii and no ace then we lowercase it // b) if label is ascii and ace and not valid idn then just lowercase it // c) if label is ascii and ace and is valid idn then get its unicode eqvl // d) if label is unicode then clean it by running it through idnmapping do { asciiLabel = true; foundAce = false; checkedAce = false; foundDot = false; //find the dot or hit the end newPos = curPos; while (newPos < length) { char c = unescapedHostname[newPos]; if (!checkedAce) { checkedAce = true; if ((newPos + 3 < length) && (c == 'x') && IsIdnAce(unescapedHostname, newPos)) foundAce = true; } if (asciiLabel && (c > '\x7F')) { asciiLabel = false; allAscii = false; } if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP (c == '\uFF0E') || //FULLWIDTH FULL STOP (c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP { foundDot = true; break; } ++newPos; } if (!asciiLabel) { string asciiForm = unescapedHostname.Substring(curPos, newPos - curPos); try { asciiForm = map.GetAscii(asciiForm); } catch (ArgumentException) { throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn); } unicodeEqvlHost += map.GetUnicode(asciiForm); if (foundDot) unicodeEqvlHost += "."; } else { bool aceValid = false; if (foundAce) { // check ace validity try { unicodeEqvlHost += map.GetUnicode(unescapedHostname.Substring(curPos, newPos - curPos)); if (foundDot) unicodeEqvlHost += "."; aceValid = true; atLeastOneValidIdn = true; } catch (ArgumentException) { // not valid ace so treat it as a normal ascii label } } if (!aceValid) { // for invalid aces we just lowercase the label unicodeEqvlHost += unescapedHostname.Substring(curPos, newPos - curPos).ToLowerInvariant(); if (foundDot) unicodeEqvlHost += "."; } } curPos = newPos + (foundDot ? 1 : 0); } while (curPos < length); return unicodeEqvlHost; } // // Determines whether a character is a letter or digit according to the // DNS specification [RFC 1035]. We use our own variant of IsLetterOrDigit // because the base version returns false positives for non-ANSI characters // private static bool IsASCIILetterOrDigit(char character, ref bool notCanonical) { if ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9')) return true; if (character >= 'A' && character <= 'Z') { notCanonical = true; return true; } return false; } // // Takes into account the additional legal domain name characters '-' and '_' // Note that '_' char is formally invalid but is historically in use, especially on corpnets // private static bool IsValidDomainLabelCharacter(char character, ref bool notCanonical) { if ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') || (character == '-') || (character == '_')) return true; if (character >= 'A' && character <= 'Z') { notCanonical = true; return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using DioLive.Cache.WebUI.Data; using DioLive.Cache.WebUI.Models; using DioLive.Cache.WebUI.Models.CategoryViewModels; using DioLive.Cache.WebUI.Models.PlanViewModels; using DioLive.Cache.WebUI.Models.PurchaseViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; namespace DioLive.Cache.WebUI.Controllers { [Authorize] public class PurchasesController : Controller { private const string Bind_Create = nameof(CreatePurchaseVM.CategoryId) + "," + nameof(CreatePurchaseVM.Date) + "," + nameof(CreatePurchaseVM.Name) + "," + nameof(CreatePurchaseVM.Cost) + "," + nameof(CreatePurchaseVM.Shop) + "," + nameof(CreatePurchaseVM.Comments) + "," + nameof(CreatePurchaseVM.PlanId); private const string Bind_Edit = nameof(EditPurchaseVM.Id) + "," + nameof(EditPurchaseVM.CategoryId) + "," + nameof(EditPurchaseVM.Date) + "," + nameof(EditPurchaseVM.Name) + "," + nameof(EditPurchaseVM.Cost) + "," + nameof(EditPurchaseVM.Shop) + "," + nameof(EditPurchaseVM.Comments); private readonly ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; private readonly IMapper _mapper; public PurchasesController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, IMapper mapper) { _context = context; _userManager = userManager; _mapper = mapper; } // GET: Purchases public async Task<IActionResult> Index() { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return RedirectToAction(nameof(HomeController.Index), "Home"); } var purchases = _context.Purchase.Include(p => p.Category).ThenInclude(c => c.Localizations) .Where(p => p.BudgetId == budgetId.Value) .OrderByDescending(p => p.Date) .ThenByDescending(p => p.CreateDate); var budget = await _context.Budget .Include(b => b.Author) .Include(b => b.Plans) .SingleOrDefaultAsync(b => b.Id == budgetId.Value); ViewData["BudgetId"] = budget.Id; ViewData["BudgetName"] = budget.Name; ViewData["BudgetAuthor"] = budget.Author.UserName; var userId = _userManager.GetUserId(User); var user = await ApplicationUser.GetWithOptions(_context, userId); ViewData["PurchaseGrouping"] = user.Options.PurchaseGrouping; if (user.Options.ShowPlanList) { ViewData["Plans"] = _mapper.Map<ICollection<PlanVM>>(budget.Plans.OrderBy(p => p.Name).ToList()); } var entities = await purchases.ToListAsync(); var model = entities.Select(ent => { var vm = _mapper.Map<PurchaseVM>(ent); var localization = ent.Category.Localizations.SingleOrDefault(loc => loc.Culture == Request.HttpContext.GetCurrentCulture()); if (localization != null) { vm.Category.DisplayName = localization.Name; }; return vm; }).ToList(); return View(model); } // GET: Purchases/Create public async Task<IActionResult> Create(int? planId = null) { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return RedirectToAction(nameof(HomeController.Index), "Home"); } string userId = _userManager.GetUserId(User); Budget budget = await Budget.GetWithShares(_context, budgetId.Value); if (!budget.HasRights(userId, ShareAccess.Purchases)) { return Forbid(); } var model = new CreatePurchaseVM { Date = DateTime.Today }; if (planId.HasValue) { var plan = _context.Budget .Include(b => b.Plans) .Single(b => b.Id == budgetId.Value) .Plans .SingleOrDefault(p => p.Id == planId.Value); model.PlanId = planId; model.Name = plan.Name; } FillCategoryList(budgetId.Value); return View(model); } // POST: Purchases/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind(Bind_Create)] CreatePurchaseVM model) { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return RedirectToAction(nameof(HomeController.Index), "Home"); } string userId = _userManager.GetUserId(User); Budget budget = await Budget.GetWithShares(_context, budgetId.Value); if (!budget.HasRights(userId, ShareAccess.Purchases)) { return Forbid(); } if (ModelState.IsValid) { Purchase purchase = _mapper.Map<Purchase>(model); purchase.AuthorId = userId; purchase.BudgetId = budgetId.Value; _context.Add(purchase); if (model.PlanId.HasValue) { var plan = _context.Budget .Include(b => b.Plans) .Single(b => b.Id == budgetId.Value) .Plans .SingleOrDefault(p => p.Id == model.PlanId.Value); plan.BuyDate = DateTime.UtcNow; plan.BuyerId = userId; } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } FillCategoryList(budgetId.Value); return View(model); } // GET: Purchases/Edit/5 public async Task<IActionResult> Edit(Guid? id) { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return RedirectToAction(nameof(HomeController.Index), "Home"); } if (!id.HasValue) { return NotFound(); } var purchase = await Get(id.Value); if (purchase == null) { return NotFound(); } if (!HasRights(purchase, ShareAccess.Purchases)) { return Forbid(); } FillCategoryList(budgetId.Value); EditPurchaseVM model = _mapper.Map<EditPurchaseVM>(purchase); return View(model); } // POST: Purchases/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(Guid id, [Bind(Bind_Edit)] EditPurchaseVM model) { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return RedirectToAction(nameof(HomeController.Index), "Home"); } if (id != model.Id) { return NotFound(); } Purchase purchase = await Get(id); if (purchase == null) { return NotFound(); } if (!HasRights(purchase, ShareAccess.Purchases)) { return Forbid(); } if (ModelState.IsValid) { purchase.CategoryId = model.CategoryId; purchase.Date = model.Date; purchase.Name = model.Name; purchase.Cost = model.Cost; purchase.Shop = model.Shop; purchase.Comments = model.Comments; purchase.LastEditorId = _userManager.GetUserId(User); try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PurchaseExists(purchase.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } FillCategoryList(budgetId.Value); return View(purchase); } // GET: Purchases/Delete/5 public async Task<IActionResult> Delete(Guid? id) { if (!id.HasValue) { return NotFound(); } var purchase = await Get(id.Value); if (purchase == null) { return NotFound(); } if (!HasRights(purchase, ShareAccess.Purchases)) { return Forbid(); } return View(purchase); } // POST: Purchases/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(Guid id) { var purchase = await Get(id); if (purchase == null) { return NotFound(); } if (!HasRights(purchase, ShareAccess.Purchases)) { return Forbid(); } _context.Purchase.Remove(purchase); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } public IActionResult Shops() { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return Json(new string[0]); } var shops = _context.Purchase .Where(p => p.BudgetId == budgetId.Value) .Select(p => p.Shop) .Distinct() .Except(new string[] { null }) .OrderBy(s => s); return Json(shops.ToArray()); } [HttpPost] public async Task<IActionResult> AddPlan(string name) { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return BadRequest(); } var budget = await _context.Budget.Include(b => b.Plans) .SingleOrDefaultAsync(b => b.Id == budgetId.Value); var plan = new Plan { Name = name, AuthorId = _userManager.GetUserId(User), }; budget.Plans.Add(plan); await _context.SaveChangesAsync(); return Json(_mapper.Map<PlanVM>(plan)); } [HttpPost] public async Task<IActionResult> RemovePlan(int id) { Guid? budgetId = CurrentBudgetId; if (!budgetId.HasValue) { return BadRequest(); } var plan = _context.Budget .Include(b => b.Plans) .Single(b => b.Id == budgetId.Value) .Plans .SingleOrDefault(p => p.Id == id); _context.Set<Plan>().Remove(plan); await _context.SaveChangesAsync(); return Ok(); } private bool PurchaseExists(Guid id) { return _context.Purchase.Any(e => e.Id == id); } private Task<Purchase> Get(Guid id) { return Purchase.GetWithShares(_context, id); } private bool HasRights(Purchase purchase, ShareAccess requiredAccess) { var userId = _userManager.GetUserId(User); return purchase.Budget.HasRights(userId, requiredAccess); } private void FillCategoryList(Guid budgetId) { IQueryable<Category> categories = _context.Category .Include(c => c.Localizations) .Include(c => c.Purchases) .Where(c => c.BudgetId == budgetId); var currentCulture = Request.HttpContext.GetCurrentCulture(); var allCategories = categories .Select(c => new { Id = c.Id, PurchasesCount = c.Purchases.Count, DefaultName = c.Name, Localization = c.Localizations.SingleOrDefault(loc => loc.Culture == currentCulture), }) .ToList(); var result = allCategories .Select(c => new { c.Id, c.PurchasesCount, DisplayName = c.Localization != null ? c.Localization.Name : c.DefaultName, }) .OrderByDescending(c => c.PurchasesCount) .ThenBy(c => c.DisplayName) .Select(c => new CategoryVM { Id = c.Id, DisplayName = c.DisplayName }) .ToList(); ViewData["CategoryId"] = new SelectList(result, nameof(CategoryVM.Id), nameof(CategoryVM.DisplayName)); } private Guid? CurrentBudgetId => HttpContext.Session.GetGuid(nameof(SessionKeys.CurrentBudget)); } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reactive; using System.Reactive.Linq; using Avalonia.Data.Core.Parsers; using Avalonia.Data.Core.Plugins; using Avalonia.Reactive; namespace Avalonia.Data.Core { /// <summary> /// Observes and sets the value of an expression on an object. /// </summary> public class ExpressionObserver : LightweightObservableBase<object>, IDescription { /// <summary> /// An ordered collection of property accessor plugins that can be used to customize /// the reading and subscription of property values on a type. /// </summary> public static readonly IList<IPropertyAccessorPlugin> PropertyAccessors = new List<IPropertyAccessorPlugin> { new AvaloniaPropertyAccessorPlugin(), new MethodAccessorPlugin(), new InpcPropertyAccessorPlugin(), }; /// <summary> /// An ordered collection of validation checker plugins that can be used to customize /// the validation of view model and model data. /// </summary> public static readonly IList<IDataValidationPlugin> DataValidators = new List<IDataValidationPlugin> { new DataAnnotationsValidationPlugin(), new IndeiValidationPlugin(), new ExceptionValidationPlugin(), }; /// <summary> /// An ordered collection of stream plugins that can be used to customize the behavior /// of the '^' stream binding operator. /// </summary> public static readonly IList<IStreamPlugin> StreamHandlers = new List<IStreamPlugin> { new TaskStreamPlugin(), new ObservableStreamPlugin(), }; private static readonly object UninitializedValue = new object(); private readonly ExpressionNode _node; private object _root; private IDisposable _rootSubscription; private WeakReference<object> _value; /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="root">The root object.</param> /// <param name="node">The expression.</param> /// <param name="description"> /// A description of the expression. /// </param> public ExpressionObserver( object root, ExpressionNode node, string description = null) { if (root == AvaloniaProperty.UnsetValue) { root = null; } _node = node; Description = description; _root = new WeakReference(root); } /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootObservable">An observable which provides the root object.</param> /// <param name="node">The expression.</param> /// <param name="description"> /// A description of the expression. /// </param> public ExpressionObserver( IObservable<object> rootObservable, ExpressionNode node, string description) { Contract.Requires<ArgumentNullException>(rootObservable != null); _node = node; Description = description; _root = rootObservable; } /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootGetter">A function which gets the root object.</param> /// <param name="node">The expression.</param> /// <param name="update">An observable which triggers a re-read of the getter.</param> /// <param name="description"> /// A description of the expression. /// </param> public ExpressionObserver( Func<object> rootGetter, ExpressionNode node, IObservable<Unit> update, string description) { Contract.Requires<ArgumentNullException>(rootGetter != null); Contract.Requires<ArgumentNullException>(update != null); Description = description; _node = node; _node.Target = new WeakReference(rootGetter()); _root = update.Select(x => rootGetter()); } /// <summary> /// Creates a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="root">The root object.</param> /// <param name="expression">The expression.</param> /// <param name="enableDataValidation">Whether or not to track data validation</param> /// <param name="description"> /// A description of the expression. If null, <paramref name="expression"/>'s string representation will be used. /// </param> public static ExpressionObserver Create<T, U>( T root, Expression<Func<T, U>> expression, bool enableDataValidation = false, string description = null) { return new ExpressionObserver(root, Parse(expression, enableDataValidation), description ?? expression.ToString()); } /// <summary> /// Creates a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootObservable">An observable which provides the root object.</param> /// <param name="expression">The expression.</param> /// <param name="enableDataValidation">Whether or not to track data validation</param> /// <param name="description"> /// A description of the expression. If null, <paramref name="expression"/>'s string representation will be used. /// </param> public static ExpressionObserver Create<T, U>( IObservable<T> rootObservable, Expression<Func<T, U>> expression, bool enableDataValidation = false, string description = null) { Contract.Requires<ArgumentNullException>(rootObservable != null); return new ExpressionObserver( rootObservable.Select(o => (object)o), Parse(expression, enableDataValidation), description ?? expression.ToString()); } /// <summary> /// Creates a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootGetter">A function which gets the root object.</param> /// <param name="expression">The expression.</param> /// <param name="update">An observable which triggers a re-read of the getter.</param> /// <param name="enableDataValidation">Whether or not to track data validation</param> /// <param name="description"> /// A description of the expression. If null, <paramref name="expression"/>'s string representation will be used. /// </param> public static ExpressionObserver Create<T, U>( Func<T> rootGetter, Expression<Func<T, U>> expression, IObservable<Unit> update, bool enableDataValidation = false, string description = null) { Contract.Requires<ArgumentNullException>(rootGetter != null); return new ExpressionObserver( () => rootGetter(), Parse(expression, enableDataValidation), update, description ?? expression.ToString()); } /// <summary> /// Attempts to set the value of a property expression. /// </summary> /// <param name="value">The value to set.</param> /// <param name="priority">The binding priority to use.</param> /// <returns> /// True if the value could be set; false if the expression does not evaluate to a /// property. Note that the <see cref="ExpressionObserver"/> must be subscribed to /// before setting the target value can work, as setting the value requires the /// expression to be evaluated. /// </returns> public bool SetValue(object value, BindingPriority priority = BindingPriority.LocalValue) { if (Leaf is SettableNode settable) { var node = _node; while (node != null) { if (node is ITransformNode transform) { value = transform.Transform(value); if (value is BindingNotification) { return false; } } node = node.Next; } return settable.SetTargetValue(value, priority); } return false; } /// <summary> /// Gets a description of the expression being observed. /// </summary> public string Description { get; } /// <summary> /// Gets the expression being observed. /// </summary> public string Expression { get; } /// <summary> /// Gets the type of the expression result or null if the expression could not be /// evaluated. /// </summary> public Type ResultType => (Leaf as SettableNode)?.PropertyType; /// <summary> /// Gets the leaf node. /// </summary> private ExpressionNode Leaf { get { var node = _node; while (node.Next != null) node = node.Next; return node; } } protected override void Initialize() { _value = null; _node.Subscribe(ValueChanged); StartRoot(); } protected override void Deinitialize() { _rootSubscription?.Dispose(); _rootSubscription = null; _node.Unsubscribe(); } protected override void Subscribed(IObserver<object> observer, bool first) { if (!first && _value != null && _value.TryGetTarget(out var value)) { observer.OnNext(value); } } private static ExpressionNode Parse(LambdaExpression expression, bool enableDataValidation) { return ExpressionTreeParser.Parse(expression, enableDataValidation); } private void StartRoot() { if (_root is IObservable<object> observable) { _rootSubscription = observable.Subscribe( x => _node.Target = new WeakReference(x != AvaloniaProperty.UnsetValue ? x : null), x => PublishCompleted(), () => PublishCompleted()); } else { _node.Target = (WeakReference)_root; } } private void ValueChanged(object value) { var broken = BindingNotification.ExtractError(value) as MarkupBindingChainException; broken?.Commit(Description); _value = new WeakReference<object>(value); PublishNext(value); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>SmartCampaignSetting</c> resource.</summary> public sealed partial class SmartCampaignSettingName : gax::IResourceName, sys::IEquatable<SmartCampaignSettingName> { /// <summary>The possible contents of <see cref="SmartCampaignSettingName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>. /// </summary> CustomerCampaign = 1, } private static gax::PathTemplate s_customerCampaign = new gax::PathTemplate("customers/{customer_id}/smartCampaignSettings/{campaign_id}"); /// <summary>Creates a <see cref="SmartCampaignSettingName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SmartCampaignSettingName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static SmartCampaignSettingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SmartCampaignSettingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SmartCampaignSettingName"/> with the pattern /// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="SmartCampaignSettingName"/> constructed from the provided ids. /// </returns> public static SmartCampaignSettingName FromCustomerCampaign(string customerId, string campaignId) => new SmartCampaignSettingName(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SmartCampaignSettingName"/> with pattern /// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SmartCampaignSettingName"/> with pattern /// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>. /// </returns> public static string Format(string customerId, string campaignId) => FormatCustomerCampaign(customerId, campaignId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SmartCampaignSettingName"/> with pattern /// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SmartCampaignSettingName"/> with pattern /// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>. /// </returns> public static string FormatCustomerCampaign(string customerId, string campaignId) => s_customerCampaign.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId))); /// <summary> /// Parses the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item> /// </list> /// </remarks> /// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SmartCampaignSettingName"/> if successful.</returns> public static SmartCampaignSettingName Parse(string smartCampaignSettingName) => Parse(smartCampaignSettingName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SmartCampaignSettingName"/> if successful.</returns> public static SmartCampaignSettingName Parse(string smartCampaignSettingName, bool allowUnparsed) => TryParse(smartCampaignSettingName, allowUnparsed, out SmartCampaignSettingName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item> /// </list> /// </remarks> /// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SmartCampaignSettingName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string smartCampaignSettingName, out SmartCampaignSettingName result) => TryParse(smartCampaignSettingName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SmartCampaignSettingName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string smartCampaignSettingName, bool allowUnparsed, out SmartCampaignSettingName result) { gax::GaxPreconditions.CheckNotNull(smartCampaignSettingName, nameof(smartCampaignSettingName)); gax::TemplatedResourceName resourceName; if (s_customerCampaign.TryParseName(smartCampaignSettingName, out resourceName)) { result = FromCustomerCampaign(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(smartCampaignSettingName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SmartCampaignSettingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CampaignId = campaignId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="SmartCampaignSettingName"/> class from the component parts of /// pattern <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> public SmartCampaignSettingName(string customerId, string campaignId) : this(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCampaign: return s_customerCampaign.Expand(CustomerId, CampaignId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SmartCampaignSettingName); /// <inheritdoc/> public bool Equals(SmartCampaignSettingName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SmartCampaignSettingName a, SmartCampaignSettingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SmartCampaignSettingName a, SmartCampaignSettingName b) => !(a == b); } public partial class SmartCampaignSetting { /// <summary> /// <see cref="SmartCampaignSettingName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal SmartCampaignSettingName ResourceNameAsSmartCampaignSettingName { get => string.IsNullOrEmpty(ResourceName) ? null : SmartCampaignSettingName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } } }