context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Pros and cons for MonoBehaviour (component) and ScriptableObject (asset): // // Component: // - PRO: Runtime changes take place immediately // - CON: Runtime changes do not persist after the game exits // - PRO: Can reference objects in the scene // - CON: Changes go into Main.unity; harder to review // // Asset: // - CON: Runtime changes are visible only after the .asset hot-reloads // - PRO: Runtime changes persist after the game exits // - CON: Cannot reference objects in the scene; only prefabs and other assets // - PRO: Changes go into their own .asset; easier to review using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; namespace TiltBrush { // These names are used in our analytics, so they must be protected from obfuscation. // Do not change the names of any of them, unless they've never been released. [Serializable] public enum SdkMode { Unset = -1, Oculus = 0, SteamVR, Cardboard_Deprecated, Monoscopic, Ods, Gvr, } // These names are used in our analytics, so they must be protected from obfuscation. // Do not change the names of any of them, unless they've never been released. // This enum should be "VrHeadsetHardware". Controller type is not necessarily // implied by headset type. [Serializable] public enum VrHardware { Unset, None, Rift, Vive, Daydream, Wmr, Quest, } /// These are not used in analytics. They indicate the type of tool tip description that will appear /// on a UI component. public enum DescriptionType { None = -1, Button = 0, Slider, PreviewCube, } /// Script Ordering: /// - does not need to come after anything /// - must come before everything that uses App.Config (ie, all scripts) /// /// Used to store global configuration data and constants. /// For per-platform data, see PlatformConfig.cs /// Despite being public, all this data should be considered read-only /// public class Config : MonoBehaviour { // When set, ModelWidget creation waits for Poly models to be loaded into memory. // When not set, ModelWidgets may be created with "dummy" Models which are automatically // replaced with the real Model once it's loaded. public readonly bool kModelWidgetsWaitForLoad = true; [System.Serializable] public class BrushReplacement { [BrushDescriptor.AsStringGuid] public string FromGuid; [BrushDescriptor.AsStringGuid] public string ToGuid; } private class UserConfigChange { public FieldInfo section; public MemberInfo setting; public object value; } // This intentionally breaks the naming convention of m_Instance because it is only intended to be // used by App. static public Config m_SingletonState; [Header("Startup")] public string m_FakeCommandLineArgsInEditor; [Header("Overwritten by build process")] [SerializeField] private PlatformConfig m_PlatformConfig; // True for experimental mode. // Cannot be ifdef'd out, because it is modified during the build process. // Public to allow App.cs and BuildTiltBrush.cs to access it; do not use it otherwise. public bool m_IsExperimental; // The sdk mode indicates which SDK (OVR, SteamVR, etc.) that we're using to drive the display. public SdkMode m_SdkMode; // Whether or not to just do an automatic profile and then exit. public bool m_AutoProfile; // How long to wait before starting to profile. public float m_AutoProfileWaitTime = 10f; [Header("App")] public SecretsConfig Secrets; public string[] m_SketchFiles = new string[0]; [NonSerialized] public bool m_QuickLoad = true; public SecretsConfig.ServiceAuthData GoogleSecrets => Secrets[SecretsConfig.Service.Google]; public SecretsConfig.ServiceAuthData SketchfabSecrets => Secrets[SecretsConfig.Service.Sketchfab]; public SecretsConfig.ServiceAuthData OculusSecrets => Secrets[SecretsConfig.Service.Oculus]; public SecretsConfig.ServiceAuthData OculusMobileSecrets => Secrets[SecretsConfig.Service.OculusMobile]; // This indicates which hardware (Rift or Vive) is being used. This is distinct from which SDK // is being used (Oculus VR, Steam's Open VR, Monoscopic, etc.). public VrHardware VrHardware { // This is set lazily the first time VrHardware is accesssed. get { if (m_VrHardware == TiltBrush.VrHardware.Unset) { if (m_SdkMode == SdkMode.Oculus) { if (App.Config.IsMobileHardware) { m_VrHardware = VrHardware.Quest; } else { m_VrHardware = VrHardware.Rift; } } else if (m_SdkMode == SdkMode.SteamVR) { // If SteamVR fails for some reason we will discover it here. try { if (Valve.VR.OpenVR.System == null) { m_VrHardware = VrHardware.None; return m_VrHardware; } } catch (Exception) { m_VrHardware = VrHardware.None; return m_VrHardware; } // GetHwTrackedInSteamVr relies on headset detection, so controllers don't have to be on. m_VrHardware = GetHwTrackedInSteamVr(); } else if (m_SdkMode == SdkMode.Gvr) { m_VrHardware = TiltBrush.VrHardware.Daydream; } else { m_VrHardware = VrHardware.None; } } return m_VrHardware; } } public String HeadsetModelName { get { if(string.IsNullOrEmpty(m_HeadsetModelName)) { m_HeadsetModelName = UnityEngine.XR.XRDevice.model; } return m_HeadsetModelName; } } /// Return a value kinda sorta half-way between "building for Android" and "running on Android" /// In order of increasing strictness, here are the in-Editor semantics of various methods /// of querying the platform. All of these methods return true when running on-device. /// Note that each level is a strict subset of the level(s) above: /// /// 1. true if build target is Android /// #if UNITY_ANDROID / #endif /// EditorUserBuildSetings.activeBuildTarget == BuildTarget.Android /// 2. true if build target is Android AND if SpoofMobileHardware.MobileHardware is set /// Config.IsMobileHardware /// 3. never true in Editor; only true on-device /// Application.platform == RuntimePlatform.Android /// App.Config.IsMobileHardware && !SpoofMobileHardware.MobileHardware: /// /// TODO: Can we get away with just #1 and #3, and remove #2? That would let us remove /// SpoofMobileHardware.MobileHardware too. public bool IsMobileHardware { // Only sadness will ensue if the user tries to set Override.MobileHardware=true // but their editor platform is still set to Windows. #if UNITY_EDITOR && UNITY_ANDROID get { return Application.platform == RuntimePlatform.Android || SpoofMobileHardware.MobileHardware; } #else get { return Application.platform == RuntimePlatform.Android; } #endif } [Header("Ods")] public int m_OdsNumFrames = 0; public float m_OdsFps = 30; public string m_OdsOutputPath = ""; public string m_OdsOutputPrefix = ""; [NonSerialized] public bool m_OdsPreview = false; [NonSerialized] public bool m_OdsCollapseIpd = true; [NonSerialized] public float m_OdsTurnTableDegrees = 0.0f; #if UNITY_EDITOR [Header("Editor-only")] // Force use of a particular controller geometry, for testing [Tooltip("Set this to a prefab in Assets/Prefabs/VrSystems/VrControllers/OVR")] public GameObject m_ControlsPrefabOverrideOvr; [Tooltip("Set this to a prefab in Assets/Prefabs/VrSystems/VrControllers/SteamVr")] public GameObject m_ControlsPrefabOverrideSteamVr; #endif [Header("Versioning")] public string m_VersionNumber; // eg "17.0b", "18.3" public string m_BuildStamp; // eg "f73783b61", "f73783b61-exp", "(menuitem)" [Header("Misc")] public GameObject m_SteamVrRenderPrefab; public bool m_UseBatchedBrushes; // Delete Batch's GeometryPool after about a second. public bool m_EnableBatchMemoryOptimization; public string m_MediaLibraryReadme; public DropperTool m_Dropper; public bool m_AxisManipulationIsResize; public GameObject m_LabsButtonOverlayPrefab; public bool m_GpuIntersectionEnabled = true; public bool m_AutosaveRestoreEnabled = false; public bool m_AllowWidgetPinning; public bool m_DebugWebRequest; public bool m_ToggleProfileOnAppButton = false; [Header("Global Shaders")] public Shader m_BlitToComputeShader; [Header("Upload and Export")] // Some brushes put a birth time in the vertex attributes; because we export // this data (we really shouldn't) it's helpful to disable it when one needs // deterministic export. public bool m_ForceDeterministicBirthTimeForExport; [NonSerialized] public List<string> m_FilePatternsToExport; [NonSerialized] public string m_ExportPath; [NonSerialized] public string m_VideoPathToRender; // TODO: m22 ripcord; remove for m23 public bool m_EnableReferenceModelExport; // TODO: m22 ripcord; remove for m23 public bool m_EnableGlbVersion2; [Tooltip("Causes the temporary Upload directory to be kept around (Editor only)")] public bool m_DebugUpload; public TiltBrushToolkit.TbtSettings m_TbtSettings; [Header("Loading")] public bool m_ReplaceBrushesOnLoad; [SerializeField] List<BrushReplacement> m_BrushReplacementMap; public string m_IntroSketchUsdFilename; [Range(0.001f, 4)] public float m_IntroSketchSpeed = 1.0f; public bool m_IntroLooped = false; [Header("Shader Warmup")] public bool CreateShaderWarmupList; [Header("Description Prefabs")] [SerializeField] GameObject m_ButtonDescriptionOneLinePrefab; [SerializeField] GameObject m_ButtonDescriptionTwoLinesPrefab; [SerializeField] GameObject m_ButtonDescriptionThreeLinesPrefab; [SerializeField] GameObject m_SliderDescriptionOneLinePrefab; [SerializeField] GameObject m_SliderDescriptionTwoLinesPrefab; [SerializeField] GameObject m_PreviewCubeDescriptionOneLinePrefab; [SerializeField] GameObject m_PreviewCubeDescriptionTwoLinesPrefab; public GameObject CreateDescriptionFor(DescriptionType type, int numberOfLines) { switch (type) { case DescriptionType.None: return null; case DescriptionType.Button: switch (numberOfLines) { case 1: return Instantiate(m_ButtonDescriptionOneLinePrefab); case 2: return Instantiate(m_ButtonDescriptionTwoLinesPrefab); case 3: return Instantiate(m_ButtonDescriptionThreeLinesPrefab); default: throw new Exception($"{type} description does not have a ${numberOfLines} line variant"); } case DescriptionType.Slider: switch (numberOfLines) { case 1: return Instantiate(m_SliderDescriptionOneLinePrefab); case 2: return Instantiate(m_SliderDescriptionTwoLinesPrefab); default: throw new Exception($"{type} description does not have a ${numberOfLines} line variant"); } case DescriptionType.PreviewCube: switch (numberOfLines) { case 1: return Instantiate(m_PreviewCubeDescriptionOneLinePrefab); case 2: return Instantiate(m_PreviewCubeDescriptionTwoLinesPrefab); default: throw new Exception($"{type} description does not have a ${numberOfLines} line variant"); } default: throw new Exception($"Unknown description type: {type}"); } } public bool OfflineRender { get { return !string.IsNullOrEmpty(m_VideoPathToRender) && m_SdkMode != SdkMode.Ods; } } public PlatformConfig PlatformConfig { get { #if UNITY_EDITOR // Ignore m_PlatformConfig: we want whatever a build would give us. // Should we cache this value? var ret = EditTimeAssetReferences.Instance.GetConfigForBuildTarget( UnityEditor.EditorUserBuildSettings.activeBuildTarget); // This is just to keep the compiler from spewing a warning about this field if (ret == null) { ret = m_PlatformConfig; } return ret; #else return m_PlatformConfig; #endif } } // ------------------------------------------------------------ // Private data // ------------------------------------------------------------ private VrHardware m_VrHardware = VrHardware.Unset; // This should not be used outside of // VrHardware as it is lazily set inside // VrHardware. private Dictionary<Guid, Guid> m_BrushReplacement = null; private List<UserConfigChange> m_UserConfigChanges = new List<UserConfigChange>(); private string m_HeadsetModelName; // ------------------------------------------------------------ // Yucky externals // ------------------------------------------------------------ public Guid GetReplacementBrush(Guid original) { Guid replacement; if (m_BrushReplacement.TryGetValue(original, out replacement)) { return replacement; } return original; } void ParseArgs(string[] args) { System.Collections.Generic.List<string> files = new System.Collections.Generic.List<string>(); bool isInBatchMode = false; // If someone entered a sketch via the editor, we need to preserve that here. foreach (var s in m_SketchFiles) { files.Add(s); } // Process all args. for (int i = 0; i < args.Length; i++) { if (i == 0) { // Skip "TiltBrush.exe" continue; } else if (args[i] == "--captureOds") { m_SdkMode = SdkMode.Ods; UnityEngine.XR.XRSettings.enabled = false; Debug.Log("CaptureODS: Enable "); } else if (args[i] == "--noQuickLoad") { m_QuickLoad = false; Debug.Log("QuickLoad: Disable "); } else if (args[i].EndsWith(SaveLoadScript.TILT_SUFFIX)) { files.Add(args[i]); Debug.LogFormat("Sketch: {0}", args[i]); } else if (args[i] == "--outputPath") { if (i == args.Length - 1) { throw new ApplicationException("Invalid outputPath argument, path expected"); } m_OdsOutputPath = args[++i]; Debug.LogFormat("ODS Output Path: {0}", args[i]); } else if (args[i] == "--outputPrefix") { if (i == args.Length - 1) { throw new ApplicationException("Invalid prefix argument, name expected"); } m_OdsOutputPrefix = args[i]; Debug.LogFormat("ODS Output Prefix: {0}", args[i]); } else if (args[i] == "--preview") { // 1k is ugly enough to stop people from shipping videos with this quality, but clear enough // to see a preview. To some people, 2k may look good enough to ship, but is horribly // aliased in the HMD, so let's not give an option for that. m_OdsPreview = true; Debug.LogFormat("Enable: ODS Preview"); } else if (args[i] == "--noCorrection") { m_OdsCollapseIpd = false; Debug.LogFormat("Enable: NO Correction"); } else if (args[i] == "--turnTable") { if (i == args.Length - 1) { throw new ApplicationException("Invalid turnTable rotation argument, N degrees expected"); } if (!float.TryParse(args[++i], out m_OdsTurnTableDegrees)) { throw new ApplicationException("Invalid turnTable rotation argument, " + "angle in degrees expected"); } Debug.LogFormat("Enable: Turntable {0}", m_OdsTurnTableDegrees); } else if (args[i] == "--numFrames") { if (i == args.Length - 1) { throw new ApplicationException("Invalid numFrames argument, N frames expected"); } if (!int.TryParse(args[++i], out m_OdsNumFrames)) { throw new ApplicationException("Invalid numFrames argument, " + "integer frame count expected"); } Debug.LogFormat("ODS Num Frames: {0}", m_OdsNumFrames); } else if (args[i] == "--fps") { if (i == args.Length - 1) { throw new ApplicationException("Invalid fps argument, value expected"); } if (!float.TryParse(args[++i], out m_OdsFps)) { throw new ApplicationException("Invalid fps argument, " + "floating point frame rate expected"); } Debug.LogFormat("ODS FPS: {0}", m_OdsFps); } else if (args[i] == "--export") { if (i == args.Length - 1) { throw new ApplicationException("Invalid export argument, filename expected."); } if (m_FilePatternsToExport == null) { m_FilePatternsToExport = new List<string>(); } while (((i + 1) < args.Length) && !args[i + 1].StartsWith("-")) { m_FilePatternsToExport.Add(args[++i]); } } else if (args[i] == "--exportPath") { if (i == args.Length - 1) { throw new ApplicationException("Invalid exportPath argument, path expected."); } m_ExportPath = args[i + 1]; } else if (args[i] == "-batchmode" || args[i] == "-nographics") { // If we're in batch mode, do monoscopic. isInBatchMode = true; } else if (args[i] == "--renderCameraPath") { if (i == args.Length - 1) { throw new ApplicationException("Invalid renderCameraPath argument, tbpath expected."); } m_VideoPathToRender = args[++i]; m_SdkMode = SdkMode.Monoscopic; UnityEngine.XR.XRSettings.enabled = false; } else if (args[i].Contains(".")) { if (i == args.Length - 1) { throw new ApplicationException("User Config Settings require an argument."); } ParseUserSetting(args[i], args[++i]); } else { Debug.LogFormat("Unknown argument: {0}", args[i]); } } if (isInBatchMode) { if (OfflineRender || m_SdkMode == SdkMode.Ods) { throw new ApplicationException("Video rendering not supported in batch mode."); } m_SdkMode = SdkMode.Monoscopic; } m_SketchFiles = files.ToArray(); } // ------------------------------------------------------------ // Yucky internals // ------------------------------------------------------------ #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) public static bool IsExperimental { get { return App.Config.m_IsExperimental; } } #endif void Awake() { m_SingletonState = this; #if UNITY_EDITOR if (!string.IsNullOrEmpty(m_FakeCommandLineArgsInEditor)) { try { // This splits the arguments by spaces, excepting arguments enclosed by quotes. var args = ("TiltBrush.exe " + m_FakeCommandLineArgsInEditor).Split('"') .Select((element, index) => index % 2 == 0 ? element.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) : new string[] { element }) .SelectMany(element => element).ToArray(); ParseArgs(args); } catch (Exception e) { UnityEngine.Debug.LogException(e); Application.Quit(); } } #elif !UNITY_ANDROID try { ParseArgs(System.Environment.GetCommandLineArgs()); } catch (Exception e) { UnityEngine.Debug.LogException(e); Application.Quit(); } #endif m_BrushReplacement = new Dictionary<Guid, Guid>(); #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (IsExperimental) { foreach (var brush in m_BrushReplacementMap) { m_BrushReplacement.Add(new Guid(brush.FromGuid), new Guid(brush.ToGuid)); } } #endif } private string GetSteamVrDeviceStringProperty(Valve.VR.ETrackedDeviceProperty property) { uint index = 0; // Index 0 is always the headset var system = Valve.VR.OpenVR.System; // If system == null, then somehow, the SteamVR SDK was not properly loaded in. Debug.Assert(system != null, "OpenVR System not found, check \"Virtual Reality Supported\""); var error = Valve.VR.ETrackedPropertyError.TrackedProp_Success; var capacity = system.GetStringTrackedDeviceProperty(index, property, null, 0, ref error); System.Text.StringBuilder buffer = new System.Text.StringBuilder((int)capacity); system.GetStringTrackedDeviceProperty(index, property, buffer, capacity, ref error); if (error == Valve.VR.ETrackedPropertyError.TrackedProp_Success) { return buffer.ToString(); } else { Debug.LogErrorFormat("GetStringTrackedDeviceProperty error {0}", error.ToString()); return null; } } // Checking what kind of hardware (Rift, Vive, of WMR) is being used in SteamVR. private VrHardware GetHwTrackedInSteamVr() { string manufacturer = GetSteamVrDeviceStringProperty( Valve.VR.ETrackedDeviceProperty.Prop_ManufacturerName_String); if (string.IsNullOrEmpty(manufacturer)) { OutputWindowScript.Error("Could not determine VR Headset manufacturer."); return VrHardware.Vive; } else if (manufacturer.Contains("Oculus")) { return VrHardware.Rift; } else if (manufacturer.Contains("WindowsMR")) { return VrHardware.Wmr; } else { return VrHardware.Vive; } } /// Parses a setting taken from the command line of the form --Section.Setting value /// Where Section and Setting should be valid members of UserConfig. /// Stores the result in a list for applying to UserConfigs later. private void ParseUserSetting(string setting, string value) { var parts = setting.Split('.'); string sectionName = parts[0].Substring(2); string settingName = parts[1]; UserConfigChange change = new UserConfigChange(); change.section = typeof(UserConfig).GetField(sectionName); if (change.section == null) { throw new ApplicationException( string.Format("User Config section '{0}' not recognised.", sectionName)); } change.setting = change.section.FieldType.GetMember(settingName).FirstOrDefault(); if (change.setting == null) { throw new ApplicationException(string.Format( "User Config section '{0}' does not have a {1} value.", sectionName, settingName)); } Type memberType = null; if (change.setting is FieldInfo) { memberType = ((FieldInfo)change.setting).FieldType; } else if (change.setting is PropertyInfo) { memberType = ((PropertyInfo) change.setting).PropertyType; } else { throw new ApplicationException(string.Format( "User Config section '{0}' does not have a {1} value.", sectionName, settingName)); } try { change.value = Convert.ChangeType(value, memberType); } catch (Exception) { throw new ApplicationException(string.Format( "User Config {0}.{1} cannot be set to '{2}'.", sectionName, settingName, value)); } m_UserConfigChanges.Add(change); } /// Apply any changes specified on the command line to a user config object public void ApplyUserConfigOverrides(UserConfig userConfig) { foreach (var change in m_UserConfigChanges) { var section = change.section.GetValue(userConfig); if (section == null) { Debug.LogWarningFormat("Weird - could not access UserConfig.{0}.", change.section.Name); continue; } if (change.setting is FieldInfo) { ((FieldInfo) change.setting).SetValue(section, change.value); } else { ((PropertyInfo) change.setting).SetValue(section, change.value, null); } change.section.SetValue(userConfig, section); } foreach (var replacement in userConfig.Testing.BrushReplacementMap) { m_BrushReplacement.Add(replacement.Key, replacement.Value); } // Report deprecated members to users. if (userConfig.Flags.HighResolutionSnapshots) { OutputWindowScript.Error("HighResolutionSnapshots is deprecated."); OutputWindowScript.Error("Use SnapshotHeight and SnapshotWidth."); } } #if UNITY_EDITOR public void OnValidate() { // This is now getting run when entering playmode. // Unity doesn't allow VR SDKs to change at runtime. if (UnityEditor.EditorApplication.isPlaying) { return; } bool useVrSdk = m_SdkMode == SdkMode.Oculus || m_SdkMode == SdkMode.SteamVR || m_SdkMode == SdkMode.Gvr; // Writing to this sets the scene-dirty flag, so don't do it unless necessary if (UnityEditor.PlayerSettings.virtualRealitySupported != useVrSdk) { UnityEditor.PlayerSettings.virtualRealitySupported = useVrSdk; } // This hotswaps vr sdks based on selection. var buildTargetGroups = new List<UnityEditor.BuildTargetGroup>(); string[] newDevices; switch (m_SdkMode) { case SdkMode.Gvr: newDevices = new string[] { "daydream" }; buildTargetGroups.Add(UnityEditor.BuildTargetGroup.Android); break; case SdkMode.Oculus: newDevices = new string[] { "Oculus" }; buildTargetGroups.Add(UnityEditor.BuildTargetGroup.Android); buildTargetGroups.Add(UnityEditor.BuildTargetGroup.Standalone); break; case SdkMode.SteamVR: newDevices = new string[] { "OpenVR" }; buildTargetGroups.Add(UnityEditor.BuildTargetGroup.Standalone); break; default: newDevices = new string[] { "" }; break; } foreach (var group in buildTargetGroups) { // TODO use the public api (see BuildTiltBrush) UnityEditorInternal.VR.VREditor.SetVirtualRealitySDKs(group, newDevices); } } /// Called at build time, just before this Config instance is saved to Main.unity public void DoBuildTimeConfiguration(UnityEditor.BuildTarget target) { m_PlatformConfig = EditTimeAssetReferences.Instance.GetConfigForBuildTarget(target); } #endif } } // namespace TiltBrush
using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel.Design; using Microsoft.Win32; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.Collections.Generic; using System.Reflection; using EnvDTE; using System.Linq; using System.Collections.ObjectModel; using System.Windows; using System.Threading; using Alphaleonis.VSProjectSetMgr; using System.Windows.Threading; namespace Alphaleonis.VSProjectSetMgr { public enum ProjectOptions { All = __VSENUMPROJFLAGS.EPF_ALLINSOLUTION, Unloaded = __VSENUMPROJFLAGS.EPF_UNLOADEDINSOLUTION, Loaded = __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION } interface IProjectDescriptor : IEquatable<IProjectDescriptor> { Guid Id { get; } string Name { get; } Guid Kind { get; } } class ProjectDescriptor : IProjectDescriptor { private readonly Guid m_id; private readonly string m_name; private readonly Guid m_kind; public ProjectDescriptor(Guid id, string name, Guid kind) { m_id = id; m_name = name; m_kind = kind; } public Guid Id { get { return m_id; } } public string Name { get { return m_name; } } public Guid Kind { get { return m_kind; } } public bool Equals(IProjectDescriptor other) { return Id.Equals(other.Id); } public override bool Equals(object obj) { return Equals(obj as ProjectDescriptor); } public override int GetHashCode() { return Id.GetHashCode(); } public override string ToString() { return string.Format("Project {0}", Name); } } public class SolutionInfo { private readonly string m_solutionDirectory; private readonly string m_solutionFile; private readonly string m_solutionOptionsFile; public SolutionInfo(string solutionDirectory, string solutionFile, string solutionOptionsFile) { m_solutionDirectory = solutionDirectory; m_solutionFile = solutionFile; m_solutionOptionsFile = solutionOptionsFile; } public string SolutionDirectory { get { return m_solutionDirectory; } } public string SolutionFile { get { return m_solutionFile; } } public string SolutionOptionsFile { get { return m_solutionOptionsFile; } } } class SolutionManager { #region Private Fields private readonly static Guid m_outputPaneGuid = new Guid("BF899951-951D-4CC6-9D57-8C42C710BE35"); private readonly static Guid m_solutionFolderId = new Guid("{66A26720-8FB5-11D2-AA7E-00C04F688DDE}"); private readonly IVsSolution m_solution; private readonly IVsSolution4 m_solution4; private readonly IOutputWindow m_outputWindow; #endregion public SolutionManager(IVsSolution solution, IOutputWindow outputWindow) { Dispatcher.CurrentDispatcher.VerifyAccess(); if (solution == null) throw new ArgumentNullException("solution", "solution is null."); m_solution = solution; m_solution4 = (IVsSolution4)solution; m_outputWindow = outputWindow; } #region Public Methods public void WriteLog(string message) { m_outputWindow.GetOrCreatePane(m_outputPaneGuid, "Project Set Manager", true).WriteLine(message); } public SolutionInfo GetSolutionInfo() { Dispatcher.CurrentDispatcher.VerifyAccess(); string solOptsFile; string solFile; string solDir; ErrorHandler.ThrowOnFailure(m_solution.GetSolutionInfo(out solDir, out solFile, out solOptsFile)); return new SolutionInfo(solDir, solFile, solOptsFile); } public IEnumerable<ProjectDescriptor> GetProjects(ProjectOptions options, bool includeMiscProjectsAndSolutionFolders = false) { Dispatcher.CurrentDispatcher.VerifyAccess(); IEnumHierarchies ppEnum; Guid tempGuid = Guid.Empty; ErrorHandler.ThrowOnFailure(m_solution.GetProjectEnum((uint)options, ref tempGuid, out ppEnum)); if (ppEnum != null) { uint actualResult = 0; IVsHierarchy[] nodes = new IVsHierarchy[1]; while (0 == ppEnum.Next(1, nodes, out actualResult)) { Guid projectId; object projectName; ErrorHandler.ThrowOnFailure(nodes[0].GetGuidProperty((uint)Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectId)); ErrorHandler.ThrowOnFailure(nodes[0].GetProperty((uint)Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectName, out projectName)); Guid projectTypeId; Guid projectKind = Guid.Empty; if (ErrorHandler.Succeeded(nodes[0].GetGuidProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_TypeGuid, out projectTypeId))) { object pVar; if (ErrorHandler.Succeeded(nodes[0].GetProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out pVar))) { Project project = pVar as Project; if (project != null) Guid.TryParse(project.Kind, out projectKind); } } // Solution Folder: {66A26720-8FB5-11D2-AA7E-00C04F688DDE} // If the project is actually a solution folder and we have elected to skip those, then skip it. if (!includeMiscProjectsAndSolutionFolders) { if (projectKind == Guid.Parse(EnvDTE.Constants.vsProjectKindSolutionItems) || projectKind == Guid.Parse(EnvDTE.Constants.vsProjectKindMisc)) { continue; } } yield return new ProjectDescriptor(projectId, (string)projectName, projectKind); } } } public void UnloadProject(ProjectDescriptor project) { Dispatcher.CurrentDispatcher.VerifyAccess(); Guid projectId = project.Id; WriteLog($"Unloading project \"{project.Name ?? project.Id.ToString()}\""); try { ErrorHandler.ThrowOnFailure(m_solution4.UnloadProject(ref projectId, (uint)_VSProjectUnloadStatus.UNLOADSTATUS_UnloadedByUser)); } catch (Exception ex) { WriteLog($"Error: Failed to unload project \"{project.Name ?? project.Id.ToString()}\"; {ex.Message}"); } } public void LoadProject(ProjectDescriptor project) { Dispatcher.CurrentDispatcher.VerifyAccess(); Guid projectId = project.Id; WriteLog($"Loading project \"{project.Name ?? project.Id.ToString()}\""); try { ErrorHandler.ThrowOnFailure(m_solution4.ReloadProject(ref projectId)); } catch (Exception ex) { WriteLog($"Error: Failed to load project \"{project.Name ?? project.Id.ToString()}\"; {ex.Message}"); } } public void UnloadExclusive(ISet<Guid> projects) { Dispatcher.CurrentDispatcher.VerifyAccess(); foreach (ProjectDescriptor project in GetProjects(ProjectOptions.Unloaded, false).Where(p => !projects.Contains(p.Id))) LoadProject(project); foreach (var project in GetProjects(ProjectOptions.Loaded, false).Where(p => projects.Contains(p.Id))) UnloadProject(project); } public void LoadExclusive(ISet<Guid> projects) { Dispatcher.CurrentDispatcher.VerifyAccess(); foreach (var project in GetProjects(ProjectOptions.Loaded, false).Where(p => !projects.Contains(p.Id))) UnloadProject(project); foreach (var project in GetProjects(ProjectOptions.Unloaded, false).Where(p => projects.Contains(p.Id))) LoadProject(project); } public void Unload(ISet<Guid> projects) { Dispatcher.CurrentDispatcher.VerifyAccess(); foreach (var project in GetProjects(ProjectOptions.Loaded, false).Where(p => projects.Contains(p.Id))) UnloadProject(project); } public void Load(ISet<Guid> projects) { Dispatcher.CurrentDispatcher.VerifyAccess(); foreach (var project in GetProjects(ProjectOptions.Unloaded, false).Where(p => projects.Contains(p.Id))) { LoadProject(project); } } public void SaveUserOpts() { Dispatcher.CurrentDispatcher.VerifyAccess(); m_solution4.WriteUserOptsFile(); } public ISolutionHierarchyContainerItem GetSolutionHierarchy(bool visibleNodesOnly = false) { Dispatcher.CurrentDispatcher.VerifyAccess(); ISolutionHierarchyContainerItem solution = CreateSolutionHierarchyItem((IVsHierarchy)m_solution, (uint)Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT) as ISolutionHierarchyContainerItem; if (solution != null) PopulateHierarchy(solution.VsHierarchy, solution.HierarchyItemId, visibleNodesOnly, solution, solution); return solution; } public ISolutionHierarchyItem CreateSolutionHierarchyItem(IVsHierarchy hierarchy, uint itemId) { Dispatcher.CurrentDispatcher.VerifyAccess(); int hr; IntPtr nestedHierarchyObj; uint nestedItemId; Guid hierGuid = typeof(IVsHierarchy).GUID; // Check first if this node has a nested hierarchy. If so, then there really are two // identities for this node: 1. hierarchy/itemid 2. nestedHierarchy/nestedItemId. // We will recurse and call EnumHierarchyItems which will display this node using // the inner nestedHierarchy/nestedItemId identity. hr = hierarchy.GetNestedHierarchy(itemId, ref hierGuid, out nestedHierarchyObj, out nestedItemId); if (VSConstants.S_OK == hr && IntPtr.Zero != nestedHierarchyObj) { IVsHierarchy nestedHierarchy = Marshal.GetObjectForIUnknown(nestedHierarchyObj) as IVsHierarchy; Marshal.Release(nestedHierarchyObj); // we are responsible to release the refcount on the out IntPtr parameter if (nestedHierarchy != null) { // Display name and type of the node in the Output Window return CreateSolutionHierarchyItem(nestedHierarchy, nestedItemId); } return null; } else { return CreateSolutionHierarchyItemDirect(hierarchy, itemId); } } #endregion #region Private Methods private static uint GetItemId(object pvar) { if (pvar == null) return VSConstants.VSITEMID_NIL; if (pvar is int) return (uint)(int)pvar; if (pvar is uint) return (uint)pvar; if (pvar is short) return (uint)(short)pvar; if (pvar is ushort) return (uint)(ushort)pvar; if (pvar is long) return (uint)(long)pvar; return VSConstants.VSITEMID_NIL; } private static bool IsSolutionFolder(IVsHierarchy hierarchy, uint itemId) { Dispatcher.CurrentDispatcher.VerifyAccess(); object pVar; hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out pVar); Guid kindId; return pVar != null && pVar is Project && Guid.TryParse(((Project)pVar).Kind, out kindId) && kindId == m_solutionFolderId; } private static ISolutionHierarchyItem CreateSolutionHierarchyItemDirect(IVsHierarchy hierarchy, uint itemId) { Dispatcher.CurrentDispatcher.VerifyAccess(); object pVar; Guid id; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_Name, out pVar)); string projectName = (string)pVar; int hr = hierarchy.GetGuidProperty(itemId, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out id); hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out pVar); if (pVar == null) { try { if (ErrorHandler.Succeeded(hierarchy.GetProperty(itemId, (int)__VSHPROPID5.VSHPROPID_ProjectUnloadStatus, out pVar))) { return new SolutionHierarchyItem(hierarchy, itemId, SolutionHierarchyItemType.UnloadedProject); } } catch { } return null; } else { Project pr = pVar as Project; if (pr != null) { Guid projectKind; if (Guid.TryParse(pr.Kind, out projectKind) && projectKind == m_solutionFolderId) { return new SolutionHierarchyContainerItem(hierarchy, itemId, SolutionHierarchyItemType.SolutionFolder); } else { return new SolutionHierarchyItem(hierarchy, itemId, SolutionHierarchyItemType.Project); } } else { Solution sol = pVar as Solution; if (sol == null) { // Unknown item return null; } else { // Solution return new SolutionHierarchyContainerItem(hierarchy, itemId, SolutionHierarchyItemType.Solution); } } } } private ISolutionHierarchyItem PopulateHierarchy(IVsHierarchy hierarchy, uint itemId, bool visibleNodesOnly, ISolutionHierarchyContainerItem solutionNode, ISolutionHierarchyItem thisNode) { Dispatcher.CurrentDispatcher.VerifyAccess(); ISolutionHierarchyContainerItem container = thisNode as ISolutionHierarchyContainerItem; if (container != null) { if (solutionNode == null) solutionNode = container; IEnumerable<uint> childIds = EnumerateChildIds(hierarchy, itemId, visibleNodesOnly); List<ISolutionHierarchyItem> list = new List<ISolutionHierarchyItem>(); foreach (uint childId in childIds) { ISolutionHierarchyItem childItem = CreateSolutionHierarchyItem(hierarchy, childId); if (childItem != null) { container.Children.Add(childItem); list.Add(childItem); // Due to a bug in VS, enumerating the solution node actually returns all projects within the solution, at any depth, // so we need to remove them here if found. if (container != solutionNode) { solutionNode.Children.Remove(childItem.Id); } } } foreach (var childItem in list.OfType<ISolutionHierarchyContainerItem>()) { if (container.Children.Contains(childItem.Id)) // On SolutionNode the child may actually have been removed (see below) { PopulateHierarchy(childItem.VsHierarchy, childItem.HierarchyItemId, visibleNodesOnly, solutionNode, childItem); } } } return thisNode; } private ISolutionHierarchyItem GetSolutionHierarchy(IVsHierarchy hierarchy, uint itemId, bool visibleNodesOnly, ISolutionHierarchyContainerItem solutionNode) { Dispatcher.CurrentDispatcher.VerifyAccess(); int hr; IntPtr nestedHierarchyObj; uint nestedItemId; Guid hierGuid = typeof(IVsHierarchy).GUID; // Check first if this node has a nested hierarchy. If so, then there really are two // identities for this node: 1. hierarchy/itemid 2. nestedHierarchy/nestedItemId. // We will recurse and call EnumHierarchyItems which will display this node using // the inner nestedHierarchy/nestedItemId identity. hr = hierarchy.GetNestedHierarchy(itemId, ref hierGuid, out nestedHierarchyObj, out nestedItemId); if (VSConstants.S_OK == hr && IntPtr.Zero != nestedHierarchyObj) { IVsHierarchy nestedHierarchy = Marshal.GetObjectForIUnknown(nestedHierarchyObj) as IVsHierarchy; Marshal.Release(nestedHierarchyObj); // we are responsible to release the refcount on the out IntPtr parameter if (nestedHierarchy != null) { // Display name and type of the node in the Output Window return GetSolutionHierarchy(nestedHierarchy, nestedItemId, visibleNodesOnly, solutionNode); } return null; } else { ISolutionHierarchyItem item = CreateSolutionHierarchyItemDirect(hierarchy, itemId); ISolutionHierarchyContainerItem container = item as ISolutionHierarchyContainerItem; if (container != null) { if (solutionNode == null) solutionNode = container; IEnumerable<uint> childIds = EnumerateChildIds(hierarchy, itemId, visibleNodesOnly); if (container == solutionNode && solutionNode != null) childIds = childIds.OrderBy(id => IsSolutionFolder(hierarchy, id) ? 1 : 0); foreach (uint childId in childIds) { ISolutionHierarchyItem childItem = GetSolutionHierarchy(hierarchy, childId, visibleNodesOnly, solutionNode); if (childItem != null) { container.Children.Add(childItem); // Due to a bug in VS, enumerating the solution node actually returns all projects within the solution, at any depth, // so we need to remove them here if found. if (container != solutionNode) solutionNode.Children.Remove(childItem.Id); } } } return item; } } private static IEnumerable<uint> EnumerateChildIds(IVsHierarchy hierarchy, uint itemId, bool visibleNodesOnly) { Dispatcher.CurrentDispatcher.VerifyAccess(); object pVar; int hr = hierarchy.GetProperty(itemId, ((visibleNodesOnly ? (int)__VSHPROPID.VSHPROPID_FirstVisibleChild : (int)__VSHPROPID.VSHPROPID_FirstChild)), out pVar); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); if (VSConstants.S_OK == hr) { uint childId = GetItemId(pVar); while (childId != VSConstants.VSITEMID_NIL) { yield return childId; hr = hierarchy.GetProperty(childId, visibleNodesOnly ? (int)__VSHPROPID.VSHPROPID_NextVisibleSibling : (int)__VSHPROPID.VSHPROPID_NextSibling, out pVar); if (VSConstants.S_OK == hr) { childId = GetItemId(pVar); } else { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); break; } } } } #endregion } enum SolutionHierarchyItemType { Solution, SolutionFolder, Project, UnloadedProject } interface ISolutionHierarchyItem { Guid Id { get; } string Name { get; } IVsHierarchy VsHierarchy { get; } uint HierarchyItemId { get; } SolutionHierarchyItemType ItemType { get; } IntPtr ImageHandle { get; } } interface ISolutionHierarchyContainerItem : ISolutionHierarchyItem { KeyedCollection<Guid, ISolutionHierarchyItem> Children { get; } } class SolutionHierarchyContainerItem : SolutionHierarchyItem, ISolutionHierarchyContainerItem { private ChildCollection m_children; public SolutionHierarchyContainerItem(IVsHierarchy hierarchy, uint itemId, SolutionHierarchyItemType itemType) : base(hierarchy, itemId, itemType) { } public KeyedCollection<Guid, ISolutionHierarchyItem> Children { get { if (m_children == null) { m_children = new ChildCollection(); } return m_children; } } private class ChildCollection : KeyedCollection<Guid, ISolutionHierarchyItem> { public ChildCollection() { } protected override Guid GetKeyForItem(ISolutionHierarchyItem item) { return item.Id; } } } class SolutionHierarchyItem : ISolutionHierarchyItem { #region Private Fields private readonly uint m_itemId; private Guid? m_id; private string m_name; private readonly IVsHierarchy m_hierarchy; private readonly SolutionHierarchyItemType m_itemType; #endregion public SolutionHierarchyItem(IVsHierarchy hierarchy, uint itemId, SolutionHierarchyItemType itemType) { m_itemId = itemId; m_hierarchy = hierarchy; m_itemType = itemType; } public IVsHierarchy VsHierarchy { get { return m_hierarchy; } } public uint HierarchyItemId { get { return m_itemId; } } public Guid Id { get { Dispatcher.CurrentDispatcher.VerifyAccess(); if (!m_id.HasValue) { Guid id; if (!ErrorHandler.Succeeded(m_hierarchy.GetGuidProperty(m_itemId, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out id))) m_id = Guid.Empty; else m_id = id; } return m_id.Value; } } public SolutionHierarchyItemType ItemType { get { return m_itemType; } } public string Name { get { Dispatcher.CurrentDispatcher.VerifyAccess(); if (m_name == null) { object pVar; ErrorHandler.ThrowOnFailure(m_hierarchy.GetProperty(m_itemId, (int)__VSHPROPID.VSHPROPID_Name, out pVar)); m_name = (string)pVar; } return m_name; } } public IntPtr ImageHandle { get { Dispatcher.CurrentDispatcher.VerifyAccess(); object pVar; int hr = VsHierarchy.GetProperty(HierarchyItemId, (int)__VSHPROPID.VSHPROPID_IconHandle, out pVar); if (pVar != null && hr == 0) { return new IntPtr((int)pVar); } else { hr = VsHierarchy.GetProperty(HierarchyItemId, (int)__VSHPROPID.VSHPROPID_IconImgList, out pVar); if (hr == 0 && pVar != null) { object index; hr = VsHierarchy.GetProperty(HierarchyItemId, (int)__VSHPROPID.VSHPROPID_IconIndex, out index); if (hr == 0 && index != null) return NativeMethods.ImageList_GetIcon(new IntPtr((int)pVar), (int)index, 0); } } return IntPtr.Zero; } } private static class NativeMethods { [DllImport("comctl32.dll", CharSet = CharSet.None, ExactSpelling = false)] public static extern IntPtr ImageList_GetIcon(IntPtr imageListHandle, int iconIndex, int flags); } } public interface IProgressInfo { int PercentComplete { get; } string CurrentOperation { get; } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.Project { /// <summary> /// This class handles opening, saving of file items in the hierarchy. /// </summary> public class FileDocumentManager : DocumentManager { #region ctors public FileDocumentManager(FileNode node) : base(node) { } #endregion #region overriden methods /// <summary> /// Open a file using the standard editor /// </summary> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public override int Open(ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { bool newFile = false; bool openWith = false; return this.Open(newFile, openWith, ref logicalView, docDataExisting, out windowFrame, windowFrameAction); } /// <summary> /// Open a file with a specific editor /// </summary> /// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param> /// <param name="editorType">Unique identifier of the editor type</param> /// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public override int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; bool newFile = false; bool openWith = false; return this.Open(newFile, openWith, editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out windowFrame, windowFrameAction); } #endregion #region public methods /// <summary> /// Open a file in a document window with a std editor /// </summary> /// <param name="newFile">Open the file as a new file</param> /// <param name="openWith">Use a dialog box to determine which editor to use</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public int Open(bool newFile, bool openWith, WindowFrameShowAction windowFrameAction) { Guid logicalView = Guid.Empty; IVsWindowFrame windowFrame = null; return this.Open(newFile, openWith, logicalView, out windowFrame, windowFrameAction); } /// <summary> /// Open a file in a document window with a std editor /// </summary> /// <param name="newFile">Open the file as a new file</param> /// <param name="openWith">Use a dialog box to determine which editor to use</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="frame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public int Open(bool newFile, bool openWith, Guid logicalView, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { frame = null; IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project"); if(rdt == null) { return VSConstants.E_FAIL; } // First we see if someone else has opened the requested view of the file. _VSRDTFLAGS flags = _VSRDTFLAGS.RDT_NoLock; uint itemid; IntPtr docData = IntPtr.Zero; IVsHierarchy ivsHierarchy; uint docCookie; string path = this.GetFullPathForDocument(); int returnValue = VSConstants.S_OK; try { ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)flags, path, out ivsHierarchy, out itemid, out docData, out docCookie)); ErrorHandler.ThrowOnFailure(this.Open(newFile, openWith, ref logicalView, docData, out frame, windowFrameAction)); } catch(COMException e) { Trace.WriteLine("Exception :" + e.Message); returnValue = e.ErrorCode; } finally { if(docData != IntPtr.Zero) { Marshal.Release(docData); } } return returnValue; } #endregion #region virtual methods /// <summary> /// Open a file in a document window /// </summary> /// <param name="newFile">Open the file as a new file</param> /// <param name="openWith">Use a dialog box to determine which editor to use</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the file</param> /// <param name="windowFrameAction">Determine the UI action on the document window</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int Open(bool newFile, bool openWith, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; Guid editorType = Guid.Empty; return this.Open(newFile, openWith, 0, ref editorType, null, ref logicalView, docDataExisting, out windowFrame, windowFrameAction); } #endregion #region helper methods private int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; if(this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } Debug.Assert(this.Node != null, "No node has been initialized for the document manager"); Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager"); Debug.Assert(this.Node is FileNode, "Node is not FileNode object"); int returnValue = VSConstants.S_OK; string caption = this.GetOwnerCaption(); string fullPath = this.GetFullPathForDocument(); // Make sure that the file is on disk before we open the editor and display message if not found if(!((FileNode)this.Node).IsFileOnDisk(true)) { // Inform clients that we have an invalid item (wrong icon) this.Node.OnInvalidateItems(this.Node.Parent); // Bail since we are not able to open the item // Do not return an error code otherwise an internal error message is shown. The scenario for this operation // normally is already a reaction to a dialog box telling that the item has been removed. return VSConstants.S_FALSE; } IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; try { this.Node.ProjectMgr.OnOpenItem(fullPath); int result = VSConstants.E_FAIL; if(openWith) { result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { __VSOSEFLAGS openFlags = 0; if(newFile) { openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile; } //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. if(editorType != Guid.Empty) { result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor; result = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, this.Node.ProjectMgr.InteropSafeIVsUIHierarchy, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } } if(result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } if(windowFrame != null) { object var; if(newFile) { ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var)); IVsPersistDocData persistDocData = (IVsPersistDocData)var; ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath)); } var = null; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); this.Node.DocCookie = (uint)(int)var; if(windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(windowFrame.Show()); } else if(windowFrameAction == WindowFrameShowAction.ShowNoActivate) { ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate()); } else if(windowFrameAction == WindowFrameShowAction.Hide) { ErrorHandler.ThrowOnFailure(windowFrame.Hide()); } } } catch(COMException e) { Trace.WriteLine("Exception e:" + e.Message); returnValue = e.ErrorCode; CloseWindowFrame(ref windowFrame); } return returnValue; } #endregion } }
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Buffers; using System.Buffers.Binary; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using Thrift.Protocol.Entities; using Thrift.Transport; namespace Thrift.Protocol { //TODO: implementation of TProtocol // ReSharper disable once InconsistentNaming public class TCompactProtocol : TProtocol { private const byte ProtocolId = 0x82; private const byte Version = 1; private const byte VersionMask = 0x1f; // 0001 1111 private const byte TypeMask = 0xE0; // 1110 0000 private const byte TypeBits = 0x07; // 0000 0111 private const int TypeShiftAmount = 5; private static readonly TStruct AnonymousStruct = new TStruct(string.Empty); private static readonly TField StopField = new TField(string.Empty, TType.Stop, 0); private const byte NoTypeOverride = 0xFF; // ReSharper disable once InconsistentNaming private static readonly byte[] TTypeToCompactType = new byte[16]; private static readonly TType[] CompactTypeToTType = new TType[13]; /// <summary> /// Used to keep track of the last field for the current and previous structs, so we can do the delta stuff. /// </summary> private readonly Stack<short> _lastField = new Stack<short>(15); /// <summary> /// If we encounter a boolean field begin, save the TField here so it can have the value incorporated. /// </summary> private TField? _booleanField; /// <summary> /// If we Read a field header, and it's a boolean field, save the boolean value here so that ReadBool can use it. /// </summary> private bool? _boolValue; private short _lastFieldId; // minimize memory allocations by means of an preallocated bytes buffer // The value of 128 is arbitrarily chosen, the required minimum size must be sizeof(long) private readonly byte[] PreAllocatedBuffer = new byte[128]; private struct VarInt { public byte[] bytes; public int count; } // minimize memory allocations by means of an preallocated VarInt buffer private VarInt PreAllocatedVarInt = new VarInt() { bytes = new byte[10], // see Int64ToVarInt() count = 0 }; public TCompactProtocol(TTransport trans) : base(trans) { TTypeToCompactType[(int) TType.Stop] = Types.Stop; TTypeToCompactType[(int) TType.Bool] = Types.BooleanTrue; TTypeToCompactType[(int) TType.Byte] = Types.Byte; TTypeToCompactType[(int) TType.I16] = Types.I16; TTypeToCompactType[(int) TType.I32] = Types.I32; TTypeToCompactType[(int) TType.I64] = Types.I64; TTypeToCompactType[(int) TType.Double] = Types.Double; TTypeToCompactType[(int) TType.String] = Types.Binary; TTypeToCompactType[(int) TType.List] = Types.List; TTypeToCompactType[(int) TType.Set] = Types.Set; TTypeToCompactType[(int) TType.Map] = Types.Map; TTypeToCompactType[(int) TType.Struct] = Types.Struct; CompactTypeToTType[Types.Stop] = TType.Stop; CompactTypeToTType[Types.BooleanTrue] = TType.Bool; CompactTypeToTType[Types.BooleanFalse] = TType.Bool; CompactTypeToTType[Types.Byte] = TType.Byte; CompactTypeToTType[Types.I16] = TType.I16; CompactTypeToTType[Types.I32] = TType.I32; CompactTypeToTType[Types.I64] = TType.I64; CompactTypeToTType[Types.Double] = TType.Double; CompactTypeToTType[Types.Binary] = TType.String; CompactTypeToTType[Types.List] = TType.List; CompactTypeToTType[Types.Set] = TType.Set; CompactTypeToTType[Types.Map] = TType.Map; CompactTypeToTType[Types.Struct] = TType.Struct; } public void Reset() { _lastField.Clear(); _lastFieldId = 0; } public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) { PreAllocatedBuffer[0] = ProtocolId; PreAllocatedBuffer[1] = (byte)((Version & VersionMask) | (((uint)message.Type << TypeShiftAmount) & TypeMask)); await Trans.WriteAsync(PreAllocatedBuffer, 0, 2, cancellationToken); Int32ToVarInt((uint) message.SeqID, ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); await WriteStringAsync(message.Name, cancellationToken); } public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } /// <summary> /// Write a struct begin. This doesn't actually put anything on the wire. We /// use it as an opportunity to put special placeholder markers on the field /// stack so we can get the field id deltas correct. /// </summary> public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } _lastField.Push(_lastFieldId); _lastFieldId = 0; } public override async Task WriteStructEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } _lastFieldId = _lastField.Pop(); } private async Task WriteFieldBeginInternalAsync(TField field, byte fieldType, CancellationToken cancellationToken) { // if there's a exType override passed in, use that. Otherwise ask GetCompactType(). if (fieldType == NoTypeOverride) fieldType = GetCompactType(field.Type); // check if we can use delta encoding for the field id if (field.ID > _lastFieldId) { var delta = field.ID - _lastFieldId; if (delta <= 15) { // Write them together PreAllocatedBuffer[0] = (byte)((delta << 4) | fieldType); await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); _lastFieldId = field.ID; return; } } // Write them separate PreAllocatedBuffer[0] = fieldType; await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); await WriteI16Async(field.ID, cancellationToken); _lastFieldId = field.ID; } public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) { if (field.Type == TType.Bool) { _booleanField = field; } else { await WriteFieldBeginInternalAsync(field, NoTypeOverride, cancellationToken); } } public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteFieldStopAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = Types.Stop; await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } protected async Task WriteCollectionBeginAsync(TType elemType, int size, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } /* Abstract method for writing the start of lists and sets. List and sets on the wire differ only by the exType indicator. */ if (size <= 14) { PreAllocatedBuffer[0] = (byte)((size << 4) | GetCompactType(elemType)); await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } else { PreAllocatedBuffer[0] = (byte)(0xf0 | GetCompactType(elemType)); await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); Int32ToVarInt((uint) size, ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); } } public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) { await WriteCollectionBeginAsync(list.ElementType, list.Count, cancellationToken); } public override async Task WriteListEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } await WriteCollectionBeginAsync(set.ElementType, set.Count, cancellationToken); } public override async Task WriteSetEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } /* Write a boolean value. Potentially, this could be a boolean field, in which case the field header info isn't written yet. If so, decide what the right exType header is for the value and then Write the field header. Otherwise, Write a single byte. */ if (_booleanField != null) { // we haven't written the field header yet var type = b ? Types.BooleanTrue : Types.BooleanFalse; await WriteFieldBeginInternalAsync(_booleanField.Value, type, cancellationToken); _booleanField = null; } else { // we're not part of a field, so just write the value. PreAllocatedBuffer[0] = b ? Types.BooleanTrue : Types.BooleanFalse; await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } } public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } PreAllocatedBuffer[0] = (byte)b; await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } Int32ToVarInt(IntToZigzag(i16), ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); } private static void Int32ToVarInt(uint n, ref VarInt varint) { // Write an i32 as a varint. Results in 1 - 5 bytes on the wire. varint.count = 0; Debug.Assert(varint.bytes.Length >= 5); while (true) { if ((n & ~0x7F) == 0) { varint.bytes[varint.count++] = (byte)n; break; } varint.bytes[varint.count++] = (byte)((n & 0x7F) | 0x80); n >>= 7; } } public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } Int32ToVarInt(IntToZigzag(i32), ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); } static private void Int64ToVarInt(ulong n, ref VarInt varint) { // Write an i64 as a varint. Results in 1-10 bytes on the wire. varint.count = 0; Debug.Assert(varint.bytes.Length >= 10); while (true) { if ((n & ~(ulong)0x7FL) == 0) { varint.bytes[varint.count++] = (byte)n; break; } varint.bytes[varint.count++] = (byte)((n & 0x7F) | 0x80); n >>= 7; } } public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } Int64ToVarInt(LongToZigzag(i64), ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); } public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } BinaryPrimitives.WriteInt64LittleEndian(PreAllocatedBuffer, BitConverter.DoubleToInt64Bits(d)); await Trans.WriteAsync(PreAllocatedBuffer, 0, 8, cancellationToken); } public override async Task WriteStringAsync(string str, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } var buf = ArrayPool<byte>.Shared.Rent(Encoding.UTF8.GetByteCount(str)); try { var numberOfBytes = Encoding.UTF8.GetBytes(str, 0, str.Length, buf, 0); Int32ToVarInt((uint)numberOfBytes, ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); await Trans.WriteAsync(buf, 0, numberOfBytes, cancellationToken); } finally { ArrayPool<byte>.Shared.Return(buf); } } public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } Int32ToVarInt((uint) bytes.Length, ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); await Trans.WriteAsync(bytes, 0, bytes.Length, cancellationToken); } public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return; } if (map.Count == 0) { PreAllocatedBuffer[0] = 0; await Trans.WriteAsync( PreAllocatedBuffer, 0, 1, cancellationToken); } else { Int32ToVarInt((uint) map.Count, ref PreAllocatedVarInt); await Trans.WriteAsync(PreAllocatedVarInt.bytes, 0, PreAllocatedVarInt.count, cancellationToken); PreAllocatedBuffer[0] = (byte)((GetCompactType(map.KeyType) << 4) | GetCompactType(map.ValueType)); await Trans.WriteAsync(PreAllocatedBuffer, 0, 1, cancellationToken); } } public override async Task WriteMapEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TMessage>(cancellationToken); } var protocolId = (byte) await ReadByteAsync(cancellationToken); if (protocolId != ProtocolId) { throw new TProtocolException($"Expected protocol id {ProtocolId:X} but got {protocolId:X}"); } var versionAndType = (byte) await ReadByteAsync(cancellationToken); var version = (byte) (versionAndType & VersionMask); if (version != Version) { throw new TProtocolException($"Expected version {Version} but got {version}"); } var type = (byte) ((versionAndType >> TypeShiftAmount) & TypeBits); var seqid = (int) await ReadVarInt32Async(cancellationToken); var messageName = await ReadStringAsync(cancellationToken); return new TMessage(messageName, (TMessageType) type, seqid); } public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<TStruct>(cancellationToken); } // some magic is here ) _lastField.Push(_lastFieldId); _lastFieldId = 0; return AnonymousStruct; } public override async Task ReadStructEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } /* Doesn't actually consume any wire data, just removes the last field for this struct from the field stack. */ // consume the last field we Read off the wire. _lastFieldId = _lastField.Pop(); } public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken) { // Read a field header off the wire. var type = (byte) await ReadByteAsync(cancellationToken); // if it's a stop, then we can return immediately, as the struct is over. if (type == Types.Stop) { return StopField; } // mask off the 4 MSB of the exType header. it could contain a field id delta. var modifier = (short) ((type & 0xf0) >> 4); var compactType = (byte)(type & 0x0f); short fieldId; if (modifier == 0) { fieldId = await ReadI16Async(cancellationToken); } else { fieldId = (short) (_lastFieldId + modifier); } var ttype = GetTType(compactType); var field = new TField(string.Empty, ttype, fieldId); // if this happens to be a boolean field, the value is encoded in the exType if( ttype == TType.Bool) { _boolValue = (compactType == Types.BooleanTrue); } // push the new field onto the field stack so we can keep the deltas going. _lastFieldId = field.ID; return field; } public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled<TMap>(cancellationToken); } /* Read a map header off the wire. If the size is zero, skip Reading the key and value exType. This means that 0-length maps will yield TMaps without the "correct" types. */ var size = (int) await ReadVarInt32Async(cancellationToken); var keyAndValueType = size == 0 ? (byte) 0 : (byte) await ReadByteAsync(cancellationToken); var map = new TMap(GetTType((byte) (keyAndValueType >> 4)), GetTType((byte) (keyAndValueType & 0xf)), size); CheckReadBytesAvailable(map); return map; } public override async Task ReadMapEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken) { /* Read a set header off the wire. If the set size is 0-14, the size will be packed into the element exType header. If it's a longer set, the 4 MSB of the element exType header will be 0xF, and a varint will follow with the true size. */ return new TSet(await ReadListBeginAsync(cancellationToken)); } public override ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken) { /* Read a boolean off the wire. If this is a boolean field, the value should already have been Read during ReadFieldBegin, so we'll just consume the pre-stored value. Otherwise, Read a byte. */ if (_boolValue != null) { var result = _boolValue.Value; _boolValue = null; return new ValueTask<bool>(result); } return InternalCall(); async ValueTask<bool> InternalCall() { var data = await ReadByteAsync(cancellationToken); return (data == Types.BooleanTrue); } } public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken) { // Read a single byte off the wire. Nothing interesting here. await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 1, cancellationToken); return (sbyte)PreAllocatedBuffer[0]; } public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<short>(cancellationToken); } return (short) ZigzagToInt(await ReadVarInt32Async(cancellationToken)); } public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<int>(cancellationToken); } return ZigzagToInt(await ReadVarInt32Async(cancellationToken)); } public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<long>(cancellationToken); } return ZigzagToLong(await ReadVarInt64Async(cancellationToken)); } public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<double>(cancellationToken); } await Trans.ReadAllAsync(PreAllocatedBuffer, 0, 8, cancellationToken); return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(PreAllocatedBuffer)); } public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken) { // read length var length = (int) await ReadVarInt32Async(cancellationToken); if (length == 0) { return string.Empty; } // read and decode data if (length < PreAllocatedBuffer.Length) { await Trans.ReadAllAsync(PreAllocatedBuffer, 0, length, cancellationToken); return Encoding.UTF8.GetString(PreAllocatedBuffer, 0, length); } Transport.CheckReadBytesAvailable(length); var buf = ArrayPool<byte>.Shared.Rent(length); try { await Trans.ReadAllAsync(buf, 0, length, cancellationToken); return Encoding.UTF8.GetString(buf, 0, length); } finally { ArrayPool<byte>.Shared.Return(buf); } } public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken) { // read length var length = (int) await ReadVarInt32Async(cancellationToken); if (length == 0) { return Array.Empty<byte>(); } // read data Transport.CheckReadBytesAvailable(length); var buf = new byte[length]; await Trans.ReadAllAsync(buf, 0, length, cancellationToken); return buf; } public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled<TList>(cancellationToken); } /* Read a list header off the wire. If the list size is 0-14, the size will be packed into the element exType header. If it's a longer list, the 4 MSB of the element exType header will be 0xF, and a varint will follow with the true size. */ var sizeAndType = (byte) await ReadByteAsync(cancellationToken); var size = (sizeAndType >> 4) & 0x0f; if (size == 15) { size = (int) await ReadVarInt32Async(cancellationToken); } var type = GetTType(sizeAndType); var list = new TList(type, size); CheckReadBytesAvailable(list); return list; } public override async Task ReadListEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } public override async Task ReadSetEndAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { await Task.FromCanceled(cancellationToken); } } private static byte GetCompactType(TType ttype) { // Given a TType value, find the appropriate TCompactProtocol.Types constant. return TTypeToCompactType[(int) ttype]; } private async ValueTask<uint> ReadVarInt32Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<uint>(cancellationToken); } /* Read an i32 from the wire as a varint. The MSB of each byte is set if there is another byte to follow. This can Read up to 5 bytes. */ uint result = 0; var shift = 0; while (true) { var b = (byte) await ReadByteAsync(cancellationToken); result |= (uint) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } return result; } private async ValueTask<ulong> ReadVarInt64Async(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return await Task.FromCanceled<uint>(cancellationToken); } /* Read an i64 from the wire as a proper varint. The MSB of each byte is set if there is another byte to follow. This can Read up to 10 bytes. */ var shift = 0; ulong result = 0; while (true) { var b = (byte) await ReadByteAsync(cancellationToken); result |= (ulong) (b & 0x7f) << shift; if ((b & 0x80) != 0x80) { break; } shift += 7; } return result; } private static int ZigzagToInt(uint n) { return (int) (n >> 1) ^ -(int) (n & 1); } private static long ZigzagToLong(ulong n) { return (long) (n >> 1) ^ -(long) (n & 1); } private static TType GetTType(byte type) { // Given a TCompactProtocol.Types constant, convert it to its corresponding TType value. return CompactTypeToTType[type & 0x0f]; } private static ulong LongToZigzag(long n) { // Convert l into a zigzag long. This allows negative numbers to be represented compactly as a varint return (ulong) (n << 1) ^ (ulong) (n >> 63); } private static uint IntToZigzag(int n) { // Convert n into a zigzag int. This allows negative numbers to be represented compactly as a varint return (uint) (n << 1) ^ (uint) (n >> 31); } // Return the minimum number of bytes a type will consume on the wire public override int GetMinSerializedSize(TType type) { switch (type) { case TType.Stop: return 0; case TType.Void: return 0; case TType.Bool: return sizeof(byte); case TType.Double: return 8; // uses fixedLongToBytes() which always writes 8 bytes case TType.Byte: return sizeof(byte); case TType.I16: return sizeof(byte); // zigzag case TType.I32: return sizeof(byte); // zigzag case TType.I64: return sizeof(byte); // zigzag case TType.String: return sizeof(byte); // string length case TType.Struct: return 0; // empty struct case TType.Map: return sizeof(byte); // element count case TType.Set: return sizeof(byte); // element count case TType.List: return sizeof(byte); // element count default: throw new TTransportException(TTransportException.ExceptionType.Unknown, "unrecognized type code"); } } public class Factory : TProtocolFactory { public override TProtocol GetProtocol(TTransport trans) { return new TCompactProtocol(trans); } } /// <summary> /// All of the on-wire exType codes. /// </summary> private static class Types { public const byte Stop = 0x00; public const byte BooleanTrue = 0x01; public const byte BooleanFalse = 0x02; public const byte Byte = 0x03; public const byte I16 = 0x04; public const byte I32 = 0x05; public const byte I64 = 0x06; public const byte Double = 0x07; public const byte Binary = 0x08; public const byte List = 0x09; public const byte Set = 0x0A; public const byte Map = 0x0B; public const byte Struct = 0x0C; } } }
#pragma warning disable 169 // ReSharper disable InconsistentNaming namespace NEventStore.DispatcherTests { using System.Threading; using FakeItEasy; using NEventStore.Dispatcher; using NEventStore.Persistence; using NEventStore.Persistence.AcceptanceTests.BDD; using Xunit; public class when_instantiating_the_asynchronous_dispatch_scheduler : SpecificationBase<TestFixture> { public IDispatchCommits Dispatcher { get { return Fixture.Variables["dispatcher"] as IDispatchCommits; } set { Fixture.Variables["dispatcher"] = value; } } public IPersistStreams Persistence { get { return Fixture.Variables["persistence"] as IPersistStreams; } set { Fixture.Variables["persistence"] = value; } } private AsynchronousDispatchScheduler DispatchScheduler { get { return Fixture.Variables["dispatchScheduler"] as AsynchronousDispatchScheduler; } set { Fixture.Variables["dispatchScheduler"] = value; } } public ICommit[] Commits { get { return Fixture.Variables["commits"] as ICommit[]; } set { Fixture.Variables["commits"] = value; } } public ICommit FirstCommit { get { return Fixture.Variables["firstCommit"] as ICommit; } set { Fixture.Variables["firstCommit"] = value; } } public ICommit LastCommit { get { return Fixture.Variables["lastCommit"] as ICommit; } set { Fixture.Variables["lastCommit"] = value; } } public when_instantiating_the_asynchronous_dispatch_scheduler(TestFixture fixture) : base(fixture) { } protected override void Context() { Commits = new[] { FirstCommit = CommitHelper.Create(), LastCommit = CommitHelper.Create() }; Dispatcher = A.Fake<IDispatchCommits>(); Persistence = A.Fake<IPersistStreams>(); A.CallTo(() => Persistence.GetUndispatchedCommits()).Returns(Commits); } protected override void Because() { DispatchScheduler = new AsynchronousDispatchScheduler(Dispatcher, Persistence); DispatchScheduler.Start(); } protected override void Cleanup() { DispatchScheduler.Dispose(); } [Fact] public void should_take_a_few_milliseconds_for_the_other_thread_to_execute() { Thread.Sleep(25); // just a precaution because we're doing async tests } [Fact] public void should_initialize_the_persistence_engine() { A.CallTo(() => Persistence.Initialize()).MustHaveHappenedOnceExactly(); } [Fact] public void should_get_the_set_of_undispatched_commits() { A.CallTo(() => Persistence.GetUndispatchedCommits()).MustHaveHappenedOnceExactly(); } [Fact] public void should_provide_the_commits_to_the_dispatcher() { A.CallTo(() => Dispatcher.Dispatch(FirstCommit)).MustHaveHappened(); A.CallTo(() => Dispatcher.Dispatch(LastCommit)).MustHaveHappened(); } } public class when_asynchronously_scheduling_a_commit_for_dispatch : SpecificationBase<TestFixture> { public IDispatchCommits Dispatcher { get { return Fixture.Variables["dispatcher"] as IDispatchCommits; } set { Fixture.Variables["dispatcher"] = value; } } public IPersistStreams Persistence { get { return Fixture.Variables["persistence"] as IPersistStreams; } set { Fixture.Variables["persistence"] = value; } } private AsynchronousDispatchScheduler DispatchScheduler { get { return Fixture.Variables["dispatchScheduler"] as AsynchronousDispatchScheduler; } set { Fixture.Variables["dispatchScheduler"] = value; } } public ICommit Commit { get { return Fixture.Variables["commit"] as ICommit; } set { Fixture.Variables["commit"] = value; } } //private readonly ICommit _commit = CommitHelper.Create(); //private readonly IDispatchCommits dispatcher = A.Fake<IDispatchCommits>(); //private readonly IPersistStreams persistence = A.Fake<IPersistStreams>(); //private AsynchronousDispatchScheduler _dispatchScheduler; public when_asynchronously_scheduling_a_commit_for_dispatch(TestFixture fixture) : base(fixture) { } protected override void Context() { Dispatcher = A.Fake<IDispatchCommits>(); Persistence = A.Fake<IPersistStreams>(); Commit = CommitHelper.Create(); DispatchScheduler = new AsynchronousDispatchScheduler(Dispatcher, Persistence); DispatchScheduler.Start(); } protected override void Because() { DispatchScheduler.ScheduleDispatch(Commit); Thread.Sleep(250); } protected override void Cleanup() { DispatchScheduler.Dispose(); } [Fact] public void should_provide_the_commit_to_the_dispatcher() { A.CallTo(() => Dispatcher.Dispatch(Commit)).MustHaveHappenedOnceExactly(); } [Fact] public void should_mark_the_commit_as_dispatched() { A.CallTo(() => Persistence.MarkCommitAsDispatched(Commit)).MustHaveHappenedOnceExactly(); } } public class when_disposing_the_async_dispatch_scheduler : SpecificationBase<TestFixture> { public IDispatchCommits Dispatcher { get { return Fixture.Variables["dispatcher"] as IDispatchCommits; } set { Fixture.Variables["dispatcher"] = value; } } public IPersistStreams Persistence { get { return Fixture.Variables["persistence"] as IPersistStreams; } set { Fixture.Variables["persistence"] = value; } } private AsynchronousDispatchScheduler DispatchScheduler { get { return Fixture.Variables["dispatchScheduler"] as AsynchronousDispatchScheduler; } set { Fixture.Variables["dispatchScheduler"] = value; } } public when_disposing_the_async_dispatch_scheduler(TestFixture fixture) : base(fixture) { } protected override void Context() { Dispatcher = A.Fake<IDispatchCommits>(); Persistence = A.Fake<IPersistStreams>(); DispatchScheduler = new AsynchronousDispatchScheduler(Dispatcher, Persistence); } protected override void Because() { DispatchScheduler.Dispose(); DispatchScheduler.Dispose(); } [Fact] public void should_dispose_the_underlying_dispatcher_exactly_once() { A.CallTo(() => Dispatcher.Dispose()).MustHaveHappenedOnceExactly(); } [Fact] public void should_dispose_the_underlying_persistence_infrastructure_exactly_once() { A.CallTo(() => Persistence.Dispose()).MustHaveHappenedOnceExactly(); } } } // ReSharper enable InconsistentNaming #pragma warning restore 169
// 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. //============================================================================= // // // Purpose: Define HResult constants. Every exception has one of these. // // //===========================================================================*/ using System; namespace System { // Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that // range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc). // In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type // HResults. Also note that some of our HResults have to map to certain // COM HR's, etc. // Another arbitrary decision... Feel free to change this, as long as you // renumber the HResults yourself (and update rexcep.h). // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f. // Security will use 0x1640 -> 0x165f // There are __HResults files in the IO, Remoting, Reflection & // Security/Util directories as well, so choose your HResults carefully. internal static class __HResults { internal const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54); internal const int CLDB_E_FILE_CORRUPT = unchecked((int)0x8013110e); internal const int CLDB_E_FILE_OLDVER = unchecked((int)0x80131107); internal const int CLDB_E_INDEX_NOTFOUND = unchecked((int)0x80131124); internal const int CLR_E_BIND_ASSEMBLY_NOT_FOUND = unchecked((int)0x80132004); internal const int CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH = unchecked((int)0x80132001); internal const int CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW = unchecked((int)0x80132000); internal const int CLR_E_BIND_TYPE_NOT_FOUND = unchecked((int)0x80132005); internal const int CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT = unchecked((int)0x80132003); internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D); internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D); internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014); internal const int COR_E_APPLICATION = unchecked((int)0x80131600); internal const int COR_E_ARGUMENT = unchecked((int)0x80070057); internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502); internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216); internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503); internal const int COR_E_ASSEMBLYEXPECTED = unchecked((int)0x80131018); internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B); internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015); internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504); internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605); internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541); internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524); internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529); internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523); internal const int COR_E_EXCEPTION = unchecked((int)0x80131500); internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506); internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507); internal const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019); internal const int COR_E_FORMAT = unchecked((int)0x80131537); internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508); internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578); internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002); internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527); internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601); internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531); internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509); internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153a); internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577); internal const int COR_E_LOADING_REFERENCE_ASSEMBLY = unchecked((int)0x80131058); internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535); internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A); internal const int COR_E_METHODACCESS = unchecked((int)0x80131510); internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511); internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532); internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512); internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513); internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536); internal const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039); internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514); internal const int COR_E_NEWER_RUNTIME = unchecked((int)0x8013101b); internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528); internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515); internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003); internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622); internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B); internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int COR_E_OVERFLOW = unchecked((int)0x80131516); internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539); internal const int COR_E_RANK = unchecked((int)0x80131517); internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602); internal const int COR_E_REMOTING = unchecked((int)0x8013150b); internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153e); internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538); internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533); internal const int COR_E_SECURITY = unchecked((int)0x8013150A); internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C); internal const int COR_E_SERVER = unchecked((int)0x8013150e); internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9); internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518); internal const int COR_E_SYSTEM = unchecked((int)0x80131501); internal const int COR_E_TARGET = unchecked((int)0x80131603); internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604); internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e); internal const int COR_E_THREADABORTED = unchecked((int)0x80131530); internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519); internal const int COR_E_THREADSTART = unchecked((int)0x80131525); internal const int COR_E_THREADSTATE = unchecked((int)0x80131520); internal const int COR_E_TIMEOUT = unchecked((int)0x80131505); internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543); internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534); internal const int COR_E_TYPELOAD = unchecked((int)0x80131522); internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013); internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005); internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D); internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C); internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430); internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431); internal const int CORSEC_E_INVALID_IMAGE_FORMAT = unchecked((int)0x8013141d); internal const int CORSEC_E_INVALID_PUBLICKEY = unchecked((int)0x8013141e); internal const int CORSEC_E_INVALID_STRONGNAME = unchecked((int)0x8013141a); internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417); internal const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b); internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418); internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416); internal const int CORSEC_E_SIGNATURE_MISMATCH = unchecked((int)0x80131420); internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131419); internal const int CTL_E_DEVICEIOERROR = unchecked((int)0x800A0039); internal const int CTL_E_DIVISIONBYZERO = unchecked((int)0x800A000B); internal const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035); internal const int CTL_E_OUTOFMEMORY = unchecked((int)0x800A0007); internal const int CTL_E_OUTOFSTACKSPACE = unchecked((int)0x800A001C); internal const int CTL_E_OVERFLOW = unchecked((int)0x800A0006); internal const int CTL_E_PATHFILEACCESSERROR = unchecked((int)0x800A004B); internal const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C); internal const int CTL_E_PERMISSIONDENIED = unchecked((int)0x800A0046); internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F); internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E); internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018); internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E); internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D); internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014); internal const int E_NOTIMPL = unchecked((int)0x80004001); internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E); internal const int E_POINTER = unchecked((int)0x80004003L); internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A); internal const int ERROR_BAD_EXE_FORMAT = unchecked((int)0x800700C1); internal const int ERROR_BAD_NET_NAME = unchecked((int)0x80070043); internal const int ERROR_BAD_NETPATH = unchecked((int)0x80070035); internal const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571); internal const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A); internal const int ERROR_DLL_NOT_FOUND = unchecked((int)0x80070485); internal const int ERROR_EXE_MARKED_INVALID = unchecked((int)0x800700C0); internal const int ERROR_FILE_CORRUPT = unchecked((int)0x80070570); internal const int ERROR_FILE_INVALID = unchecked((int)0x800703EE); internal const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002); internal const int ERROR_INVALID_DLL = unchecked((int)0x80070482); internal const int ERROR_INVALID_NAME = unchecked((int)0x8007007B); internal const int ERROR_INVALID_ORDINAL = unchecked((int)0x800700B6); internal const int ERROR_INVALID_PARAMETER = unchecked((int)0x80070057); internal const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021); internal const int ERROR_MOD_NOT_FOUND = unchecked((int)0x8007007E); internal const int ERROR_NO_UNICODE_TRANSLATION = unchecked((int)0x80070459); internal const int ERROR_NOACCESS = unchecked((int)0x800703E6); internal const int ERROR_NOT_READY = unchecked((int)0x80070015); internal const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E); internal const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003); internal const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020); internal const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004); internal const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED); internal const int ERROR_WRONG_TARGET_NAME = unchecked((int)0x80070574); internal const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042); internal const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052); internal const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048); internal const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050); internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041); internal const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051); internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044); internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040); internal const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045); internal const int INET_E_CANNOT_CONNECT = unchecked((int)0x800C0004); internal const int INET_E_CONNECTION_TIMEOUT = unchecked((int)0x800C000B); internal const int INET_E_DATA_NOT_AVAILABLE = unchecked((int)0x800C0007); internal const int INET_E_DOWNLOAD_FAILURE = unchecked((int)0x800C0008); internal const int INET_E_OBJECT_NOT_FOUND = unchecked((int)0x800C0006); internal const int INET_E_RESOURCE_NOT_FOUND = unchecked((int)0x800C0005); internal const int INET_E_UNKNOWN_PROTOCOL = unchecked((int)0x800C000D); internal const int ISS_E_ALLOC_TOO_LARGE = unchecked((int)0x80131484); internal const int ISS_E_BLOCK_SIZE_TOO_SMALL = unchecked((int)0x80131483); internal const int ISS_E_CALLER = unchecked((int)0x801314A1); internal const int ISS_E_CORRUPTED_STORE_FILE = unchecked((int)0x80131480); internal const int ISS_E_CREATE_DIR = unchecked((int)0x80131468); internal const int ISS_E_CREATE_MUTEX = unchecked((int)0x80131464); internal const int ISS_E_DEPRECATE = unchecked((int)0x801314A0); internal const int ISS_E_FILE_NOT_MAPPED = unchecked((int)0x80131482); internal const int ISS_E_FILE_WRITE = unchecked((int)0x80131466); internal const int ISS_E_GET_FILE_SIZE = unchecked((int)0x80131463); internal const int ISS_E_ISOSTORE = unchecked((int)0x80131450); internal const int ISS_E_LOCK_FAILED = unchecked((int)0x80131465); internal const int ISS_E_MACHINE = unchecked((int)0x801314A3); internal const int ISS_E_MACHINE_DACL = unchecked((int)0x801314A4); internal const int ISS_E_MAP_VIEW_OF_FILE = unchecked((int)0x80131462); internal const int ISS_E_OPEN_FILE_MAPPING = unchecked((int)0x80131461); internal const int ISS_E_OPEN_STORE_FILE = unchecked((int)0x80131460); internal const int ISS_E_PATH_LENGTH = unchecked((int)0x801314A2); internal const int ISS_E_SET_FILE_POINTER = unchecked((int)0x80131467); internal const int ISS_E_STORE_NOT_OPEN = unchecked((int)0x80131469); internal const int ISS_E_STORE_VERSION = unchecked((int)0x80131481); internal const int ISS_E_TABLE_ROW_NOT_FOUND = unchecked((int)0x80131486); internal const int ISS_E_USAGE_WILL_EXCEED_QUOTA = unchecked((int)0x80131485); internal const int META_E_BAD_SIGNATURE = unchecked((int)0x80131192); internal const int META_E_CA_FRIENDS_SN_REQUIRED = unchecked((int)0x801311e6); internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016); internal const int RO_E_CLOSED = unchecked((int)0x80000013); internal const int E_BOUNDS = unchecked((int)0x8000000B); internal const int RO_E_METADATA_NAME_NOT_FOUND = unchecked((int)0x8000000F); internal const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403); internal const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401); internal const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402); internal const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003); public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003); public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined public const int COR_E_FILELOAD = unchecked((int)0x80131621); public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002); public const int COR_E_IO = unchecked((int)0x80131620); public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE); } }
using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Libraries.Collections { public interface ICell<T> : IEnumerable<T>, ICloneable { T this[int index] { get; } int Length { get; } int Count { get; } bool IsFull { get; } void Expand(int newSize); bool Exists(Predicate<T> predicate); int IndexOf(T value); bool Add(T value); bool Remove(T value); bool Contains(T value); T[] ToArray(); void Clear(); } public class Cell<T> : ICell<T> { public const int DEFAULT_CAPACITY = 7; protected T[] backingStore; private int count; public T this[int index] { get { return backingStore[index]; } set { backingStore[index] = value; } } public int Count { get { return count; } protected set { count = value; } } public int Length { get { return backingStore.Length; } } public bool IsFull { get { return backingStore.Length == Count; } } public Cell(IEnumerable<T> elements) : this(elements.Count()) { foreach(T e in elements) Add(e); } public Cell(int capacity) { backingStore = new T[capacity]; count = 0; } public Cell() : this(DEFAULT_CAPACITY) { } public void Expand(int newSize) { if(newSize == Length) return; else if(newSize < Length) throw new ArgumentException("Given expansion size is less than the current size"); else { T[] newBackingStore = new T[newSize]; for(int i = 0; i < Count; i++) { newBackingStore[i] = backingStore[i]; backingStore[i] = default(T); } backingStore = newBackingStore; } } public bool Exists(Predicate<T> predicate) { for(int i = 0; i < Count; i++) if(predicate(backingStore[i])) return true; return false; } public int IndexOf(T value) { int index = 0; Predicate<T> pred = (x) => { bool result = x.Equals(value); if(!result) index++; return result; }; if(Exists(pred)) return index; else return -1; } public bool Contains(T value) { return IndexOf(value) != -1; } public bool Add(T value) { bool result = !IsFull; if(result) { backingStore[count] = value; count++; } return result; } ///<summary> ///Used to remove all intermediate empty cells and put them at the back ///This code assumes that there is at least one free cell, otherwise it will ///do nothing. It also assumes that the starting position is empty and that we are removing ///</summary> protected void CompressCell(int startingAt) { if((startingAt < (Length - 1))) { for(int i = startingAt; (i + 1) < Length; i++) backingStore[i] = backingStore[i + 1]; } } public bool Remove(T value) { int index = IndexOf(value); bool result = (index != -1); if(result) { backingStore[index] = default(T); if(index != (Count - 1)) CompressCell(index); count--; } return result; } public bool RemoveFirst() { bool result = Count == 0; if(!result) { backingStore[0] = default(T); if(Count > 1) CompressCell(0); count--; } return result; } public bool RemoveLast() { bool result = Count == 0; if(!result) { backingStore[Count - 1] = default(T); count--; } return result; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<T> GetEnumerator() { return new CellEnumerator(this); } public void SecureClear() { //linear operation to clear it for(int i = 0; i < Count; i++) this[i] = default(T); count = 0; } public void Clear() { count = 0; //we already have the block, lets not //waste it } public T[] ToArray() { T[] newElements = new T[backingStore.Length]; for(int i = 0; i < Count; i++) newElements[i] = backingStore[i]; return newElements; } public class CellEnumerator : IEnumerator<T> { private T[] backingStore; private int index, count; public T Current { get { return backingStore[index]; } } object IEnumerator.Current { get { return backingStore[index]; } } public CellEnumerator(Cell<T> cell) { this.backingStore = cell.backingStore; this.count = cell.count; this.index = -1; } public bool MoveNext() { index++; return index < count; } public void Reset() { index = -1; } public void Dispose() { backingStore = null; } } public virtual object Clone() { return new Cell<T>(this); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Water //----------------------------------------------------------------------------- singleton ShaderData( WaterShader ) { DXVertexShaderFile = $Core::CommonShaderPath @ "/water/waterV.hlsl"; DXPixelShaderFile = $Core::CommonShaderPath @ "/water/waterP.hlsl"; OGLVertexShaderFile = $Core::CommonShaderPath @ "/water/gl/waterV.glsl"; OGLPixelShaderFile = $Core::CommonShaderPath @ "/water/gl/waterP.glsl"; samplerNames[0] = "$bumpMap"; // noise samplerNames[1] = "$prepassTex"; // #prepass samplerNames[2] = "$reflectMap"; // $reflectbuff samplerNames[3] = "$refractBuff"; // $backbuff samplerNames[4] = "$skyMap"; // $cubemap samplerNames[5] = "$foamMap"; // foam samplerNames[6] = "$depthGradMap"; // depthMap ( color gradient ) pixVersion = 3.0; }; new GFXSamplerStateData(WaterSampler) { textureColorOp = GFXTOPModulate; addressModeU = GFXAddressWrap; addressModeV = GFXAddressWrap; addressModeW = GFXAddressWrap; magFilter = GFXTextureFilterLinear; minFilter = GFXTextureFilterAnisotropic; mipFilter = GFXTextureFilterLinear; maxAnisotropy = 4; }; singleton GFXStateBlockData( WaterStateBlock ) { samplersDefined = true; samplerStates[0] = WaterSampler; // noise samplerStates[1] = SamplerClampPoint; // #prepass samplerStates[2] = SamplerClampLinear; // $reflectbuff samplerStates[3] = SamplerClampPoint; // $backbuff samplerStates[4] = SamplerWrapLinear; // $cubemap samplerStates[5] = SamplerWrapLinear; // foam samplerStates[6] = SamplerClampLinear; // depthMap ( color gradient ) cullDefined = true; cullMode = "GFXCullCCW"; }; singleton GFXStateBlockData( UnderWaterStateBlock : WaterStateBlock ) { cullMode = "GFXCullCW"; }; singleton CustomMaterial( WaterMat ) { sampler["prepassTex"] = "#prepass"; sampler["reflectMap"] = "$reflectbuff"; sampler["refractBuff"] = "$backbuff"; // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = ""; //sampler["skyMap"] = ""; //sampler["foamMap"] = ""; //sampler["depthGradMap"] = ""; shader = WaterShader; stateBlock = WaterStateBlock; version = 3.0; useAnisotropic[0] = true; }; //----------------------------------------------------------------------------- // Underwater //----------------------------------------------------------------------------- singleton ShaderData( UnderWaterShader : WaterShader ) { defines = "UNDERWATER"; }; singleton CustomMaterial( UnderwaterMat ) { // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = "core/art/water/noise02"; //sampler["foamMap"] = "core/art/water/foam"; sampler["prepassTex"] = "#prepass"; sampler["refractBuff"] = "$backbuff"; shader = UnderWaterShader; stateBlock = UnderWaterStateBlock; specular = "0.75 0.75 0.75 1.0"; specularPower = 48.0; version = 3.0; }; //----------------------------------------------------------------------------- // Basic Water //----------------------------------------------------------------------------- singleton ShaderData( WaterBasicShader ) { DXVertexShaderFile = $Core::CommonShaderPath @ "/water/waterBasicV.hlsl"; DXPixelShaderFile = $Core::CommonShaderPath @ "/water/waterBasicP.hlsl"; OGLVertexShaderFile = $Core::CommonShaderPath @ "/water/gl/waterBasicV.glsl"; OGLPixelShaderFile = $Core::CommonShaderPath @ "/water/gl/waterBasicP.glsl"; samplerNames[0] = "$bumpMap"; samplerNames[2] = "$reflectMap"; samplerNames[3] = "$refractBuff"; samplerNames[4] = "$skyMap"; samplerNames[5] = "$depthGradMap"; pixVersion = 2.0; }; singleton GFXStateBlockData( WaterBasicStateBlock ) { samplersDefined = true; samplerStates[0] = WaterSampler; // noise samplerStates[2] = SamplerClampLinear; // $reflectbuff samplerStates[3] = SamplerClampPoint; // $backbuff samplerStates[4] = SamplerWrapLinear; // $cubemap cullDefined = true; cullMode = "GFXCullCCW"; }; singleton GFXStateBlockData( UnderWaterBasicStateBlock : WaterBasicStateBlock ) { cullMode = "GFXCullCW"; }; singleton CustomMaterial( WaterBasicMat ) { // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = "core/art/water/noise02"; //sampler["skyMap"] = "$cubemap"; //sampler["prepassTex"] = "#prepass"; sampler["reflectMap"] = "$reflectbuff"; sampler["refractBuff"] = "$backbuff"; cubemap = NewLevelSkyCubemap; shader = WaterBasicShader; stateBlock = WaterBasicStateBlock; version = 2.0; }; //----------------------------------------------------------------------------- // Basic UnderWater //----------------------------------------------------------------------------- singleton ShaderData( UnderWaterBasicShader : WaterBasicShader) { defines = "UNDERWATER"; }; singleton CustomMaterial( UnderwaterBasicMat ) { // These samplers are set in code not here. // This is to allow different WaterObject instances // to use this same material but override these textures // per instance. //sampler["bumpMap"] = "core/art/water/noise02"; //samplers["skyMap"] = "$cubemap"; //sampler["prepassTex"] = "#prepass"; sampler["refractBuff"] = "$backbuff"; shader = UnderWaterBasicShader; stateBlock = UnderWaterBasicStateBlock; version = 2.0; };
using System; using System.Collections.Generic; using System.IO; using System.Text.Encodings.Web; using System.Threading.Tasks; using Fluid; using Fluid.Ast; using Microsoft.Extensions.DependencyInjection; using OrchardCore.Liquid; using OrchardCore.ResourceManagement; namespace OrchardCore.Resources.Liquid { public class ScriptTag { private static readonly char[] Separators = new[] { ',', ' ' }; public static async ValueTask<Completion> WriteToAsync(List<FilterArgument> argumentsList, TextWriter writer, TextEncoder encoder, TemplateContext context) { var services = ((LiquidTemplateContext)context).Services; var resourceManager = services.GetRequiredService<IResourceManager>(); string name = null; string src = null; bool? appendVersion = null; string cdnSrc = null; string debugSrc = null; string debugCdnSrc = null; bool? useCdn = null; string condition = null; string culture = null; bool? debug = null; string dependsOn = null; string version = null; var at = ResourceLocation.Unspecified; Dictionary<string, string> customAttributes = null; foreach (var argument in argumentsList) { switch (argument.Name) { case "name": name = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "src": src = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "append_version": appendVersion = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; case "cdn_src": cdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "debug_src": debugSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "debug_cdn_src": debugCdnSrc = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "use_cdn": useCdn = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; case "condition": condition = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "culture": culture = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "debug": debug = (await argument.Expression.EvaluateAsync(context)).ToBooleanValue(); break; case "depends_on": dependsOn = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "version": version = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; case "at": Enum.TryParse((await argument.Expression.EvaluateAsync(context)).ToStringValue(), ignoreCase: true, out at); break; default: (customAttributes ??= new Dictionary<string, string>())[argument.Name] = (await argument.Expression.EvaluateAsync(context)).ToStringValue(); break; } } if (String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(src)) { // {% script src:"~/TheBlogTheme/js/clean-blog.min.js" %} RequireSettings setting; if (String.IsNullOrEmpty(dependsOn)) { // Include custom script url setting = resourceManager.RegisterUrl("script", src, debugSrc); } else { // Anonymous declaration with dependencies, then display // Using the source as the name to prevent duplicate references to the same file var s = src.ToLowerInvariant(); var definition = resourceManager.InlineManifest.DefineScript(s); definition.SetUrl(src, debugSrc); if (!String.IsNullOrEmpty(version)) { definition.SetVersion(version); } if (!String.IsNullOrEmpty(cdnSrc)) { definition.SetCdn(cdnSrc, debugCdnSrc); } if (!String.IsNullOrEmpty(culture)) { definition.SetCultures(culture.Split(Separators, StringSplitOptions.RemoveEmptyEntries)); } if (!String.IsNullOrEmpty(dependsOn)) { definition.SetDependencies(dependsOn.Split(Separators, StringSplitOptions.RemoveEmptyEntries)); } if (appendVersion.HasValue) { definition.ShouldAppendVersion(appendVersion); } if (!String.IsNullOrEmpty(version)) { definition.SetVersion(version); } setting = resourceManager.RegisterResource("script", s); } if (at != ResourceLocation.Unspecified) { setting.AtLocation(at); } if (!String.IsNullOrEmpty(condition)) { setting.UseCondition(condition); } if (debug != null) { setting.UseDebugMode(debug.Value); } if (!String.IsNullOrEmpty(culture)) { setting.UseCulture(culture); } if (appendVersion.HasValue) { setting.ShouldAppendVersion(appendVersion); } if (customAttributes != null) { foreach (var attribute in customAttributes) { setting.SetAttribute(attribute.Key, attribute.Value); } } if (at == ResourceLocation.Unspecified || at == ResourceLocation.Inline) { resourceManager.RenderLocalScript(setting, writer); } } else if (!String.IsNullOrEmpty(name) && String.IsNullOrEmpty(src)) { // Resource required // {% script name:"bootstrap" %} var setting = resourceManager.RegisterResource("script", name); if (at != ResourceLocation.Unspecified) { setting.AtLocation(at); } if (useCdn != null) { setting.UseCdn(useCdn.Value); } if (!String.IsNullOrEmpty(condition)) { setting.UseCondition(condition); } if (debug != null) { setting.UseDebugMode(debug.Value); } if (!String.IsNullOrEmpty(culture)) { setting.UseCulture(culture); } if (appendVersion.HasValue) { setting.ShouldAppendVersion(appendVersion); } if (!String.IsNullOrEmpty(version)) { setting.UseVersion(version); } // This allows additions to the pre registered scripts dependencies. if (!String.IsNullOrEmpty(dependsOn)) { setting.SetDependencies(dependsOn.Split(Separators, StringSplitOptions.RemoveEmptyEntries)); } if (at == ResourceLocation.Unspecified || at == ResourceLocation.Inline) { resourceManager.RenderLocalScript(setting, writer); } } else if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(src)) { // Inline declaration var definition = resourceManager.InlineManifest.DefineScript(name); definition.SetUrl(src, debugSrc); if (!String.IsNullOrEmpty(version)) { definition.SetVersion(version); } if (!String.IsNullOrEmpty(cdnSrc)) { definition.SetCdn(cdnSrc, debugCdnSrc); } if (!String.IsNullOrEmpty(culture)) { definition.SetCultures(culture.Split(Separators, StringSplitOptions.RemoveEmptyEntries)); } if (!String.IsNullOrEmpty(dependsOn)) { definition.SetDependencies(dependsOn.Split(Separators, StringSplitOptions.RemoveEmptyEntries)); } if (appendVersion.HasValue) { definition.ShouldAppendVersion(appendVersion); } if (!String.IsNullOrEmpty(version)) { definition.SetVersion(version); } // If At is specified then we also render it if (at != ResourceLocation.Unspecified) { var setting = resourceManager.RegisterResource("script", name); setting.AtLocation(at); if (useCdn != null) { setting.UseCdn(useCdn.Value); } if (!String.IsNullOrEmpty(condition)) { setting.UseCondition(condition); } if (debug != null) { setting.UseDebugMode(debug.Value); } if (!String.IsNullOrEmpty(culture)) { setting.UseCulture(culture); } if (customAttributes != null) { foreach (var attribute in customAttributes) { setting.SetAttribute(attribute.Key, attribute.Value); } } if (at == ResourceLocation.Inline) { resourceManager.RenderLocalScript(setting, writer); } } } return Completion.Normal; } } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. 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. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using Antlr4.Runtime; using Antlr4.Runtime.Sharpen; using Antlr4.Runtime.Tree; using Antlr4.Runtime.Tree.Xpath; namespace Antlr4.Runtime.Tree.Xpath { /// <summary> /// Represent a subset of XPath XML path syntax for use in identifying nodes in /// parse trees. /// </summary> /// <remarks> /// Represent a subset of XPath XML path syntax for use in identifying nodes in /// parse trees. /// <p> /// Split path into words and separators /// <c>/</c> /// and /// <c>//</c> /// via ANTLR /// itself then walk path elements from left to right. At each separator-word /// pair, find set of nodes. Next stage uses those as work list.</p> /// <p> /// The basic interface is /// <see cref="FindAll(Antlr4.Runtime.Tree.IParseTree, string, Antlr4.Runtime.Parser)">ParseTree.findAll</see> /// <c>(tree, pathString, parser)</c> /// . /// But that is just shorthand for:</p> /// <pre> /// <see cref="XPath"/> /// p = new /// <see cref="XPath(Antlr4.Runtime.Parser, string)">XPath</see> /// (parser, pathString); /// return p. /// <see cref="Evaluate(Antlr4.Runtime.Tree.IParseTree)">evaluate</see> /// (tree); /// </pre> /// <p> /// See /// <c>org.antlr.v4.test.TestXPath</c> /// for descriptions. In short, this /// allows operators:</p> /// <dl> /// <dt>/</dt> <dd>root</dd> /// <dt>//</dt> <dd>anywhere</dd> /// <dt>!</dt> <dd>invert; this must appear directly after root or anywhere /// operator</dd> /// </dl> /// <p> /// and path elements:</p> /// <dl> /// <dt>ID</dt> <dd>token name</dd> /// <dt>'string'</dt> <dd>any string literal token from the grammar</dd> /// <dt>expr</dt> <dd>rule name</dd> /// <dt>*</dt> <dd>wildcard matching any node</dd> /// </dl> /// <p> /// Whitespace is not allowed.</p> /// </remarks> public class XPath { public const string Wildcard = "*"; public const string Not = "!"; protected internal string path; protected internal XPathElement[] elements; protected internal Parser parser; public XPath(Parser parser, string path) { // word not operator/separator // word for invert operator this.parser = parser; this.path = path; elements = Split(path); } // System.out.println(Arrays.toString(elements)); // TODO: check for invalid token/rule names, bad syntax public virtual XPathElement[] Split(string path) { AntlrInputStream @in; try { @in = new AntlrInputStream(new StringReader(path)); } catch (IOException ioe) { throw new ArgumentException("Could not read path: " + path, ioe); } XPathLexer lexer = new _XPathLexer_87(@in); lexer.RemoveErrorListeners(); lexer.AddErrorListener(new XPathLexerErrorListener()); CommonTokenStream tokenStream = new CommonTokenStream(lexer); try { tokenStream.Fill(); } catch (LexerNoViableAltException e) { int pos = lexer.Column; string msg = "Invalid tokens or characters at index " + pos + " in path '" + path + "'"; throw new ArgumentException(msg, e); } IList<IToken> tokens = tokenStream.GetTokens(); // System.out.println("path="+path+"=>"+tokens); IList<XPathElement> elements = new List<XPathElement>(); int n = tokens.Count; int i = 0; while (i < n) { IToken el = tokens[i]; IToken next = null; switch (el.Type) { case XPathLexer.Root: case XPathLexer.Anywhere: { bool anywhere = el.Type == XPathLexer.Anywhere; i++; next = tokens[i]; bool invert = next.Type == XPathLexer.Bang; if (invert) { i++; next = tokens[i]; } XPathElement pathElement = GetXPathElement(next, anywhere); pathElement.invert = invert; elements.Add(pathElement); i++; break; } case XPathLexer.TokenRef: case XPathLexer.RuleRef: case XPathLexer.Wildcard: { elements.Add(GetXPathElement(el, false)); i++; break; } case TokenConstants.Eof: { goto loop_break; } default: { throw new ArgumentException("Unknowth path element " + el); } } } loop_break: ; return elements.ToArray(); } private sealed class _XPathLexer_87 : XPathLexer { public _XPathLexer_87(ICharStream baseArg1) : base(baseArg1) { } public override void Recover(LexerNoViableAltException e) { throw e; } } /// <summary> /// Convert word like /// <c>*</c> /// or /// <c>ID</c> /// or /// <c>expr</c> /// to a path /// element. /// <paramref name="anywhere"/> /// is /// <see langword="true"/> /// if /// <c>//</c> /// precedes the /// word. /// </summary> protected internal virtual XPathElement GetXPathElement(IToken wordToken, bool anywhere) { if (wordToken.Type == TokenConstants.Eof) { throw new ArgumentException("Missing path element at end of path"); } string word = wordToken.Text; int ttype = parser.GetTokenType(word); int ruleIndex = parser.GetRuleIndex(word); switch (wordToken.Type) { case XPathLexer.Wildcard: { return anywhere ? new XPathWildcardAnywhereElement() : (XPathElement)new XPathWildcardElement(); } case XPathLexer.TokenRef: case XPathLexer.String: { if (ttype == TokenConstants.InvalidType) { throw new ArgumentException(word + " at index " + wordToken.StartIndex + " isn't a valid token name"); } return anywhere ? new XPathTokenAnywhereElement(word, ttype) : (XPathElement)new XPathTokenElement(word, ttype); } default: { if (ruleIndex == -1) { throw new ArgumentException(word + " at index " + wordToken.StartIndex + " isn't a valid rule name"); } return anywhere ? new XPathRuleAnywhereElement(word, ruleIndex) : (XPathElement)new XPathRuleElement(word, ruleIndex); } } } public static ICollection<IParseTree> FindAll(IParseTree tree, string xpath, Parser parser) { Antlr4.Runtime.Tree.Xpath.XPath p = new Antlr4.Runtime.Tree.Xpath.XPath(parser, xpath); return p.Evaluate(tree); } /// <summary> /// Return a list of all nodes starting at /// <paramref name="t"/> /// as root that satisfy the /// path. The root /// <c>/</c> /// is relative to the node passed to /// <see cref="Evaluate(Antlr4.Runtime.Tree.IParseTree)"/> /// . /// </summary> public virtual ICollection<IParseTree> Evaluate(IParseTree t) { ParserRuleContext dummyRoot = new ParserRuleContext(); dummyRoot.children = Antlr4.Runtime.Sharpen.Collections.SingletonList(t); // don't set t's parent. ICollection<IParseTree> work = new[] { dummyRoot }; int i = 0; while (i < elements.Length) { HashSet<IParseTree> visited = new HashSet<IParseTree>(); ICollection<IParseTree> next = new List<IParseTree>(); foreach (IParseTree node in work) { if (node.ChildCount > 0) { // only try to match next element if it has children // e.g., //func/*/stat might have a token node for which // we can't go looking for stat nodes. ICollection<IParseTree> matching = elements[i].Evaluate(node); foreach (IParseTree parseTree in matching) { if (visited.Add(parseTree)) next.Add(parseTree); } } } i++; work = next; } return work; } } }
// 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.Globalization; using System.Numerics; using Xunit; namespace System.Tests { public partial class UInt64Tests { [Fact] public static void Ctor_Empty() { var i = new ulong(); Assert.Equal((ulong)0, i); } [Fact] public static void Ctor_Value() { ulong i = 41; Assert.Equal((ulong)41, i); } [Fact] public static void MaxValue() { Assert.Equal(0xFFFFFFFFFFFFFFFF, ulong.MaxValue); } [Fact] public static void MinValue() { Assert.Equal((ulong)0, ulong.MinValue); } [Theory] [InlineData((ulong)234, (ulong)234, 0)] [InlineData((ulong)234, ulong.MinValue, 1)] [InlineData((ulong)234, (ulong)123, 1)] [InlineData((ulong)234, (ulong)456, -1)] [InlineData((ulong)234, ulong.MaxValue, -1)] [InlineData((ulong)234, null, 1)] public void CompareTo_Other_ReturnsExpected(ulong i, object value, int expected) { if (value is ulong ulongValue) { Assert.Equal(expected, Math.Sign(i.CompareTo(ulongValue))); } Assert.Equal(expected, Math.Sign(i.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotUlong_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((ulong)123).CompareTo(value)); } [Theory] [InlineData((ulong)789, (ulong)789, true)] [InlineData((ulong)788, (ulong)0, false)] [InlineData((ulong)0, (ulong)0, true)] [InlineData((ulong)789, null, false)] [InlineData((ulong)789, "789", false)] [InlineData((ulong)789, 789, false)] public static void Equals(ulong i1, object obj, bool expected) { if (obj is ulong i2) { Assert.Equal(expected, i1.Equals(i2)); Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode())); Assert.Equal((int)i1, i1.GetHashCode()); } Assert.Equal(expected, i1.Equals(obj)); } [Fact] public void GetTypeCode_Invoke_ReturnsUInt64() { Assert.Equal(TypeCode.UInt64, ((ulong)1).GetTypeCode()); } public static IEnumerable<object[]> ToString_TestData() { foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo }) { foreach (string defaultSpecifier in new[] { "G", "G\0", "\0N222", "\0", "" }) { yield return new object[] { (ulong)0, defaultSpecifier, defaultFormat, "0" }; yield return new object[] { (ulong)4567, defaultSpecifier, defaultFormat, "4567" }; yield return new object[] { ulong.MaxValue, defaultSpecifier, defaultFormat, "18446744073709551615" }; } yield return new object[] { (ulong)4567, "D", defaultFormat, "4567" }; yield return new object[] { (ulong)4567, "D18", defaultFormat, "000000000000004567" }; yield return new object[] { (ulong)0x2468, "x", defaultFormat, "2468" }; yield return new object[] { (ulong)2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) }; } var customFormat = new NumberFormatInfo() { NegativeSign = "#", NumberDecimalSeparator = "~", NumberGroupSeparator = "*", PositiveSign = "&", NumberDecimalDigits = 2, PercentSymbol = "@", PercentGroupSeparator = ",", PercentDecimalSeparator = ".", PercentDecimalDigits = 5 }; yield return new object[] { (ulong)2468, "N", customFormat, "2*468~00" }; yield return new object[] { (ulong)123, "E", customFormat, "1~230000E&002" }; yield return new object[] { (ulong)123, "F", customFormat, "123~00" }; yield return new object[] { (ulong)123, "P", customFormat, "12,300.00000 @" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(ulong i, string format, IFormatProvider provider, string expected) { // Format is case insensitive string upperFormat = format.ToUpperInvariant(); string lowerFormat = format.ToLowerInvariant(); string upperExpected = expected.ToUpperInvariant(); string lowerExpected = expected.ToLowerInvariant(); bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo); if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G") { if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString()); Assert.Equal(upperExpected, i.ToString((IFormatProvider)null)); } Assert.Equal(upperExpected, i.ToString(provider)); } if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString(upperFormat)); Assert.Equal(lowerExpected, i.ToString(lowerFormat)); Assert.Equal(upperExpected, i.ToString(upperFormat, null)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, null)); } Assert.Equal(upperExpected, i.ToString(upperFormat, provider)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider)); } [Fact] public static void ToString_InvalidFormat_ThrowsFormatException() { ulong i = 123; Assert.Throws<FormatException>(() => i.ToString("r")); // Invalid format Assert.Throws<FormatException>(() => i.ToString("r", null)); // Invalid format Assert.Throws<FormatException>(() => i.ToString("R")); // Invalid format Assert.Throws<FormatException>(() => i.ToString("R", null)); // Invalid format Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format } public static IEnumerable<object[]> Parse_Valid_TestData() { // Reuse all Int64 test data that's relevant foreach (object[] objs in Int64Tests.Parse_Valid_TestData()) { if ((long)objs[3] < 0) continue; yield return new object[] { objs[0], objs[1], objs[2], (ulong)(long)objs[3] }; } // All lengths decimal { string s = ""; ulong result = 0; for (int i = 1; i <= 20; i++) { result = (result * 10) + (ulong)(i % 10); s += (i % 10).ToString(); yield return new object[] { s, NumberStyles.Integer, null, result }; } } // All lengths hexadecimal { string s = ""; ulong result = 0; for (int i = 1; i <= 16; i++) { result = (result * 16) + (ulong)(i % 16); s += (i % 16).ToString("X"); yield return new object[] { s, NumberStyles.HexNumber, null, result }; } } // And test boundary conditions for UInt64 yield return new object[] { "18446744073709551615", NumberStyles.Integer, null, ulong.MaxValue }; yield return new object[] { "+18446744073709551615", NumberStyles.Integer, null, ulong.MaxValue }; yield return new object[] { " +18446744073709551615 ", NumberStyles.Integer, null, ulong.MaxValue }; yield return new object[] { "FFFFFFFFFFFFFFFF", NumberStyles.HexNumber, null, ulong.MaxValue }; yield return new object[] { " FFFFFFFFFFFFFFFF ", NumberStyles.HexNumber, null, ulong.MaxValue }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, ulong expected) { ulong result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.True(ulong.TryParse(value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, ulong.Parse(value)); } // Default provider if (provider == null) { Assert.Equal(expected, ulong.Parse(value, style)); // Substitute default NumberFormatInfo Assert.True(ulong.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(expected, result); Assert.Equal(expected, ulong.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Equal(expected, ulong.Parse(value, provider)); } // Full overloads Assert.True(ulong.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, ulong.Parse(value, style, provider)); } public static IEnumerable<object[]> Parse_Invalid_TestData() { // Reuse all long test data, except for those that wouldn't overflow ulong. foreach (object[] objs in Int64Tests.Parse_Invalid_TestData()) { if ((Type)objs[3] == typeof(OverflowException) && (!BigInteger.TryParse((string)objs[0], out BigInteger bi) || bi <= ulong.MaxValue)) { continue; } yield return objs; } // < min value foreach (string ws in new[] { "", " " }) { yield return new object[] { ws + "-1" + ws, NumberStyles.Integer, null, typeof(OverflowException) }; yield return new object[] { ws + "abc123" + ws, NumberStyles.Integer, new NumberFormatInfo { NegativeSign = "abc" }, typeof(OverflowException) }; } // > max value yield return new object[] { "18446744073709551616", NumberStyles.Integer, null, typeof(OverflowException) }; yield return new object[] { "10000000000000000", NumberStyles.HexNumber, null, typeof(OverflowException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { ulong result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.False(ulong.TryParse(value, out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => ulong.Parse(value)); } // Default provider if (provider == null) { Assert.Throws(exceptionType, () => ulong.Parse(value, style)); // Substitute default NumberFormatInfo Assert.False(ulong.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => ulong.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Throws(exceptionType, () => ulong.Parse(value, provider)); } // Full overloads Assert.False(ulong.TryParse(value, style, provider, out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => ulong.Parse(value, style, provider)); } [Theory] [InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)] [InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")] public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName) { ulong result = 0; AssertExtensions.Throws<ArgumentException>(paramName, () => ulong.TryParse("1", style, null, out result)); Assert.Equal(default(ulong), result); AssertExtensions.Throws<ArgumentException>(paramName, () => ulong.Parse("1", style)); AssertExtensions.Throws<ArgumentException>(paramName, () => ulong.Parse("1", style, null)); } } }
using System.Diagnostics; namespace Lucene.Net.Codecs.Lucene41 { using IOUtils = Lucene.Net.Util.IOUtils; /* * 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 SegmentReadState = Lucene.Net.Index.SegmentReadState; using SegmentWriteState = Lucene.Net.Index.SegmentWriteState; /// <summary> /// Lucene 4.1 postings format, which encodes postings in packed integer blocks /// for fast decode. /// /// <p><b>NOTE</b>: this format is still experimental and /// subject to change without backwards compatibility. /// /// <p> /// Basic idea: /// <ul> /// <li> /// <b>Packed Blocks and VInt Blocks</b>: /// <p>In packed blocks, integers are encoded with the same bit width (<seealso cref="PackedInts packed format"/>): /// the block size (i.e. number of integers inside block) is fixed (currently 128). Additionally blocks /// that are all the same value are encoded in an optimized way.</p> /// <p>In VInt blocks, integers are encoded as <seealso cref="DataOutput#writeVInt VInt"/>: /// the block size is variable.</p> /// </li> /// /// <li> /// <b>Block structure</b>: /// <p>When the postings are long enough, Lucene41PostingsFormat will try to encode most integer data /// as a packed block.</p> /// <p>Take a term with 259 documents as an example, the first 256 document ids are encoded as two packed /// blocks, while the remaining 3 are encoded as one VInt block. </p> /// <p>Different kinds of data are always encoded separately into different packed blocks, but may /// possibly be interleaved into the same VInt block. </p> /// <p>this strategy is applied to pairs: /// &lt;document number, frequency&gt;, /// &lt;position, payload length&gt;, /// &lt;position, offset start, offset length&gt;, and /// &lt;position, payload length, offsetstart, offset length&gt;.</p> /// </li> /// /// <li> /// <b>Skipdata settings</b>: /// <p>The structure of skip table is quite similar to previous version of Lucene. Skip interval is the /// same as block size, and each skip entry points to the beginning of each block. However, for /// the first block, skip data is omitted.</p> /// </li> /// /// <li> /// <b>Positions, Payloads, and Offsets</b>: /// <p>A position is an integer indicating where the term occurs within one document. /// A payload is a blob of metadata associated with current position. /// An offset is a pair of integers indicating the tokenized start/end offsets for given term /// in current position: it is essentially a specialized payload. </p> /// <p>When payloads and offsets are not omitted, numPositions==numPayloads==numOffsets (assuming a /// null payload contributes one count). As mentioned in block structure, it is possible to encode /// these three either combined or separately. /// <p>In all cases, payloads and offsets are stored together. When encoded as a packed block, /// position data is separated out as .pos, while payloads and offsets are encoded in .pay (payload /// metadata will also be stored directly in .pay). When encoded as VInt blocks, all these three are /// stored interleaved into the .pos (so is payload metadata).</p> /// <p>With this strategy, the majority of payload and offset data will be outside .pos file. /// So for queries that require only position data, running on a full index with payloads and offsets, /// this reduces disk pre-fetches.</p> /// </li> /// </ul> /// </p> /// /// <p> /// Files and detailed format: /// <ul> /// <li><tt>.tim</tt>: <a href="#Termdictionary">Term Dictionary</a></li> /// <li><tt>.tip</tt>: <a href="#Termindex">Term Index</a></li> /// <li><tt>.doc</tt>: <a href="#Frequencies">Frequencies and Skip Data</a></li> /// <li><tt>.pos</tt>: <a href="#Positions">Positions</a></li> /// <li><tt>.pay</tt>: <a href="#Payloads">Payloads and Offsets</a></li> /// </ul> /// </p> /// /// <a name="Termdictionary" id="Termdictionary"></a> /// <dl> /// <dd> /// <b>Term Dictionary</b> /// /// <p>The .tim file contains the list of terms in each /// field along with per-term statistics (such as docfreq) /// and pointers to the frequencies, positions, payload and /// skip data in the .doc, .pos, and .pay files. /// See <seealso cref="BlockTreeTermsWriter"/> for more details on the format. /// </p> /// /// <p>NOTE: The term dictionary can plug into different postings implementations: /// the postings writer/reader are actually responsible for encoding /// and decoding the PostingsHeader and TermMetadata sections described here:</p> /// /// <ul> /// <li>PostingsHeader --&gt; Header, PackedBlockSize</li> /// <li>TermMetadata --&gt; (DocFPDelta|SingletonDocID), PosFPDelta?, PosVIntBlockFPDelta?, PayFPDelta?, /// SkipFPDelta?</li> /// <li>Header, --&gt; <seealso cref="CodecUtil#writeHeader CodecHeader"/></li> /// <li>PackedBlockSize, SingletonDocID --&gt; <seealso cref="DataOutput#writeVInt VInt"/></li> /// <li>DocFPDelta, PosFPDelta, PayFPDelta, PosVIntBlockFPDelta, SkipFPDelta --&gt; <seealso cref="DataOutput#writeVLong VLong"/></li> /// <li>Footer --&gt; <seealso cref="CodecUtil#writeFooter CodecFooter"/></li> /// </ul> /// <p>Notes:</p> /// <ul> /// <li>Header is a <seealso cref="CodecUtil#writeHeader CodecHeader"/> storing the version information /// for the postings.</li> /// <li>PackedBlockSize is the fixed block size for packed blocks. In packed block, bit width is /// determined by the largest integer. Smaller block size result in smaller variance among width /// of integers hence smaller indexes. Larger block size result in more efficient bulk i/o hence /// better acceleration. this value should always be a multiple of 64, currently fixed as 128 as /// a tradeoff. It is also the skip interval used to accelerate <seealso cref="DocsEnum#advance(int)"/>. /// <li>DocFPDelta determines the position of this term's TermFreqs within the .doc file. /// In particular, it is the difference of file offset between this term's /// data and previous term's data (or zero, for the first term in the block).On disk it is /// stored as the difference from previous value in sequence. </li> /// <li>PosFPDelta determines the position of this term's TermPositions within the .pos file. /// While PayFPDelta determines the position of this term's &lt;TermPayloads, TermOffsets?&gt; within /// the .pay file. Similar to DocFPDelta, it is the difference between two file positions (or /// neglected, for fields that omit payloads and offsets).</li> /// <li>PosVIntBlockFPDelta determines the position of this term's last TermPosition in last pos packed /// block within the .pos file. It is synonym for PayVIntBlockFPDelta or OffsetVIntBlockFPDelta. /// this is actually used to indicate whether it is necessary to load following /// payloads and offsets from .pos instead of .pay. Every time a new block of positions are to be /// loaded, the PostingsReader will use this value to check whether current block is packed format /// or VInt. When packed format, payloads and offsets are fetched from .pay, otherwise from .pos. /// (this value is neglected when total number of positions i.e. totalTermFreq is less or equal /// to PackedBlockSize). /// <li>SkipFPDelta determines the position of this term's SkipData within the .doc /// file. In particular, it is the length of the TermFreq data. /// SkipDelta is only stored if DocFreq is not smaller than SkipMinimum /// (i.e. 128 in Lucene41PostingsFormat).</li> /// <li>SingletonDocID is an optimization when a term only appears in one document. In this case, instead /// of writing a file pointer to the .doc file (DocFPDelta), and then a VIntBlock at that location, the /// single document ID is written to the term dictionary.</li> /// </ul> /// </dd> /// </dl> /// /// <a name="Termindex" id="Termindex"></a> /// <dl> /// <dd> /// <b>Term Index</b> /// <p>The .tip file contains an index into the term dictionary, so that it can be /// accessed randomly. See <seealso cref="BlockTreeTermsWriter"/> for more details on the format.</p> /// </dd> /// </dl> /// /// /// <a name="Frequencies" id="Frequencies"></a> /// <dl> /// <dd> /// <b>Frequencies and Skip Data</b> /// /// <p>The .doc file contains the lists of documents which contain each term, along /// with the frequency of the term in that document (except when frequencies are /// omitted: <seealso cref="IndexOptions#DOCS_ONLY"/>). It also saves skip data to the beginning of /// each packed or VInt block, when the length of document list is larger than packed block size.</p> /// /// <ul> /// <li>docFile(.doc) --&gt; Header, &lt;TermFreqs, SkipData?&gt;<sup>TermCount</sup>, Footer</li> /// <li>Header --&gt; <seealso cref="CodecUtil#writeHeader CodecHeader"/></li> /// <li>TermFreqs --&gt; &lt;PackedBlock&gt; <sup>PackedDocBlockNum</sup>, /// VIntBlock? </li> /// <li>PackedBlock --&gt; PackedDocDeltaBlock, PackedFreqBlock? /// <li>VIntBlock --&gt; &lt;DocDelta[, Freq?]&gt;<sup>DocFreq-PackedBlockSize*PackedDocBlockNum</sup> /// <li>SkipData --&gt; &lt;&lt;SkipLevelLength, SkipLevel&gt; /// <sup>NumSkipLevels-1</sup>, SkipLevel&gt;, SkipDatum?</li> /// <li>SkipLevel --&gt; &lt;SkipDatum&gt; <sup>TrimmedDocFreq/(PackedBlockSize^(Level + 1))</sup></li> /// <li>SkipDatum --&gt; DocSkip, DocFPSkip, &lt;PosFPSkip, PosBlockOffset, PayLength?, /// PayFPSkip?&gt;?, SkipChildLevelPointer?</li> /// <li>PackedDocDeltaBlock, PackedFreqBlock --&gt; <seealso cref="PackedInts PackedInts"/></li> /// <li>DocDelta, Freq, DocSkip, DocFPSkip, PosFPSkip, PosBlockOffset, PayByteUpto, PayFPSkip /// --&gt; /// <seealso cref="DataOutput#writeVInt VInt"/></li> /// <li>SkipChildLevelPointer --&gt; <seealso cref="DataOutput#writeVLong VLong"/></li> /// <li>Footer --&gt; <seealso cref="CodecUtil#writeFooter CodecFooter"/></li> /// </ul> /// <p>Notes:</p> /// <ul> /// <li>PackedDocDeltaBlock is theoretically generated from two steps: /// <ol> /// <li>Calculate the difference between each document number and previous one, /// and get a d-gaps list (for the first document, use absolute value); </li> /// <li>For those d-gaps from first one to PackedDocBlockNum*PackedBlockSize<sup>th</sup>, /// separately encode as packed blocks.</li> /// </ol> /// If frequencies are not omitted, PackedFreqBlock will be generated without d-gap step. /// </li> /// <li>VIntBlock stores remaining d-gaps (along with frequencies when possible) with a format /// that encodes DocDelta and Freq: /// <p>DocDelta: if frequencies are indexed, this determines both the document /// number and the frequency. In particular, DocDelta/2 is the difference between /// this document number and the previous document number (or zero when this is the /// first document in a TermFreqs). When DocDelta is odd, the frequency is one. /// When DocDelta is even, the frequency is read as another VInt. If frequencies /// are omitted, DocDelta contains the gap (not multiplied by 2) between document /// numbers and no frequency information is stored.</p> /// <p>For example, the TermFreqs for a term which occurs once in document seven /// and three times in document eleven, with frequencies indexed, would be the /// following sequence of VInts:</p> /// <p>15, 8, 3</p> /// <p>If frequencies were omitted (<seealso cref="IndexOptions#DOCS_ONLY"/>) it would be this /// sequence of VInts instead:</p> /// <p>7,4</p> /// </li> /// <li>PackedDocBlockNum is the number of packed blocks for current term's docids or frequencies. /// In particular, PackedDocBlockNum = floor(DocFreq/PackedBlockSize) </li> /// <li>TrimmedDocFreq = DocFreq % PackedBlockSize == 0 ? DocFreq - 1 : DocFreq. /// We use this trick since the definition of skip entry is a little different from base interface. /// In <seealso cref="MultiLevelSkipListWriter"/>, skip data is assumed to be saved for /// skipInterval<sup>th</sup>, 2*skipInterval<sup>th</sup> ... posting in the list. However, /// in Lucene41PostingsFormat, the skip data is saved for skipInterval+1<sup>th</sup>, /// 2*skipInterval+1<sup>th</sup> ... posting (skipInterval==PackedBlockSize in this case). /// When DocFreq is multiple of PackedBlockSize, MultiLevelSkipListWriter will expect one /// more skip data than Lucene41SkipWriter. </li> /// <li>SkipDatum is the metadata of one skip entry. /// For the first block (no matter packed or VInt), it is omitted.</li> /// <li>DocSkip records the document number of every PackedBlockSize<sup>th</sup> document number in /// the postings (i.e. last document number in each packed block). On disk it is stored as the /// difference from previous value in the sequence. </li> /// <li>DocFPSkip records the file offsets of each block (excluding )posting at /// PackedBlockSize+1<sup>th</sup>, 2*PackedBlockSize+1<sup>th</sup> ... , in DocFile. /// The file offsets are relative to the start of current term's TermFreqs. /// On disk it is also stored as the difference from previous SkipDatum in the sequence.</li> /// <li>Since positions and payloads are also block encoded, the skip should skip to related block first, /// then fetch the values according to in-block offset. PosFPSkip and PayFPSkip record the file /// offsets of related block in .pos and .pay, respectively. While PosBlockOffset indicates /// which value to fetch inside the related block (PayBlockOffset is unnecessary since it is always /// equal to PosBlockOffset). Same as DocFPSkip, the file offsets are relative to the start of /// current term's TermFreqs, and stored as a difference sequence.</li> /// <li>PayByteUpto indicates the start offset of the current payload. It is equivalent to /// the sum of the payload lengths in the current block up to PosBlockOffset</li> /// </ul> /// </dd> /// </dl> /// /// <a name="Positions" id="Positions"></a> /// <dl> /// <dd> /// <b>Positions</b> /// <p>The .pos file contains the lists of positions that each term occurs at within documents. It also /// sometimes stores part of payloads and offsets for speedup.</p> /// <ul> /// <li>PosFile(.pos) --&gt; Header, &lt;TermPositions&gt; <sup>TermCount</sup>, Footer</li> /// <li>Header --&gt; <seealso cref="CodecUtil#writeHeader CodecHeader"/></li> /// <li>TermPositions --&gt; &lt;PackedPosDeltaBlock&gt; <sup>PackedPosBlockNum</sup>, /// VIntBlock? </li> /// <li>VIntBlock --&gt; &lt;PositionDelta[, PayloadLength?], PayloadData?, /// OffsetDelta?, OffsetLength?&gt;<sup>PosVIntCount</sup> /// <li>PackedPosDeltaBlock --&gt; <seealso cref="PackedInts PackedInts"/></li> /// <li>PositionDelta, OffsetDelta, OffsetLength --&gt; /// <seealso cref="DataOutput#writeVInt VInt"/></li> /// <li>PayloadData --&gt; <seealso cref="DataOutput#writeByte byte"/><sup>PayLength</sup></li> /// <li>Footer --&gt; <seealso cref="CodecUtil#writeFooter CodecFooter"/></li> /// </ul> /// <p>Notes:</p> /// <ul> /// <li>TermPositions are order by term (terms are implicit, from the term dictionary), and position /// values for each term document pair are incremental, and ordered by document number.</li> /// <li>PackedPosBlockNum is the number of packed blocks for current term's positions, payloads or offsets. /// In particular, PackedPosBlockNum = floor(totalTermFreq/PackedBlockSize) </li> /// <li>PosVIntCount is the number of positions encoded as VInt format. In particular, /// PosVIntCount = totalTermFreq - PackedPosBlockNum*PackedBlockSize</li> /// <li>The procedure how PackedPosDeltaBlock is generated is the same as PackedDocDeltaBlock /// in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.</li> /// <li>PositionDelta is, if payloads are disabled for the term's field, the /// difference between the position of the current occurrence in the document and /// the previous occurrence (or zero, if this is the first occurrence in this /// document). If payloads are enabled for the term's field, then PositionDelta/2 /// is the difference between the current and the previous position. If payloads /// are enabled and PositionDelta is odd, then PayloadLength is stored, indicating /// the length of the payload at the current term position.</li> /// <li>For example, the TermPositions for a term which occurs as the fourth term in /// one document, and as the fifth and ninth term in a subsequent document, would /// be the following sequence of VInts (payloads disabled): /// <p>4, 5, 4</p></li> /// <li>PayloadData is metadata associated with the current term position. If /// PayloadLength is stored at the current position, then it indicates the length /// of this payload. If PayloadLength is not stored, then this payload has the same /// length as the payload at the previous position.</li> /// <li>OffsetDelta/2 is the difference between this position's startOffset from the /// previous occurrence (or zero, if this is the first occurrence in this document). /// If OffsetDelta is odd, then the length (endOffset-startOffset) differs from the /// previous occurrence and an OffsetLength follows. Offset data is only written for /// <seealso cref="IndexOptions#DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS"/>.</li> /// </ul> /// </dd> /// </dl> /// /// <a name="Payloads" id="Payloads"></a> /// <dl> /// <dd> /// <b>Payloads and Offsets</b> /// <p>The .pay file will store payloads and offsets associated with certain term-document positions. /// Some payloads and offsets will be separated out into .pos file, for performance reasons.</p> /// <ul> /// <li>PayFile(.pay): --&gt; Header, &lt;TermPayloads, TermOffsets?&gt; <sup>TermCount</sup>, Footer</li> /// <li>Header --&gt; <seealso cref="CodecUtil#writeHeader CodecHeader"/></li> /// <li>TermPayloads --&gt; &lt;PackedPayLengthBlock, SumPayLength, PayData&gt; <sup>PackedPayBlockNum</sup> /// <li>TermOffsets --&gt; &lt;PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock&gt; <sup>PackedPayBlockNum</sup> /// <li>PackedPayLengthBlock, PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock --&gt; <seealso cref="PackedInts PackedInts"/></li> /// <li>SumPayLength --&gt; <seealso cref="DataOutput#writeVInt VInt"/></li> /// <li>PayData --&gt; <seealso cref="DataOutput#writeByte byte"/><sup>SumPayLength</sup></li> /// <li>Footer --&gt; <seealso cref="CodecUtil#writeFooter CodecFooter"/></li> /// </ul> /// <p>Notes:</p> /// <ul> /// <li>The order of TermPayloads/TermOffsets will be the same as TermPositions, note that part of /// payload/offsets are stored in .pos.</li> /// <li>The procedure how PackedPayLengthBlock and PackedOffsetLengthBlock are generated is the /// same as PackedFreqBlock in chapter <a href="#Frequencies">Frequencies and Skip Data</a>. /// While PackedStartDeltaBlock follows a same procedure as PackedDocDeltaBlock.</li> /// <li>PackedPayBlockNum is always equal to PackedPosBlockNum, for the same term. It is also synonym /// for PackedOffsetBlockNum.</li> /// <li>SumPayLength is the total length of payloads written within one block, should be the sum /// of PayLengths in one packed block.</li> /// <li>PayLength in PackedPayLengthBlock is the length of each payload associated with the current /// position.</li> /// </ul> /// </dd> /// </dl> /// </p> /// /// @lucene.experimental /// </summary> public sealed class Lucene41PostingsFormat : PostingsFormat { /// <summary> /// Filename extension for document number, frequencies, and skip data. /// See chapter: <a href="#Frequencies">Frequencies and Skip Data</a> /// </summary> public const string DOC_EXTENSION = "doc"; /// <summary> /// Filename extension for positions. /// See chapter: <a href="#Positions">Positions</a> /// </summary> public const string POS_EXTENSION = "pos"; /// <summary> /// Filename extension for payloads and offsets. /// See chapter: <a href="#Payloads">Payloads and Offsets</a> /// </summary> public const string PAY_EXTENSION = "pay"; private readonly int MinTermBlockSize; private readonly int MaxTermBlockSize; /// <summary> /// Fixed packed block size, number of integers encoded in /// a single packed block. /// </summary> // NOTE: must be multiple of 64 because of PackedInts long-aligned encoding/decoding public static int BLOCK_SIZE = 128; /// <summary> /// Creates {@code Lucene41PostingsFormat} with default /// settings. /// </summary> public Lucene41PostingsFormat() : this(BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE) { } /// <summary> /// Creates {@code Lucene41PostingsFormat} with custom /// values for {@code minBlockSize} and {@code /// maxBlockSize} passed to block terms dictionary. </summary> /// <seealso cref= BlockTreeTermsWriter#BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int) </seealso> public Lucene41PostingsFormat(int minTermBlockSize, int maxTermBlockSize) : base("Lucene41") { this.MinTermBlockSize = minTermBlockSize; Debug.Assert(minTermBlockSize > 1); this.MaxTermBlockSize = maxTermBlockSize; Debug.Assert(minTermBlockSize <= maxTermBlockSize); } public override string ToString() { return Name + "(blocksize=" + BLOCK_SIZE + ")"; } public override FieldsConsumer FieldsConsumer(SegmentWriteState state) { PostingsWriterBase postingsWriter = new Lucene41PostingsWriter(state); bool success = false; try { FieldsConsumer ret = new BlockTreeTermsWriter(state, postingsWriter, MinTermBlockSize, MaxTermBlockSize); success = true; return ret; } finally { if (!success) { IOUtils.CloseWhileHandlingException(postingsWriter); } } } public override FieldsProducer FieldsProducer(SegmentReadState state) { PostingsReaderBase postingsReader = new Lucene41PostingsReader(state.Directory, state.FieldInfos, state.SegmentInfo, state.Context, state.SegmentSuffix); bool success = false; try { FieldsProducer ret = new BlockTreeTermsReader(state.Directory, state.FieldInfos, state.SegmentInfo, postingsReader, state.Context, state.SegmentSuffix, state.TermsIndexDivisor); success = true; return ret; } finally { if (!success) { IOUtils.CloseWhileHandlingException(postingsReader); } } } } }
// ReSharper disable All using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json.Linq; using Frapid.WebsiteBuilder.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; namespace Frapid.WebsiteBuilder.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Tag Views. /// </summary> [RoutePrefix("api/v1.0/website/tag-view")] public class TagViewController : FrapidApiController { /// <summary> /// The TagView repository. /// </summary> private readonly ITagViewRepository TagViewRepository; public TagViewController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>(); this._UserId = AppUsers.GetCurrent().View.UserId.To<int>(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>(); this._Catalog = AppUsers.GetCatalog(); this.TagViewRepository = new Frapid.WebsiteBuilder.DataAccess.TagView { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public TagViewController(ITagViewRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.To<long>(); this._UserId = view.UserId.To<int>(); this._OfficeId = view.OfficeId.To<int>(); this._Catalog = catalog; this.TagViewRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Counts the number of tag views. /// </summary> /// <returns>Returns the count of the tag views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/website/tag-view/count")] [Authorize] public long Count() { try { return this.TagViewRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of tag view for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("all")] [Route("~/api/website/tag-view/export")] [Route("~/api/website/tag-view/all")] [Authorize] public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> Get() { try { return this.TagViewRepository.Get(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 tag views on each page, sorted by the property . /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/website/tag-view")] [Authorize] public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetPaginatedResult() { try { return this.TagViewRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 tag views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/website/tag-view/page/{pageNumber}")] [Authorize] public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetPaginatedResult(long pageNumber) { try { return this.TagViewRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of tag views using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered tag views.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/website/tag-view/count-where")] [Authorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.TagViewRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 tag views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/website/tag-view/get-where/{pageNumber}")] [Authorize] public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.TagViewRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of tag views using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered tag views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/website/tag-view/count-filtered/{filterName}")] [Authorize] public long CountFiltered(string filterName) { try { return this.TagViewRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 tag views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/website/tag-view/get-filtered/{pageNumber}/{filterName}")] [Authorize] public IEnumerable<Frapid.WebsiteBuilder.Entities.TagView> GetFiltered(long pageNumber, string filterName) { try { return this.TagViewRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
/* Copyright (c) 2006-2008 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. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #region Using directives #define USE_TRACING using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml; using System.Reflection; using Google.GData.Extensions; #endregion namespace Google.GData.Client { ////////////////////////////////////////////////////////////////////// /// <summary>String utilities /// </summary> ////////////////////////////////////////////////////////////////////// public sealed class Utilities { /// <summary> /// xsd version of bool:true /// </summary> public const string XSDTrue = "true"; /// <summary> /// xsd version of bool:false /// </summary> public const string XSDFalse = "false"; /// <summary> /// default user string /// </summary> public const string DefaultUser = "default"; ////////////////////////////////////////////////////////////////////// /// <summary>private constructor to prevent the compiler from generating a default one</summary> ////////////////////////////////////////////////////////////////////// private Utilities() { } ///////////////////////////////////////////////////////////////////////////// /// <summary>Little helper that checks if a string is XML persistable</summary> public static bool IsPersistable(string toPersist) { if (string.IsNullOrEmpty(toPersist) == false && toPersist.Trim().Length != 0) { return true; } return false; } /// <summary>Little helper that checks if a string is XML persistable</summary> public static bool IsPersistable(AtomUri uriString) { return uriString == null ? false : Utilities.IsPersistable(uriString.ToString()); } /// <summary>Little helper that checks if an int is XML persistable</summary> public static bool IsPersistable(int number) { return number == 0 ? false : true; } /// <summary>Little helper that checks if a datevalue is XML persistable</summary> public static bool IsPersistable(DateTime testDate) { return testDate == Utilities.EmptyDate ? false : true; } /// <summary> /// .NET treats bool as True/False as the default /// string representation. XSD requires true/false /// this method encapsulates this /// </summary> /// <param name="flag">the boolean to convert</param> /// <returns>"true" or "false"</returns> public static string ConvertBooleanToXSDString(bool flag) { return flag ? Utilities.XSDTrue : Utilities.XSDFalse; } /// <summary> /// .NET treats bool as True/False as the default /// string representation. XSD requires true/false /// this method encapsulates this /// </summary> /// <param name="obj">the object to convert</param> /// <returns>the string representation</returns> public static string ConvertToXSDString(Object obj) { if (obj is bool) { return ConvertBooleanToXSDString((bool) obj); } return Convert.ToString(obj, CultureInfo.InvariantCulture); } ////////////////////////////////////////////////////////////////////// /// <summary>helper to read in a string and Encode it</summary> /// <param name="content">the xmlreader string</param> /// <returns>UTF8 encoded string</returns> ////////////////////////////////////////////////////////////////////// public static string EncodeString(string content) { // get the encoding Encoding utf8Encoder = Encoding.UTF8; Byte[] utf8Bytes = EncodeStringToUtf8(content); char[] utf8Chars = new char[utf8Encoder.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)]; utf8Encoder.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0); String utf8String = new String(utf8Chars); return utf8String; } /// <summary> /// returns you a bytearray of UTF8 bytes from the string passed in /// the passed in string is assumed to be UTF16 /// </summary> /// <param name="content">UTF16 string</param> /// <returns>utf 8 byte array</returns> public static Byte[] EncodeStringToUtf8(string content) { // get the encoding Encoding utf8Encoder = Encoding.UTF8; Encoding utf16Encoder = Encoding.Unicode; Byte[] bytes = utf16Encoder.GetBytes(content); Byte[] utf8Bytes = Encoding.Convert(utf16Encoder, utf8Encoder, bytes); return utf8Bytes; } ////////////////////////////////////////////////////////////////////// /// <summary>helper to read in a string and Encode it according to /// RFC 5023 rules for slugheaders</summary> /// <param name="slug">the Unicode string for the slug header</param> /// <returns>ASCII encoded string</returns> ////////////////////////////////////////////////////////////////////// public static string EncodeSlugHeader(string slug) { if (slug == null) return ""; Byte[] bytes =EncodeStringToUtf8(slug); if (bytes == null) return ""; StringBuilder returnString = new StringBuilder(256); foreach (byte b in bytes) { if ((b < 0x20) || (b == 0x25) || (b > 0x7E)) { returnString.AppendFormat(CultureInfo.InvariantCulture, "%{0:X}", b); } else { returnString.Append((char) b); } } return returnString.ToString(); } /// <summary> /// used as a cover method to hide the actual decoding implementation /// decodes an html decoded string /// </summary> /// <param name="value">the string to decode</param> public static string DecodedValue(string value) { return System.Web.HttpUtility.HtmlDecode(value); } /// <summary> /// used as a cover method to hide the actual decoding implementation /// decodes an URL decoded string /// </summary> /// <param name="value">the string to decode</param> public static string UrlDecodedValue(string value) { return System.Web.HttpUtility.UrlDecode(value); } ////////////////////////////////////////////////////////////////////// /// <summary>helper to read in a string and replace the reserved URI /// characters with hex encoding</summary> /// <param name="content">the parameter string</param> /// <returns>hex encoded string</returns> ////////////////////////////////////////////////////////////////////// public static string UriEncodeReserved(string content) { if (content == null) return null; StringBuilder returnString = new StringBuilder(256); foreach (char ch in content) { if (ch == ';' || ch == '/' || ch == '?' || ch == ':' || ch == '@' || ch == '&' || ch == '=' || ch == '+' || ch == '$' || ch == ',' || ch == '%' ) { returnString.Append(Uri.HexEscape(ch)); } else { returnString.Append(ch); } } return returnString.ToString(); } /// <summary> /// tests an etag for weakness. returns TRUE for weak etags and for null strings /// </summary> /// <param name="eTag"></param> /// <returns></returns> public static bool IsWeakETag(string eTag) { if (eTag == null) { return true; } if (eTag.StartsWith("W/") == true) { return true; } return false; } /// <summary> /// tests an etag for weakness. returns TRUE for weak etags and for null strings /// </summary> /// <param name="ise">the element that supports an etag</param> /// <returns></returns> public static bool IsWeakETag(ISupportsEtag ise) { string eTag = null; if (ise != null) { eTag = ise.Etag; } return IsWeakETag(eTag); } ////////////////////////////////////////////////////////////////////// /// <summary>helper to read in a string and replace the reserved URI /// characters with hex encoding</summary> /// <param name="content">the parameter string</param> /// <returns>hex encoded string</returns> ////////////////////////////////////////////////////////////////////// public static string UriEncodeUnsafe(string content) { if (content == null) return null; StringBuilder returnString = new StringBuilder(256); foreach (char ch in content) { if (ch == ';' || ch == '/' || ch == '?' || ch == ':' || ch == '@' || ch == '&' || ch == '=' || ch == '+' || ch == '$' || ch == ',' || ch == ' ' || ch == '\'' || ch == '"' || ch == '>' || ch == '<' || ch == '#' || ch == '%' ) { returnString.Append(Uri.HexEscape(ch)); } else { returnString.Append(ch); } } return returnString.ToString(); } ////////////////////////////////////////////////////////////////////// /// <summary>Method to output just the date portion as string</summary> /// <param name="dateTime">the DateTime object to output as a string</param> /// <returns>an rfc-3339 string</returns> ////////////////////////////////////////////////////////////////////// public static string LocalDateInUTC(DateTime dateTime) { // Add "full-date T partial-time" return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } ////////////////////////////////////////////////////////////////////// /// <summary>Method to output DateTime as string</summary> /// <param name="dateTime">the DateTime object to output as a string</param> /// <returns>an rfc-3339 string</returns> ////////////////////////////////////////////////////////////////////// public static string LocalDateTimeInUTC(DateTime dateTime) { TimeSpan diffFromUtc = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime); // Add "full-date T partial-time" string strOutput = dateTime.ToString("s", CultureInfo.InvariantCulture); // Add "time-offset" return strOutput + FormatTimeOffset(diffFromUtc); } /// <summary> /// returns the next child element of the xml reader, based on the /// depth passed in. /// </summary> /// <param name="reader">the xml reader to use</param> /// <param name="depth">the depth to start with</param> /// <returns></returns> public static bool NextChildElement(XmlReader reader, ref int depth) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (reader.Depth == depth) { // assume we gone around circle, a child read and moved to the next element of the same KIND return false; } if (reader.NodeType == XmlNodeType.Element && depth >= 0 && reader.Depth > depth) { // assume we gone around circle, a child read and moved to the next element of the same KIND // but now we are in the parent/containing element, hence we return TRUE without reading further return true; } if (depth == -1) { depth = reader.Depth; } while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == depth) { return false; } else if (reader.NodeType == XmlNodeType.Element && reader.Depth > depth) { return true; } else if (reader.NodeType == XmlNodeType.Element && reader.Depth == depth) { // assume that we had no children. We read once and we are at the // next element, same level as the previous one. return false; } } return !reader.EOF; } ////////////////////////////////////////////////////////////////////// /// <summary>Helper method to format a TimeSpan as a string compliant with the "time-offset" format defined in RFC-3339</summary> /// <param name="spanFromUtc">the TimeSpan to format</param> /// <returns></returns> ////////////////////////////////////////////////////////////////////// public static string FormatTimeOffset(TimeSpan spanFromUtc) { // Simply return "Z" if there is no offset if (spanFromUtc == TimeSpan.Zero) return "Z"; // Return the numeric offset TimeSpan absoluteSpan = spanFromUtc.Duration(); if (spanFromUtc > TimeSpan.Zero) { return "+" + FormatNumOffset(absoluteSpan); } else { return "-" + FormatNumOffset(absoluteSpan); } } ////////////////////////////////////////////////////////////////////// /// <summary>Helper method to format a TimeSpan to {HH}:{MM}</summary> /// <param name="timeSpan">the TimeSpan to format</param> /// <returns>a string in "hh:mm" format.</returns> ////////////////////////////////////////////////////////////////////// internal static string FormatNumOffset(TimeSpan timeSpan) { return String.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}", timeSpan.Hours, timeSpan.Minutes); } ////////////////////////////////////////////////////////////////////// /// <summary>public static string CalculateUri(string base, string inheritedBase, string local)</summary> /// <param name="localBase">the baseUri from xml:base </param> /// <param name="inheritedBase">the pushed down baseUri from an outer element</param> /// <param name="localUri">the Uri value</param> /// <returns>the absolute Uri to use... </returns> ////////////////////////////////////////////////////////////////////// internal static string CalculateUri(AtomUri localBase, AtomUri inheritedBase, string localUri) { try { Uri uriBase = null; Uri uriSuperBase= null; Uri uriComplete = null; if (inheritedBase != null && inheritedBase.ToString() != null) { uriSuperBase = new Uri(inheritedBase.ToString()); } if (localBase != null && localBase.ToString() != null) { if (uriSuperBase != null) { uriBase = new Uri(uriSuperBase, localBase.ToString()); } else { uriBase = new Uri(localBase.ToString()); } } else { // if no local xml:base, take the passed down one uriBase = uriSuperBase; } if (localUri != null) { if (uriBase != null) { uriComplete = new Uri(uriBase, localUri.ToString()); } else { uriComplete = new Uri(localUri.ToString()); } } else { uriComplete = uriBase; } return uriComplete != null ? uriComplete.AbsoluteUri : null; } catch (System.UriFormatException) { return "Unsupported URI format"; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Sets the Atom namespace, if it's not already set. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <returns> the namespace prefix</returns> ////////////////////////////////////////////////////////////////////// static public string EnsureAtomNamespace(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(BaseNameTable.NSAtom); if (strPrefix == null) { writer.WriteAttributeString("xmlns", null, BaseNameTable.NSAtom); } return strPrefix; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Sets the gData namespace, if it's not already set. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <returns> the namespace prefix</returns> ////////////////////////////////////////////////////////////////////// static public string EnsureGDataNamespace(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(BaseNameTable.gNamespace); if (strPrefix == null) { writer.WriteAttributeString("xmlns", BaseNameTable.gDataPrefix, null, BaseNameTable.gNamespace); } return strPrefix; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Sets the gDataBatch namespace, if it's not already set. /// </summary> /// <param name="writer"> the xmlwriter to use</param> /// <returns> the namespace prefix</returns> ////////////////////////////////////////////////////////////////////// static public string EnsureGDataBatchNamespace(XmlWriter writer) { Tracing.Assert(writer != null, "writer should not be null"); if (writer == null) { throw new ArgumentNullException("writer"); } string strPrefix = writer.LookupPrefix(BaseNameTable.gBatchNamespace); if (strPrefix == null) { writer.WriteAttributeString("xmlns", BaseNameTable.gBatchPrefix, null, BaseNameTable.gBatchNamespace); } return strPrefix; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>searches tokenCollection for a specific NEXT value. /// The collection is assume to be a key/value pair list, so if A,B,C,D is the list /// A and C are keys, B and D are values /// </summary> /// <param name="tokens">the TokenCollection to search</param> /// <param name="key">the key to search for</param> /// <returns> the value string</returns> ////////////////////////////////////////////////////////////////////// static public string FindToken(TokenCollection tokens, string key) { if (tokens == null) { throw new ArgumentNullException("tokens"); } string returnValue = null; bool fNextOne=false; foreach (string token in tokens ) { if (fNextOne == true) { returnValue = token; break; } if (key == token) { // next one is it fNextOne = true; } } return returnValue; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>converts a form response stream to a TokenCollection, /// by parsing the contents of the stream for newlines and equal signs /// the input stream is assumed to be an ascii encoded form resonse /// </summary> /// <param name="inputStream">the stream to read and parse</param> /// <returns> the resulting TokenCollection </returns> ////////////////////////////////////////////////////////////////////// static public TokenCollection ParseStreamInTokenCollection(Stream inputStream) { // get the body and parse it ASCIIEncoding encoder = new ASCIIEncoding(); StreamReader readStream = new StreamReader(inputStream, encoder); String body = readStream.ReadToEnd(); readStream.Close(); Tracing.TraceMsg("got the following body back: " + body); // all we are interested is the token, so we break the string in parts TokenCollection tokens = new TokenCollection(body, '=', true, 2); return tokens; } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>parses a form response stream in token form for a specific value /// </summary> /// <param name="inputStream">the stream to read and parse</param> /// <param name="key">the key to search for</param> /// <returns> the string in the tokenized stream </returns> ////////////////////////////////////////////////////////////////////// static public string ParseValueFormStream(Stream inputStream, string key) { TokenCollection tokens = ParseStreamInTokenCollection(inputStream); return FindToken(tokens, key); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>returns a blank emptyDate. That's the default for an empty string date</summary> ////////////////////////////////////////////////////////////////////// public static DateTime EmptyDate { get { // that's the blank value you get when setting a DateTime to an empty string inthe property browswer return new DateTime(1,1,1); } } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// Finds a specific ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, the first one where /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="arrList">the array to search through</param> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <returns>Object</returns> public static IExtensionElementFactory FindExtension(ExtensionList arrList, string localName, string ns) { if (arrList == null) { return null; } foreach (IExtensionElementFactory ele in arrList) { if (compareXmlNess(ele.XmlName, localName, ele.XmlNameSpace, ns)) { return ele; } } return null; } /// <summary> /// Finds all ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, allwhere /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="arrList">the array to search through</param> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <param name="arr">the array to fill</param> /// <returns>none</returns> public static ExtensionList FindExtensions(ExtensionList arrList, string localName, string ns, ExtensionList arr) { if (arrList == null) { throw new ArgumentNullException("arrList"); } if (arr == null) { throw new ArgumentNullException("arr"); } foreach (IExtensionElementFactory ob in arrList) { XmlNode node = ob as XmlNode; if (node != null) { if (compareXmlNess(node.LocalName, localName, node.NamespaceURI, ns)) { arr.Add(ob); } } else { // only if the elements do implement the ExtensionElementFactory // do we know if it's xml name/namespace IExtensionElementFactory ele = ob as IExtensionElementFactory; if (ele != null) { if (compareXmlNess(ele.XmlName, localName, ele.XmlNameSpace, ns)) { arr.Add(ob); } } } } return arr; } /// <summary> /// Finds all ExtensionElement based on it's local name /// and it's namespace. If namespace is NULL, allwhere /// the localname matches is found. If there are extensionelements that do /// not implment ExtensionElementFactory, they will not be taken into account /// Primary use of this is to find XML nodes /// </summary> /// <param name="arrList">the array to search through</param> /// <param name="localName">the xml local name of the element to find</param> /// <param name="ns">the namespace of the elementToPersist</param> /// <returns>none</returns> public static List<T> FindExtensions<T>(ExtensionList arrList, string localName, string ns) where T : IExtensionElementFactory { List<T> list = new List<T>(); if (arrList == null) { throw new ArgumentNullException("arrList"); } foreach (IExtensionElementFactory obj in arrList) { if (obj is T) { T ele = (T) obj; // only if the elements do implement the ExtensionElementFactory // do we know if it's xml name/namespace if (ele != null) { if (compareXmlNess(ele.XmlName, localName, ele.XmlNameSpace, ns)) { list.Add(ele); } } } } return list; } /// <summary> /// save method to get an attribute value from an xmlnode /// </summary> /// <param name="attributeName"></param> /// <param name="xmlNode"></param> /// <returns></returns> public static string GetAttributeValue(string attributeName, XmlNode xmlNode) { if (xmlNode != null && attributeName != null && xmlNode.Attributes != null && xmlNode.Attributes[attributeName] != null) { return xmlNode.Attributes[attributeName].Value; } return null; } /// <summary> /// returns the current assembly version using split() instead of the version /// attribute to avoid security issues /// </summary> /// <returns>the current assembly version as a string</returns> public static string GetAssemblyVersion() { Assembly asm = Assembly.GetExecutingAssembly(); if (asm != null) { string[] parts = asm.FullName.Split(','); if (parts != null && parts.Length > 1) return parts[1].Trim(); } return "1.0.0"; } /// <summary> /// returns the useragent string, including a version number /// </summary> /// <returns>the constructed userAgend in a standard form</returns> public static string ConstructUserAgent(string applicationName, string serviceName) { return "G-" + applicationName + "/" + serviceName + "-CS-" + GetAssemblyVersion(); } private static bool compareXmlNess(string l1, string l2, string ns1, string ns2) { if (String.Compare(l1,l2)==0) { if (ns1 == null) { return true; } else if (String.Compare(ns1, ns2)==0) { return true; } } return false; } ////////////////////////////////////////////////////////////////////// /// <summary>goes to the Google auth service, and gets a new auth token</summary> /// <returns>the auth token, or NULL if none received</returns> ////////////////////////////////////////////////////////////////////// public static string QueryClientLoginToken(GDataCredentials gc, string serviceName, string applicationName, bool fUseKeepAlive, Uri clientLoginHandler ) { Tracing.Assert(gc != null, "Do not call QueryAuthToken with no network credentials"); if (gc == null) { throw new System.ArgumentNullException("nc", "No credentials supplied"); } HttpWebRequest authRequest = WebRequest.Create(clientLoginHandler) as HttpWebRequest; authRequest.KeepAlive = fUseKeepAlive; string accountType = GoogleAuthentication.AccountType; if (!String.IsNullOrEmpty(gc.AccountType)) { accountType += gc.AccountType; } else { accountType += GoogleAuthentication.AccountTypeDefault; } WebResponse authResponse = null; string authToken = null; try { authRequest.ContentType = HttpFormPost.Encoding; authRequest.Method = HttpMethods.Post; ASCIIEncoding encoder = new ASCIIEncoding(); string user = gc.Username == null ? "" : gc.Username; string pwd = gc.getPassword() == null ? "" : gc.getPassword(); // now enter the data in the stream string postData = GoogleAuthentication.Email + "=" + Utilities.UriEncodeUnsafe(user) + "&"; postData += GoogleAuthentication.Password + "=" + Utilities.UriEncodeUnsafe(pwd) + "&"; postData += GoogleAuthentication.Source + "=" + Utilities.UriEncodeUnsafe(applicationName) + "&"; postData += GoogleAuthentication.Service + "=" + Utilities.UriEncodeUnsafe(serviceName) + "&"; if (gc.CaptchaAnswer != null) { postData += GoogleAuthentication.CaptchaAnswer + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaAnswer) + "&"; } if (gc.CaptchaToken != null) { postData += GoogleAuthentication.CaptchaToken + "=" + Utilities.UriEncodeUnsafe(gc.CaptchaToken) + "&"; } postData += accountType; byte[] encodedData = encoder.GetBytes(postData); authRequest.ContentLength = encodedData.Length; Stream requestStream = authRequest.GetRequestStream() ; requestStream.Write(encodedData, 0, encodedData.Length); requestStream.Close(); authResponse = authRequest.GetResponse(); } catch (WebException e) { Tracing.TraceMsg("QueryAuthtoken failed " + e.Status + " " + e.Message); throw; } HttpWebResponse response = authResponse as HttpWebResponse; if (response != null) { // check the content type, it must be text if (!response.ContentType.StartsWith(HttpFormPost.ReturnContentType)) { throw new GDataRequestException("Execution of authentication request returned unexpected content type: " + response.ContentType, response); } TokenCollection tokens = Utilities.ParseStreamInTokenCollection(response.GetResponseStream()); authToken = Utilities.FindToken(tokens, GoogleAuthentication.AuthToken); if (authToken == null) { throw Utilities.getAuthException(tokens, response); } // failsafe. if getAuthException did not catch an error... int code= (int)response.StatusCode; if (code != 200) { throw new GDataRequestException("Execution of authentication request returned unexpected result: " +code, response); } } Tracing.Assert(authToken != null, "did not find an auth token in QueryAuthToken"); if (authResponse != null) { authResponse.Close(); } return authToken; } ///////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the respective GDataAuthenticationException given the return /// values from the login URI handler. /// </summary> /// <param name="tokens">The tokencollection of the parsed return form</param> /// <param name="response">the webresponse</param> /// <returns>AuthenticationException</returns> static LoggedException getAuthException(TokenCollection tokens, HttpWebResponse response) { String errorName = Utilities.FindToken(tokens, "Error"); int code= (int)response.StatusCode; if (errorName == null || errorName.Length == 0) { // no error given by Gaia, return a standard GDataRequestException throw new GDataRequestException("Execution of authentication request returned unexpected result: " +code, response); } if ("BadAuthentication".Equals(errorName)) { return new InvalidCredentialsException("Invalid credentials"); } else if ("AccountDeleted".Equals(errorName)) { return new AccountDeletedException("Account deleted"); } else if ("AccountDisabled".Equals(errorName)) { return new AccountDisabledException("Account disabled"); } else if ("NotVerified".Equals(errorName)) { return new NotVerifiedException("Not verified"); } else if ("TermsNotAgreed".Equals(errorName)) { return new TermsNotAgreedException("Terms not agreed"); } else if ("ServiceUnavailable".Equals(errorName)) { return new ServiceUnavailableException("Service unavailable"); } else if ("CaptchaRequired".Equals(errorName)) { String captchaPath = Utilities.FindToken(tokens, "CaptchaUrl"); String captchaToken = Utilities.FindToken(tokens, "CaptchaToken"); StringBuilder captchaUrl = new StringBuilder(); captchaUrl.Append(GoogleAuthentication.DefaultProtocol).Append("://"); captchaUrl.Append(GoogleAuthentication.DefaultDomain); captchaUrl.Append(GoogleAuthentication.AccountPrefix); captchaUrl.Append('/').Append(captchaPath); return new CaptchaRequiredException("Captcha required", captchaUrl.ToString(), captchaToken); } else { return new AuthenticationException("Error authenticating (check service name): " + errorName); } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>standard string tokenizer class. Pretty much cut/copy/paste out of /// MSDN. /// </summary> ////////////////////////////////////////////////////////////////////// public class TokenCollection : IEnumerable { private string[] elements; /// <summary>Constructor, takes a string and a delimiter set</summary> public TokenCollection(string source, char[] delimiters) { if (source != null) { this.elements = source.Split(delimiters); } } /// <summary>Constructor, takes a string and a delimiter set</summary> public TokenCollection(string source, char delimiter, bool seperateLines, int resultsPerLine) { if (source != null) { if (seperateLines == true) { // first split the source into a line array string [] lines = source.Split(new char[] {'\n'}); int size = lines.Length * resultsPerLine; this.elements = new string[size]; size = 0; foreach (String s in lines) { // do not use Split(char,int) as that one // does not exist on .NET CF string []temp = s.Split(delimiter); int counter = temp.Length < resultsPerLine ? temp.Length : resultsPerLine; for (int i = 0; i <counter; i++) { this.elements[size++] = temp[i]; } for (int i = resultsPerLine; i < temp.Length; i++) { this.elements[size-1] += delimiter + temp[i]; } } } else { string[] temp = source.Split(delimiter); resultsPerLine = temp.Length < resultsPerLine ? temp.Length : resultsPerLine; this.elements = new string[resultsPerLine]; for (int i = 0; i <resultsPerLine; i++) { this.elements[i] = temp[i]; } for (int i = resultsPerLine; i < temp.Length; i++) { this.elements[resultsPerLine-1] += delimiter + temp[i]; } } } } /// <summary> /// creates a dictionary of tokens based on this tokencollection /// </summary> /// <returns></returns> public Dictionary<string, string> CreateDictionary() { Dictionary<string, string> dict = new Dictionary<string,string>(); for (int i=0; i< this.elements.Length; i+=2) { string key = this.elements[i]; string val = this.elements[i+1]; dict.Add(key, val); } return dict; } /// <summary>IEnumerable Interface Implementation, for the noninterface</summary> public TokenEnumerator GetEnumerator() // non-IEnumerable version { return new TokenEnumerator(this); } /// <summary>IEnumerable Interface Implementation</summary> IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) new TokenEnumerator(this); } /// <summary>Inner class implements IEnumerator interface</summary> public class TokenEnumerator: IEnumerator { private int position = -1; private TokenCollection tokens; /// <summary>Standard constructor</summary> public TokenEnumerator(TokenCollection tokens) { this.tokens = tokens; } /// <summary>IEnumerable::MoveNext implementation</summary> public bool MoveNext() { if (this.tokens.elements != null && position < this.tokens.elements.Length - 1) { position++; return true; } else { return false; } } /// <summary>IEnumerable::Reset implementation</summary> public void Reset() { position = -1; } /// <summary>Current implementation, non interface, type-safe</summary> public string Current { get { return this.tokens.elements != null ? this.tokens.elements[position] : null; } } /// <summary>Current implementation, interface, not type-safe</summary> object IEnumerator.Current { get { return this.tokens.elements != null ? this.tokens.elements[position] : null; } } } } ///////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////
using System; using System.Runtime.InteropServices; using SFML.System; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// IntRect is an utility class for manipulating 2D rectangles /// with integer coordinates /// </summary> //////////////////////////////////////////////////////////// [StructLayout(LayoutKind.Sequential)] public struct IntRect : IEquatable<IntRect> { //////////////////////////////////////////////////////////// /// <summary> /// Construct the rectangle from its coordinates /// </summary> /// <param name="left">Left coordinate of the rectangle</param> /// <param name="top">Top coordinate of the rectangle</param> /// <param name="width">Width of the rectangle</param> /// <param name="height">Height of the rectangle</param> //////////////////////////////////////////////////////////// public IntRect(int left, int top, int width, int height) { Left = left; Top = top; Width = width; Height = height; } //////////////////////////////////////////////////////////// /// <summary> /// Construct the rectangle from position and size /// </summary> /// <param name="position">Position of the top-left corner of the rectangle</param> /// <param name="size">Size of the rectangle</param> //////////////////////////////////////////////////////////// public IntRect(Vector2i position, Vector2i size) : this(position.X, position.Y, size.X, size.Y) { } //////////////////////////////////////////////////////////// /// <summary> /// Check if a point is inside the rectangle's area /// </summary> /// <param name="x">X coordinate of the point to test</param> /// <param name="y">Y coordinate of the point to test</param> /// <returns>True if the point is inside</returns> //////////////////////////////////////////////////////////// public bool Contains(int x, int y) { int minX = Math.Min(Left, Left + Width); int maxX = Math.Max(Left, Left + Width); int minY = Math.Min(Top, Top + Height); int maxY = Math.Max(Top, Top + Height); return (x >= minX) && (x < maxX) && (y >= minY) && (y < maxY); } //////////////////////////////////////////////////////////// /// <summary> /// Check intersection between two rectangles /// </summary> /// <param name="rect"> Rectangle to test</param> /// <returns>True if rectangles overlap</returns> //////////////////////////////////////////////////////////// public bool Intersects(IntRect rect) { IntRect overlap; return Intersects(rect, out overlap); } //////////////////////////////////////////////////////////// /// <summary> /// Check intersection between two rectangles /// </summary> /// <param name="rect"> Rectangle to test</param> /// <param name="overlap">Rectangle to be filled with overlapping rect</param> /// <returns>True if rectangles overlap</returns> //////////////////////////////////////////////////////////// public bool Intersects(IntRect rect, out IntRect overlap) { // Rectangles with negative dimensions are allowed, so we must handle them correctly // Compute the min and max of the first rectangle on both axes int r1MinX = Math.Min(Left, Left + Width); int r1MaxX = Math.Max(Left, Left + Width); int r1MinY = Math.Min(Top, Top + Height); int r1MaxY = Math.Max(Top, Top + Height); // Compute the min and max of the second rectangle on both axes int r2MinX = Math.Min(rect.Left, rect.Left + rect.Width); int r2MaxX = Math.Max(rect.Left, rect.Left + rect.Width); int r2MinY = Math.Min(rect.Top, rect.Top + rect.Height); int r2MaxY = Math.Max(rect.Top, rect.Top + rect.Height); // Compute the intersection boundaries int interLeft = Math.Max(r1MinX, r2MinX); int interTop = Math.Max(r1MinY, r2MinY); int interRight = Math.Min(r1MaxX, r2MaxX); int interBottom = Math.Min(r1MaxY, r2MaxY); // If the intersection is valid (positive non zero area), then there is an intersection if ((interLeft < interRight) && (interTop < interBottom)) { overlap.Left = interLeft; overlap.Top = interTop; overlap.Width = interRight - interLeft; overlap.Height = interBottom - interTop; return true; } else { overlap.Left = 0; overlap.Top = 0; overlap.Width = 0; overlap.Height = 0; return false; } } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[IntRect]" + " Left(" + Left + ")" + " Top(" + Top + ")" + " Width(" + Width + ")" + " Height(" + Height + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Compare rectangle and object and checks if they are equal /// </summary> /// <param name="obj">Object to check</param> /// <returns>Object and rectangle are equal</returns> //////////////////////////////////////////////////////////// public override bool Equals(object obj) { return (obj is IntRect) && obj.Equals(this); } /////////////////////////////////////////////////////////// /// <summary> /// Compare two rectangles and checks if they are equal /// </summary> /// <param name="other">Rectangle to check</param> /// <returns>Rectangles are equal</returns> //////////////////////////////////////////////////////////// public bool Equals(IntRect other) { return (Left == other.Left) && (Top == other.Top) && (Width == other.Width) && (Height == other.Height); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a integer describing the object /// </summary> /// <returns>Integer description of the object</returns> //////////////////////////////////////////////////////////// public override int GetHashCode() { return unchecked((int)((uint)Left ^ (((uint)Top << 13) | ((uint)Top >> 19)) ^ (((uint)Width << 26) | ((uint)Width >> 6)) ^ (((uint)Height << 7) | ((uint)Height >> 25)))); } //////////////////////////////////////////////////////////// /// <summary> /// Operator == overload ; check rect equality /// </summary> /// <param name="r1">First rect</param> /// <param name="r2">Second rect</param> /// <returns>r1 == r2</returns> //////////////////////////////////////////////////////////// public static bool operator ==(IntRect r1, IntRect r2) { return r1.Equals(r2); } //////////////////////////////////////////////////////////// /// <summary> /// Operator != overload ; check rect inequality /// </summary> /// <param name="r1">First rect</param> /// <param name="r2">Second rect</param> /// <returns>r1 != r2</returns> //////////////////////////////////////////////////////////// public static bool operator !=(IntRect r1, IntRect r2) { return !r1.Equals(r2); } //////////////////////////////////////////////////////////// /// <summary> /// Explicit casting to another rectangle type /// </summary> /// <param name="r">Rectangle being casted</param> /// <returns>Casting result</returns> //////////////////////////////////////////////////////////// public static explicit operator FloatRect(IntRect r) { return new FloatRect((float)r.Left, (float)r.Top, (float)r.Width, (float)r.Height); } /// <summary>Left coordinate of the rectangle</summary> public int Left; /// <summary>Top coordinate of the rectangle</summary> public int Top; /// <summary>Width of the rectangle</summary> public int Width; /// <summary>Height of the rectangle</summary> public int Height; } //////////////////////////////////////////////////////////// /// <summary> /// IntRect is an utility class for manipulating 2D rectangles /// with float coordinates /// </summary> //////////////////////////////////////////////////////////// [StructLayout(LayoutKind.Sequential)] public struct FloatRect : IEquatable<FloatRect> { //////////////////////////////////////////////////////////// /// <summary> /// Construct the rectangle from its coordinates /// </summary> /// <param name="left">Left coordinate of the rectangle</param> /// <param name="top">Top coordinate of the rectangle</param> /// <param name="width">Width of the rectangle</param> /// <param name="height">Height of the rectangle</param> //////////////////////////////////////////////////////////// public FloatRect(float left, float top, float width, float height) { Left = left; Top = top; Width = width; Height = height; } //////////////////////////////////////////////////////////// /// <summary> /// Construct the rectangle from position and size /// </summary> /// <param name="position">Position of the top-left corner of the rectangle</param> /// <param name="size">Size of the rectangle</param> //////////////////////////////////////////////////////////// public FloatRect(Vector2f position, Vector2f size) : this(position.X, position.Y, size.X, size.Y) { } //////////////////////////////////////////////////////////// /// <summary> /// Check if a point is inside the rectangle's area /// </summary> /// <param name="x">X coordinate of the point to test</param> /// <param name="y">Y coordinate of the point to test</param> /// <returns>True if the point is inside</returns> //////////////////////////////////////////////////////////// public bool Contains(float x, float y) { float minX = Math.Min(Left, Left + Width); float maxX = Math.Max(Left, Left + Width); float minY = Math.Min(Top, Top + Height); float maxY = Math.Max(Top, Top + Height); return (x >= minX) && (x < maxX) && (y >= minY) && (y < maxY); } //////////////////////////////////////////////////////////// /// <summary> /// Check intersection between two rectangles /// </summary> /// <param name="rect"> Rectangle to test</param> /// <returns>True if rectangles overlap</returns> //////////////////////////////////////////////////////////// public bool Intersects(FloatRect rect) { FloatRect overlap; return Intersects(rect, out overlap); } //////////////////////////////////////////////////////////// /// <summary> /// Check intersection between two rectangles /// </summary> /// <param name="rect"> Rectangle to test</param> /// <param name="overlap">Rectangle to be filled with overlapping rect</param> /// <returns>True if rectangles overlap</returns> //////////////////////////////////////////////////////////// public bool Intersects(FloatRect rect, out FloatRect overlap) { // Rectangles with negative dimensions are allowed, so we must handle them correctly // Compute the min and max of the first rectangle on both axes float r1MinX = Math.Min(Left, Left + Width); float r1MaxX = Math.Max(Left, Left + Width); float r1MinY = Math.Min(Top, Top + Height); float r1MaxY = Math.Max(Top, Top + Height); // Compute the min and max of the second rectangle on both axes float r2MinX = Math.Min(rect.Left, rect.Left + rect.Width); float r2MaxX = Math.Max(rect.Left, rect.Left + rect.Width); float r2MinY = Math.Min(rect.Top, rect.Top + rect.Height); float r2MaxY = Math.Max(rect.Top, rect.Top + rect.Height); // Compute the intersection boundaries float interLeft = Math.Max(r1MinX, r2MinX); float interTop = Math.Max(r1MinY, r2MinY); float interRight = Math.Min(r1MaxX, r2MaxX); float interBottom = Math.Min(r1MaxY, r2MaxY); // If the intersection is valid (positive non zero area), then there is an intersection if ((interLeft < interRight) && (interTop < interBottom)) { overlap.Left = interLeft; overlap.Top = interTop; overlap.Width = interRight - interLeft; overlap.Height = interBottom - interTop; return true; } else { overlap.Left = 0; overlap.Top = 0; overlap.Width = 0; overlap.Height = 0; return false; } } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[FloatRect]" + " Left(" + Left + ")" + " Top(" + Top + ")" + " Width(" + Width + ")" + " Height(" + Height + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Compare rectangle and object and checks if they are equal /// </summary> /// <param name="obj">Object to check</param> /// <returns>Object and rectangle are equal</returns> //////////////////////////////////////////////////////////// public override bool Equals(object obj) { return (obj is FloatRect) && obj.Equals(this); } /////////////////////////////////////////////////////////// /// <summary> /// Compare two rectangles and checks if they are equal /// </summary> /// <param name="other">Rectangle to check</param> /// <returns>Rectangles are equal</returns> //////////////////////////////////////////////////////////// public bool Equals(FloatRect other) { return (Left == other.Left) && (Top == other.Top) && (Width == other.Width) && (Height == other.Height); } //////////////////////////////////////////////////////////// /// <summary> /// Provide a integer describing the object /// </summary> /// <returns>Integer description of the object</returns> //////////////////////////////////////////////////////////// public override int GetHashCode() { return unchecked((int)((uint)Left ^ (((uint)Top << 13) | ((uint)Top >> 19)) ^ (((uint)Width << 26) | ((uint)Width >> 6)) ^ (((uint)Height << 7) | ((uint)Height >> 25)))); } //////////////////////////////////////////////////////////// /// <summary> /// Operator == overload ; check rect equality /// </summary> /// <param name="r1">First rect</param> /// <param name="r2">Second rect</param> /// <returns>r1 == r2</returns> //////////////////////////////////////////////////////////// public static bool operator ==(FloatRect r1, FloatRect r2) { return r1.Equals(r2); } //////////////////////////////////////////////////////////// /// <summary> /// Operator != overload ; check rect inequality /// </summary> /// <param name="r1">First rect</param> /// <param name="r2">Second rect</param> /// <returns>r1 != r2</returns> //////////////////////////////////////////////////////////// public static bool operator !=(FloatRect r1, FloatRect r2) { return !r1.Equals(r2); } //////////////////////////////////////////////////////////// /// <summary> /// Explicit casting to another rectangle type /// </summary> /// <param name="r">Rectangle being casted</param> /// <returns>Casting result</returns> //////////////////////////////////////////////////////////// public static explicit operator IntRect(FloatRect r) { return new IntRect((int)r.Left, (int)r.Top, (int)r.Width, (int)r.Height); } /// <summary>Left coordinate of the rectangle</summary> public float Left; /// <summary>Top coordinate of the rectangle</summary> public float Top; /// <summary>Width of the rectangle</summary> public float Width; /// <summary>Height of the rectangle</summary> public float Height; } } }
// 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>HotelReconciliation</c> resource.</summary> public sealed partial class HotelReconciliationName : gax::IResourceName, sys::IEquatable<HotelReconciliationName> { /// <summary>The possible contents of <see cref="HotelReconciliationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c>. /// </summary> CustomerCommission = 1, } private static gax::PathTemplate s_customerCommission = new gax::PathTemplate("customers/{customer_id}/hotelReconciliations/{commission_id}"); /// <summary>Creates a <see cref="HotelReconciliationName"/> 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="HotelReconciliationName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static HotelReconciliationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new HotelReconciliationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="HotelReconciliationName"/> with the pattern /// <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="commissionId">The <c>Commission</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="HotelReconciliationName"/> constructed from the provided ids. /// </returns> public static HotelReconciliationName FromCustomerCommission(string customerId, string commissionId) => new HotelReconciliationName(ResourceNameType.CustomerCommission, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), commissionId: gax::GaxPreconditions.CheckNotNullOrEmpty(commissionId, nameof(commissionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="HotelReconciliationName"/> with pattern /// <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="commissionId">The <c>Commission</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="HotelReconciliationName"/> with pattern /// <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c>. /// </returns> public static string Format(string customerId, string commissionId) => FormatCustomerCommission(customerId, commissionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="HotelReconciliationName"/> with pattern /// <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="commissionId">The <c>Commission</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="HotelReconciliationName"/> with pattern /// <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c>. /// </returns> public static string FormatCustomerCommission(string customerId, string commissionId) => s_customerCommission.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(commissionId, nameof(commissionId))); /// <summary> /// Parses the given resource name string into a new <see cref="HotelReconciliationName"/> 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}/hotelReconciliations/{commission_id}</c></description></item> /// </list> /// </remarks> /// <param name="hotelReconciliationName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="HotelReconciliationName"/> if successful.</returns> public static HotelReconciliationName Parse(string hotelReconciliationName) => Parse(hotelReconciliationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="HotelReconciliationName"/> 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}/hotelReconciliations/{commission_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="hotelReconciliationName">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="HotelReconciliationName"/> if successful.</returns> public static HotelReconciliationName Parse(string hotelReconciliationName, bool allowUnparsed) => TryParse(hotelReconciliationName, allowUnparsed, out HotelReconciliationName 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="HotelReconciliationName"/> 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}/hotelReconciliations/{commission_id}</c></description></item> /// </list> /// </remarks> /// <param name="hotelReconciliationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="HotelReconciliationName"/>, 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 hotelReconciliationName, out HotelReconciliationName result) => TryParse(hotelReconciliationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="HotelReconciliationName"/> 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}/hotelReconciliations/{commission_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="hotelReconciliationName">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="HotelReconciliationName"/>, 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 hotelReconciliationName, bool allowUnparsed, out HotelReconciliationName result) { gax::GaxPreconditions.CheckNotNull(hotelReconciliationName, nameof(hotelReconciliationName)); gax::TemplatedResourceName resourceName; if (s_customerCommission.TryParseName(hotelReconciliationName, out resourceName)) { result = FromCustomerCommission(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(hotelReconciliationName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private HotelReconciliationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string commissionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; CommissionId = commissionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="HotelReconciliationName"/> class from the component parts of /// pattern <c>customers/{customer_id}/hotelReconciliations/{commission_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="commissionId">The <c>Commission</c> ID. Must not be <c>null</c> or empty.</param> public HotelReconciliationName(string customerId, string commissionId) : this(ResourceNameType.CustomerCommission, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), commissionId: gax::GaxPreconditions.CheckNotNullOrEmpty(commissionId, nameof(commissionId))) { } /// <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>Commission</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CommissionId { 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.CustomerCommission: return s_customerCommission.Expand(CustomerId, CommissionId); 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 HotelReconciliationName); /// <inheritdoc/> public bool Equals(HotelReconciliationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(HotelReconciliationName a, HotelReconciliationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(HotelReconciliationName a, HotelReconciliationName b) => !(a == b); } public partial class HotelReconciliation { /// <summary> /// <see cref="HotelReconciliationName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal HotelReconciliationName ResourceNameAsHotelReconciliationName { get => string.IsNullOrEmpty(ResourceName) ? null : HotelReconciliationName.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() ?? ""; } } }
#region License // Copyright (C) 2011-2014 Kazunori Sakamoto // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using Code2Xml.Core.Generators; using Code2Xml.Core.SyntaxTree; using NUnit.Framework; using ParserTests; namespace Code2Xml.Learner.Core.Learning.Experiments { [TestFixture] public class LuaExperiment : Experiment { public static CstGenerator Generator = CstGenerators.LuaUsingAntlr3; private const string LangName = "Lua"; private static readonly LearningExperiment[] Experiments = { new LuaComplexStatementExperiment(), //new LuaSuperComplexBranchExperiment(), //new LuaExpressionStatementExperiment(), //new LuaArithmeticOperatorExperiment(), //new LuaSuperComplexBranchExperimentWithoutTrue(), //new LuaComplexBranchExperiment(), //new LuaStatementExperiment(), //new LuaIfExperiment(), //new LuaWhileExperiment(), //new LuaDoWhileExperiment(), //new LuaPrintExperiment(), //new LuaStatementExperiment(), //new LuaLabeledStatementExperiment(), //new LuaEmptyStatementExperiment(), }; #region LearningSets private static readonly Tuple<string, string>[] LearningSets = { Tuple.Create( @"https://github.com/kennyledet/Algorithm-Implementations.git", @"ec423a1984fa923e117053c114c92ae86d32bfd4"), Tuple.Create( @"https://github.com/nrk/redis-lua.git", @"4408c3d686ffd1f2689c0561a166821785cc09ec"), Tuple.Create( @"https://github.com/gamesys/moonshine.git", @"ca6d7a57bfb676caf409e7398a448f90eb139b47"), Tuple.Create( @"https://github.com/tekkub/wow-ui-source.git", @"e9e777a6d1baca29d6253260a69463767d8d9b00"), Tuple.Create( @"https://github.com/minetest/minetest_game.git", @"15740ffd3d1ea1af182a8607c600f3af414c2c73"), Tuple.Create( @"https://github.com/kikito/lua_missions.git", @"330d7702417c4b18358ab822ba676058892ad889"), Tuple.Create( @"https://github.com/kernelsauce/turbo.git", @"d1411bbbcbe18cb20a7d91bb95505d952993c31f"), Tuple.Create( @"https://github.com/appwilldev/moochine.git", @"9f643a5b51fb132c11ec1c870e4979cf03012992"), Tuple.Create( @"https://github.com/Fluorohydride/ygopro.git", @"16a98132749215b8ca27f6e479976ef42c4cd0fc"), Tuple.Create( @"https://github.com/Shestak/ShestakUI.git", @"42527a9c4b81c3c1f762b73d4e777cd0fbd3a852"), Tuple.Create( @"https://github.com/pavouk/lgi.git", @"3feb90f4c0c20312e646fb8b1106a5c44a04293e"), Tuple.Create( @"https://github.com/virgo-agent-toolkit/rackspace-monitoring-agent.git", @"5197adcd93c61db3c30b1a45a6fc6dbd1d95d66f"), Tuple.Create( @"https://github.com/pkulchenko/MobDebug.git", @"c2b9988ccda7998be466da67690316b45fd3469a"), Tuple.Create( @"https://github.com/davidm/lua-inspect.git", @"ca3988019a2f5f1b3f4e94b285eb6e77e5923dd3"), Tuple.Create( @"https://github.com/lipp/lua-websockets.git", @"9ade24fc972cfc80b5d1d31e1d92ec1d28b7c4be"), Tuple.Create( @"https://github.com/harningt/luajson.git", @"827425b10152f8cdc515e4ffb900338506e28910"), Tuple.Create( @"https://github.com/AdamBuchweitz/CrawlSpaceLib.git", @"471868fe6cad288cac57281b5218cdd711b826eb"), Tuple.Create( @"https://github.com/miko/Love2d-samples.git", @"50a8b4b43d517081a83d036e4510904402dcd7d2"), Tuple.Create( @"https://github.com/Neopallium/lua-handlers.git", @"ae93f442175f4f03dd612cafa073df74a8fe626f"), Tuple.Create( @"https://github.com/cedlemo/blingbling.git", @"7ac39503e2811042cf0d83a0874d230779a710ef"), Tuple.Create( @"https://github.com/radamanthus/corona-game-template.git", @"2d1dc125648b70b855fe5a318ad8a6ee30a4e1d2"), Tuple.Create( @"https://github.com/ostinelli/gin.git", @"8361d2f5f16e64c65ba33d1dbbc74b97d5256f76"), Tuple.Create( @"https://github.com/ymobe/rapanui.git", @"595076d5706695a8b9b8de393b749d7d90a414a2"), Tuple.Create( @"https://github.com/bjc/prosody.git", @"701fa72ca55909888b3fd428724128c654d8b543"), Tuple.Create( @"https://github.com/Yonaba/Jumper.git", @"2479afadf3d50e30ea9f9ab104e6229176d57339"), Tuple.Create( @"https://github.com/iamgreaser/iceball.git", @"4ae5d09ce4fd2269f4e097b63bd0fd9b83f2198f"), Tuple.Create( @"https://github.com/xopxe/Lumen.git", @"264d9d042ee9848bccfd064d69259c1d6bde0a2e"), Tuple.Create( @"https://github.com/Bertram25/ValyriaTear.git", @"a0e86da761fbc84ace9a778faf64e0f3687dbb3e"), Tuple.Create( @"https://github.com/Yonaba/Moses.git", @"57c7b5d1d1f074cafbd570088ad8681b03c65601"), Tuple.Create( @"https://github.com/metadeus/luv.git", @"655c0efc14572d18744aff336210b30574dd7eaf"), Tuple.Create( @"https://github.com/lubyk/dub.git", @"b0c7087e878937399f329468bff41de9484f8b0c"), Tuple.Create( @"https://github.com/pygy/LuLPeg.git", @"c457b27e0d7fc935b133921bf3aee92efffe40c8"), Tuple.Create( @"https://github.com/lua-nucleo/lua-nucleo.git", @"570e115dab1260ad433bd778eebb5d91fd122d5a"), Tuple.Create( @"https://github.com/annulen/premake.git", @"c559fa4913bd86be6e415c3b193db90ae4607f5b"), Tuple.Create( @"https://github.com/Neopallium/LuaNativeObjects.git", @"a5c444769b7dfad1436a1bc4fe21dce75629db25"), Tuple.Create( @"https://github.com/SiENcE/lovecodify.git", @"9b84ce1a5f3474707e6021355afd6c2554f18251"), Tuple.Create( @"https://github.com/jp-ganis/JPS.git", @"c65f107fa59a5f572e0ffd70be7990a873d87487"), Tuple.Create( @"https://github.com/stravant/LuaMinify.git", @"c284a942089b0154af7498b110e02d1bba8aee16"), Tuple.Create( @"https://github.com/UPenn-RoboCup/UPennalizers.git", @"abd9b34294a6485965be274333b72f1272f8f3c8"), Tuple.Create( @"https://github.com/SimonLarsen/mrrescue.git", @"8f226413b95544d0e0744d9c3e92c68b87659483"), Tuple.Create( @"https://github.com/meric/l2l.git", @"e9394879e9bde63b1b21e39928ac19f304fc1b39"), Tuple.Create( @"https://github.com/dmccuskey/DMC-Corona-Library.git", @"8c85803e39a673cc84b6aa089b51be56f05dd062"), Tuple.Create( @"https://github.com/Neopallium/lua-pb.git", @"862fe3121e71f695d9a44ee1d1038069292b69f3"), Tuple.Create( @"https://github.com/SnakeSVx/spacebuild.git", @"68186b8bc7cabbb5275afd734fae9613fbd8761d"), Tuple.Create( @"https://github.com/Wiladams/LAPHLibs.git", @"aed3531fb6face76c5634bde995e9cf503d6136b"), Tuple.Create( @"https://github.com/tales/sourceoftales.git", @"f259c99ebb42a4956f6e4c5464051651a3226d5a"), Tuple.Create( @"https://github.com/paulofmandown/rotLove.git", @"bb089f3294ba9cd1f7cc031dffc0b695fa2ed4bf"), Tuple.Create( @"https://github.com/Eonblast/fleece-lite.git", @"06103ea87601c74801ca5780bc9014011243bbec"), Tuple.Create( @"https://github.com/ildyria/iFilger.git", @"d092e040143146a551b6821b6a9b199a4b98e9db"), }; #endregion private static IEnumerable<TestCaseData> TestCases { get { foreach (var exp in Experiments) { foreach (var learningSet in LearningSets.Skip(SkipCount).Take(TakeCount)) { var url = learningSet.Item1; var path = Fixture.GetGitRepositoryPath(url); File.AppendAllText(@"C:\Users\exKAZUu\Desktop\Debug.txt", url + "Clone\r\n"); Git.Clone(path, url); Git.Checkout(path, learningSet.Item2); File.AppendAllText(@"C:\Users\exKAZUu\Desktop\Debug.txt", "Done\r\n"); yield return new TestCaseData(exp, path); } } } } protected override string SearchPattern { get { return "*.lua"; } } [Test] public void TestApply() { var seedPaths = new List<string> { Fixture.GetInputCodePath(LangName, "Seed.lua"), }; LearnAndApply(seedPaths, LearningSets, Experiments); } //[Test, TestCaseSource("TestCases")] public void Test(LearningExperiment exp, string projectPath) { var seedPaths = new List<string> { Fixture.GetInputCodePath(LangName, "Seed.lua"), }; Learn(seedPaths, exp, projectPath); } } public class LuaComplexBranchExperiment : LearningExperiment { protected override CstGenerator Generator => LuaExperiment.Generator; public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaComplexBranchExperiment() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var siblings = node.Siblings().ToList(); var parent = node.Parent; if (parent.SafeName() == "stat" && siblings[0].TokenText == "if") { return true; } if (parent.SafeName() == "stat" && siblings[0].TokenText == "while") { return true; } if (parent.SafeName() == "stat" && siblings[0].TokenText == "repeat") { return true; } return false; } } public class LuaSuperComplexBranchExperiment : LearningExperiment { protected override CstGenerator Generator => LuaExperiment.Generator; public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public override IEnumerable<SelectedFragment> AcceptingFragments => new[] { new SelectedFragment(1, @"print(b)", "b"), new SelectedFragment(2, @"print(b, c)", "b"), new SelectedFragment(2, @"rint(b, c)", "c"), new SelectedFragment(7, @"if b then", "b"), new SelectedFragment(8, @"elseif b then", "b"), new SelectedFragment(11, @"while b do", "b"), new SelectedFragment(15, @"until b", "b"), new SelectedFragment(24, @"if true then", "true"), new SelectedFragment(25, @"elseif true then", "true"), new SelectedFragment(28, @"while true do", "true"), new SelectedFragment(32, @"until true", "true"), }; public LuaSuperComplexBranchExperiment() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var siblings = node.Siblings().ToList(); var parent = node.Parent; if (parent.SafeName() == "stat" && siblings[0].TokenText == "if") { return true; } if (parent.SafeName() == "stat" && siblings[0].TokenText == "while") { return true; } if (parent.SafeName() == "stat" && siblings[0].TokenText == "repeat") { return true; } var ppp = node.SafeParent().SafeParent().SafeParent(); var pppp = ppp.SafeParent(); if (pppp.SafeName() == "functioncall" && ppp.Prev != null && ppp.Prev.TokenText == "print") { return true; } return false; } } public class LuaSuperComplexBranchExperimentWithoutTrue : LearningExperiment { protected override CstGenerator Generator => LuaExperiment.Generator; public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public override IEnumerable<SelectedFragment> AcceptingFragments => new[] { new SelectedFragment(1, @"print(b)", "b"), new SelectedFragment(2, @"print(b, c)", "b"), new SelectedFragment(2, @"rint(b, c)", "c"), new SelectedFragment(7, @"if b then", "b"), new SelectedFragment(8, @"elseif b then", "b"), new SelectedFragment(11, @"while b do", "b"), new SelectedFragment(15, @"until b", "b"), }; //public override IEnumerable<SelectedFragment> RejectingFragments { // get { // return new[] { // new SelectedFragment(24, @"if true then", "true"), // new SelectedFragment(25, @"elseif true then", "true"), // new SelectedFragment(28, @"while true do", "true"), // new SelectedFragment(32, @"until true", "true"), // }; // } //} public LuaSuperComplexBranchExperimentWithoutTrue() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var siblings = node.Siblings().ToList(); var parent = node.Parent; if (parent.SafeName() == "stat" && siblings[0].TokenText == "if") { return node.TokenText != "true"; } if (parent.SafeName() == "stat" && siblings[0].TokenText == "while") { return node.TokenText != "true"; } if (parent.SafeName() == "stat" && siblings[0].TokenText == "repeat") { return node.TokenText != "true"; } var ppp = node.SafeParent().SafeParent().SafeParent(); var pppp = ppp.SafeParent(); if (pppp.SafeName() == "functioncall" && ppp.Prev != null && ppp.Prev.TokenText == "print") { return node.TokenText != "true"; } return false; } } public class LuaIfExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaIfExperiment() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var siblings = node.Siblings().ToList(); var parent = node.Parent; if (parent.SafeName() == "stat" && siblings[0].TokenText == "if") { return true; } return false; } } public class LuaWhileExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaWhileExperiment() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var siblings = node.Siblings().ToList(); var parent = node.Parent; if (parent.SafeName() == "stat" && siblings[0].TokenText == "while") { return true; } return false; } } public class LuaDoWhileExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaDoWhileExperiment() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var siblings = node.Siblings().ToList(); var parent = node.Parent; if (parent.SafeName() == "stat" && siblings[0].TokenText == "repeat") { return true; } return false; } } public class LuaPrintExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaPrintExperiment() : base("exp") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { var ppp = node.SafeParent().SafeParent().SafeParent(); var pppp = ppp.SafeParent(); if (pppp.SafeName() == "functioncall" && ppp.Prev != null && ppp.Prev.TokenText == "print") { return true; } return false; } } public class LuaComplexStatementExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public override IEnumerable<SelectedFragment> AcceptingFragments { get { return new[] { new SelectedFragment(1, @"print(b)"), new SelectedFragment(2, @"print(b, c)"), new SelectedFragment(4, @"i = 0"), new SelectedFragment(5, @"f(0 + 1 - 2 * 3 / 4 % 5)"), new SelectedFragment(7, @"if b then elseif b then end"), new SelectedFragment(11, @"while b do end"), new SelectedFragment(14, @"repeat until b"), new SelectedFragment(17, @"for i = 0, 1, 1 do end"), new SelectedFragment(22, @"i = 0"), new SelectedFragment(24, @"if true then elseif true then end"), new SelectedFragment(28, @"while true do end"), new SelectedFragment(31, @"repeat until true"), }; } } public LuaComplexStatementExperiment() : base("stat") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { if (node.FirstChild.Name == "label") { return false; } if (node.FirstChild.TokenText == ";") { return false; } return true; } } public class LuaStatementExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaStatementExperiment() : base("stat") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { return true; } } public class LuaLabeledStatementExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaLabeledStatementExperiment() : base("stat") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { if (node.FirstChild.Name == "label") { return true; } return false; } } public class LuaEmptyStatementExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public LuaEmptyStatementExperiment() : base("stat") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { if (node.FirstChild.TokenText == ";") { return true; } return false; } } public class LuaExpressionStatementExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public override IEnumerable<SelectedFragment> AcceptingFragments { get { return new[] { new SelectedFragment(1, @"print(b)"), new SelectedFragment(2, @"print(b, c)"), new SelectedFragment(4, @"i = 0"), new SelectedFragment(5, @"f(0 + 1 - 2 * 3 / 4 % 5)"), new SelectedFragment(22, @"i = 0"), }; } } public LuaExpressionStatementExperiment() : base("stat") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { return node.FirstChild.Name == "varlist" || node.FirstChild.Name == "functioncall"; } } public class LuaArithmeticOperatorExperiment : LearningExperiment { protected override CstGenerator Generator { get { return LuaExperiment.Generator; } } public override FeatureExtractor CreateExtractor() { return new FeatureExtractor(); } public override IEnumerable<SelectedFragment> AcceptingFragments { get { return new[] { new SelectedFragment(5, @"0 + 1", @"+"), new SelectedFragment(5, @"1 - 2", @"-"), new SelectedFragment(5, @"2 * 3", @"*"), new SelectedFragment(5, @"3 / 4", @"/") }; } } public LuaArithmeticOperatorExperiment() : base("TOKENS") {} public override bool ProtectedIsAcceptedUsingOracle(CstNode node) { if (node.Name == "binop") { node = node.FirstChild; } return node.Parent.Name == "binop" && (node.TokenText == "+" || node.TokenText == "-" || node.TokenText == "*" || node.TokenText == "/"); } } }
using System.Diagnostics; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2007 August 27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file contains code used to implement mutexes on Btree objects. ** This code really belongs in btree.c. But btree.c is getting too ** big and we want to break it down some. This packaged seemed like ** a good breakout. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ //#include "btreeInt.h" #if !SQLITE_OMIT_SHARED_CACHE #if SQLITE_THREADSAFE /* ** Obtain the BtShared mutex associated with B-Tree handle p. Also, ** set BtShared.db to the database handle associated with p and the ** p->locked boolean to true. */ static void lockBtreeMutex(Btree *p){ assert( p->locked==0 ); assert( sqlite3_mutex_notheld(p->pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3_mutex_enter(p->pBt->mutex); p->pBt->db = p->db; p->locked = 1; } /* ** Release the BtShared mutex associated with B-Tree handle p and ** clear the p->locked boolean. */ static void unlockBtreeMutex(Btree *p){ BtShared *pBt = p->pBt; assert( p->locked==1 ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( sqlite3_mutex_held(p->db->mutex) ); assert( p->db==pBt->db ); sqlite3_mutex_leave(pBt->mutex); p->locked = 0; } /* ** Enter a mutex on the given BTree object. ** ** If the object is not sharable, then no mutex is ever required ** and this routine is a no-op. The underlying mutex is non-recursive. ** But we keep a reference count in Btree.wantToLock so the behavior ** of this interface is recursive. ** ** To avoid deadlocks, multiple Btrees are locked in the same order ** by all database connections. The p->pNext is a list of other ** Btrees belonging to the same database connection as the p Btree ** which need to be locked after p. If we cannot get a lock on ** p, then first unlock all of the others on p->pNext, then wait ** for the lock to become available on p, then relock all of the ** subsequent Btrees that desire a lock. */ void sqlite3BtreeEnter(Btree *p){ Btree *pLater; /* Some basic sanity checking on the Btree. The list of Btrees ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to ** the same connection. Only shared Btrees are on the list. */ assert( p->pNext==0 || p->pNext->pBt>p->pBt ); assert( p->pPrev==0 || p->pPrev->pBt<p->pBt ); assert( p->pNext==0 || p->pNext->db==p->db ); assert( p->pPrev==0 || p->pPrev->db==p->db ); assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); /* Check for locking consistency */ assert( !p->locked || p->wantToLock>0 ); assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ assert( sqlite3_mutex_held(p->db->mutex) ); /* Unless the database is sharable and unlocked, then BtShared.db ** should already be set correctly. */ assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db ); if( !p->sharable ) return; p->wantToLock++; if( p->locked ) return; /* In most cases, we should be able to acquire the lock we ** want without having to go throught the ascending lock ** procedure that follows. Just be sure not to block. */ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ p->pBt->db = p->db; p->locked = 1; return; } /* To avoid deadlock, first release all locks with a larger ** BtShared address. Then acquire our lock. Then reacquire ** the other BtShared locks that we used to hold in ascending ** order. */ for(pLater=p->pNext; pLater; pLater=pLater->pNext){ assert( pLater->sharable ); assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt ); assert( !pLater->locked || pLater->wantToLock>0 ); if( pLater->locked ){ unlockBtreeMutex(pLater); } } lockBtreeMutex(p); for(pLater=p->pNext; pLater; pLater=pLater->pNext){ if( pLater->wantToLock ){ lockBtreeMutex(pLater); } } } /* ** Exit the recursive mutex on a Btree. */ void sqlite3BtreeLeave(Btree *p){ if( p->sharable ){ assert( p->wantToLock>0 ); p->wantToLock--; if( p->wantToLock==0 ){ unlockBtreeMutex(p); } } } #if NDEBUG /* ** Return true if the BtShared mutex is held on the btree, or if the ** B-Tree is not marked as sharable. ** ** This routine is used only from within assert() statements. */ int sqlite3BtreeHoldsMutex(Btree *p){ assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 ); assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) ); assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) ); return (p->sharable==0 || p->locked); } #endif #if SQLITE_OMIT_INCRBLOB /* ** Enter and leave a mutex on a Btree given a cursor owned by that ** Btree. These entry points are used by incremental I/O and can be ** omitted if that module is not used. */ void sqlite3BtreeEnterCursor(BtCursor *pCur){ sqlite3BtreeEnter(pCur->pBtree); } void sqlite3BtreeLeaveCursor(BtCursor *pCur){ sqlite3BtreeLeave(pCur->pBtree); } #endif //* SQLITE_OMIT_INCRBLOB */ /* ** Enter the mutex on every Btree associated with a database ** connection. This is needed (for example) prior to parsing ** a statement since we will be comparing table and column names ** against all schemas and we do not want those schemas being ** reset out from under us. ** ** There is a corresponding leave-all procedures. ** ** Enter the mutexes in accending order by BtShared pointer address ** to avoid the possibility of deadlock when two threads with ** two or more btrees in common both try to lock all their btrees ** at the same instant. */ void sqlite3BtreeEnterAll(sqlite3 *db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeEnter(p); } } void sqlite3BtreeLeaveAll(sqlite3 *db){ int i; Btree *p; assert( sqlite3_mutex_held(db->mutex) ); for(i=0; i<db->nDb; i++){ p = db->aDb[i].pBt; if( p ) sqlite3BtreeLeave(p); } } /* ** Return true if a particular Btree requires a lock. Return FALSE if ** no lock is ever required since it is not sharable. */ int sqlite3BtreeSharable(Btree *p){ return p->sharable; } #if NDEBUG /* ** Return true if the current thread holds the database connection ** mutex and all required BtShared mutexes. ** ** This routine is used inside assert() statements only. */ int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){ int i; if( !sqlite3_mutex_held(db->mutex) ){ return 0; } for(i=0; i<db->nDb; i++){ Btree *p; p = db->aDb[i].pBt; if( p && p->sharable && (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){ return 0; } } return 1; } #endif //* NDEBUG */ #if NDEBUG /* ** Return true if the correct mutexes are held for accessing the ** db->aDb[iDb].pSchema structure. The mutexes required for schema ** access are: ** ** (1) The mutex on db ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt. ** ** If pSchema is not NULL, then iDb is computed from pSchema and ** db using sqlite3SchemaToIndex(). */ int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){ Btree *p; assert( db!=0 ); if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema); assert( iDb>=0 && iDb<db->nDb ); if( !sqlite3_mutex_held(db->mutex) ) return 0; if( iDb==1 ) return 1; p = db->aDb[iDb].pBt; assert( p!=0 ); return p->sharable==0 || p->locked==1; } #endif //* NDEBUG */ #else //* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */ /* ** The following are special cases for mutex enter routines for use ** in single threaded applications that use shared cache. Except for ** these two routines, all mutex operations are no-ops in that case and ** are null #defines in btree.h. ** ** If shared cache is disabled, then all btree mutex routines, including ** the ones below, are no-ops and are null #defines in btree.h. */ void sqlite3BtreeEnter(Btree *p){ p->pBt->db = p->db; } void sqlite3BtreeEnterAll(sqlite3 *db){ int i; for(i=0; i<db->nDb; i++){ Btree *p = db->aDb[i].pBt; if( p ){ p->pBt->db = p->db; } } } #endif //* if SQLITE_THREADSAFE */ #endif //* ifndef SQLITE_OMIT_SHARED_CACHE */ } }
using System; using System.Linq; using System.Reflection; using FluentAssertions.Common; using FluentAssertions.Primitives; using FluentAssertions.Types; #if !OLD_MSTEST using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #else using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace FluentAssertions.Specs { [TestClass] public class TypeAssertionSpecs { #region Be [TestMethod] public void When_type_is_equal_to_the_same_type_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); Type sameType = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Be(sameType); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_type_is_equal_to_another_type_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); Type differentType = typeof (ClassWithoutAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Be(differentType); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_type_is_equal_to_another_type_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); Type differentType = typeof (ClassWithoutAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Be(differentType, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>().WithMessage( "Expected type to be FluentAssertions.Specs.ClassWithoutAttribute" + " because we want to test the error message, but found FluentAssertions.Specs.ClassWithAttribute."); } [TestMethod] public void When_asserting_equality_of_a_type_but_the_type_is_null_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type nullType = null; Type someType = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => nullType.Should().Be(someType, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>().WithMessage( "Expected type to be FluentAssertions.Specs.ClassWithAttribute" + " because we want to test the error message, but found <null>."); } [TestMethod] public void When_asserting_equality_of_a_type_with_null_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type someType = typeof (ClassWithAttribute); Type nullType = null; //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => someType.Should().Be(nullType, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>().WithMessage( "Expected type to be <null>" + " because we want to test the error message, but found FluentAssertions.Specs.ClassWithAttribute."); } [TestMethod] public void When_type_is_equal_to_same_type_from_different_assembly_it_fails_with_assembly_qualified_name () { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- #pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec Type typeFromThisAssembly = typeof (ObjectAssertions); #if !WINRT && !WINDOWS_PHONE_APP Type typeFromOtherAssembly = typeof (TypeAssertions).Assembly.GetType("FluentAssertions.Primitives.ObjectAssertions"); #else Type typeFromOtherAssembly = Type.GetType("FluentAssertions.Primitives.ObjectAssertions,FluentAssertions.Core"); #endif #pragma warning restore 436 //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => typeFromThisAssembly.Should().Be(typeFromOtherAssembly, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- const string expectedMessage = "Expected type to be [FluentAssertions.Primitives.ObjectAssertions, FluentAssertions*]" + " because we want to test the error message, but found " + "[FluentAssertions.Primitives.ObjectAssertions, FluentAssertions*]."; act.ShouldThrow<AssertFailedException>().WithMessage(expectedMessage); } [TestMethod] public void When_type_is_equal_to_the_same_type_using_generics_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Be<ClassWithAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_type_is_equal_to_another_type_using_generics_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Be<ClassWithoutAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_type_is_equal_to_another_type_using_generics_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Be<ClassWithoutAttribute>("because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected type to be FluentAssertions.Specs.ClassWithoutAttribute because we want to test " + "the error message, but found FluentAssertions.Specs.ClassWithAttribute."); } #endregion #region NotBe [TestMethod] public void When_type_is_not_equal_to_the_another_type_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); Type otherType = typeof (ClassWithoutAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotBe(otherType); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_type_is_not_equal_to_the_same_type_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); Type sameType = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotBe(sameType); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_type_is_not_equal_to_the_same_type_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); Type sameType = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotBe(sameType, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type not to be [FluentAssertions.Specs.ClassWithAttribute*]" + " because we want to test the error message, but it is."); } [TestMethod] public void When_type_is_not_equal_to_another_type_using_generics_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotBe<ClassWithoutAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotBe<ClassWithAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotBe<ClassWithAttribute>("because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected type not to be [FluentAssertions.Specs.ClassWithAttribute*] because we want to test " + "the error message, but it is."); } #endregion #region BeAssignableTo [TestMethod] public void When_asserting_an_object_is_assignable_its_own_type_it_succeeds() { //----------------------------------------------------------------------------------------------------------- // Arrange / Act / Assert //----------------------------------------------------------------------------------------------------------- typeof (DummyImplementingClass).Should().BeAssignableTo<DummyImplementingClass>(); } [TestMethod] public void When_asserting_an_object_is_assignable_to_its_base_type_it_succeeds() { //----------------------------------------------------------------------------------------------------------- // Arrange / Act / Assert //----------------------------------------------------------------------------------------------------------- typeof (DummyImplementingClass).Should().BeAssignableTo<DummyBaseClass>(); } [TestMethod] public void When_asserting_an_object_is_assignable_to_an_implemented_interface_type_it_succeeds() { //----------------------------------------------------------------------------------------------------------- // Arrange / Act / Assert //----------------------------------------------------------------------------------------------------------- typeof (DummyImplementingClass).Should().BeAssignableTo<IDisposable>(); } [TestMethod] public void When_asserting_an_object_is_assignable_to_an_unrelated_type_it_fails_with_a_a_useful_message() { //----------------------------------------------------------------------------------------------------------- // Arrange //----------------------------------------------------------------------------------------------------------- Type someType = typeof (DummyImplementingClass); //----------------------------------------------------------------------------------------------------------- // Act / Assert //----------------------------------------------------------------------------------------------------------- someType.Invoking( x => x.Should().BeAssignableTo<DateTime>("because we want to test the failure {0}", "message")) .ShouldThrow<AssertFailedException>() .WithMessage(string.Format( "Expected type {0} to be assignable to {1} because we want to test the failure message, but it is not", typeof (DummyImplementingClass), typeof (DateTime))); } #endregion #region BeDerivedFrom [TestMethod] public void When_asserting_a_type_is_derived_from_its_base_class_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(DummyImplementingClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().BeDerivedFrom(typeof(DummyBaseClass)); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_is_derived_from_an_unrelated_class_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(DummyBaseClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().BeDerivedFrom(typeof(ClassWithMembers), "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.DummyBaseClass to be derived from " + "FluentAssertions.Specs.ClassWithMembers because we want to test the error message, but it is not."); } [TestMethod] public void When_asserting_a_type_is_derived_from_an_interface_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatImplementsInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().BeDerivedFrom(typeof(IDummyInterface), "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<ArgumentException>() .WithMessage("Must not be an interface Type.\r\nParameter name: baseType"); } #endregion #region BeDerivedFromOfT [TestMethod] public void When_asserting_a_type_is_DerivedFromOfT_its_base_class_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(DummyImplementingClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().BeDerivedFrom<DummyBaseClass>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region BeDecoratedWith [TestMethod] public void When_type_is_decorated_with_expected_attribute_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type typeWithAttribute = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => typeWithAttribute.Should().BeDecoratedWith<DummyClassAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_type_is_not_decorated_with_expected_attribute_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type typeWithoutAttribute = typeof (ClassWithoutAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => typeWithoutAttribute.Should().BeDecoratedWith<DummyClassAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>(); } [TestMethod] public void When_type_is_not_decorated_with_expected_attribute_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type typeWithoutAttribute = typeof (ClassWithoutAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => typeWithoutAttribute.Should().BeDecoratedWith<DummyClassAttribute>( "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.ClassWithoutAttribute to be decorated with " + "FluentAssertions.Specs.DummyClassAttribute because we want to test the error message, but the attribute " + "was not found."); } [TestMethod] public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type typeWithAttribute = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => typeWithAttribute.Should() .BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Expected") && a.IsEnabled)); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_type_is_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type typeWithAttribute = typeof (ClassWithAttribute); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => typeWithAttribute.Should() .BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Unexpected") && a.IsEnabled)); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.ClassWithAttribute to be decorated with " + "FluentAssertions.Specs.DummyClassAttribute that matches ((a.Name == \"Unexpected\")*a.IsEnabled), " + "but no matching attribute was found."); } [TestMethod] public void When_asserting_a_selection_of_decorated_types_is_decorated_with_an_attribute_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var types = new TypeSelector(new[] { typeof (ClassWithAttribute) }); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => types.Should().BeDecoratedWith<DummyClassAttribute>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_selection_of_non_decorated_types_is_decorated_with_an_attribute_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var types = new TypeSelector(new[] { typeof (ClassWithAttribute), typeof (ClassWithoutAttribute), typeof (OtherClassWithoutAttribute) }); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => types.Should().BeDecoratedWith<DummyClassAttribute>("because we do"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected all types to be decorated with FluentAssertions.Specs.DummyClassAttribute" + " because we do, but the attribute was not found on the following types:\r\n" + "FluentAssertions.Specs.ClassWithoutAttribute\r\n" + "FluentAssertions.Specs.OtherClassWithoutAttribute"); } [TestMethod] public void When_asserting_a_selection_of_types_with_unexpected_attribute_property_it_fails() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var types = new TypeSelector(new[] { typeof (ClassWithAttribute), typeof (ClassWithoutAttribute), typeof (OtherClassWithoutAttribute) }); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => types.Should() .BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Expected") && a.IsEnabled), "because we do"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected all types to be decorated with FluentAssertions.Specs.DummyClassAttribute" + " that matches ((a.Name == \"Expected\")*a.IsEnabled) because we do," + " but no matching attribute was found on the following types:\r\n" + "FluentAssertions.Specs.ClassWithoutAttribute\r\n" + "FluentAssertions.Specs.OtherClassWithoutAttribute"); } #endregion #region Implement [TestMethod] public void When_asserting_a_type_implements_an_interface_which_it_does_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof (ClassThatImplementsInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Implement(typeof (IDummyInterface)); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_then_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof (ClassThatDoesNotImplementInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Implement(typeof (IDummyInterface), "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.ClassThatDoesNotImplementInterface to implement " + "interface FluentAssertions.Specs.IDummyInterface because we want to test the error message, " + "but it does not."); } [TestMethod] public void When_asserting_a_type_implements_a_NonInterface_type_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatDoesNotImplementInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Implement(typeof(DateTime), "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<ArgumentException>() .WithMessage("Must be an interface Type.\r\nParameter name: interfaceType"); } #endregion #region ImplementOfT [TestMethod] public void When_asserting_a_type_implementsOfT_an_interface_which_it_does_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatImplementsInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().Implement<IDummyInterface>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region NotImplement [TestMethod] public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_not_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatDoesNotImplementInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotImplement(typeof(IDummyInterface)); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_implements_an_interface_which_it_does_not_then_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatImplementsInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotImplement(typeof(IDummyInterface), "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.ClassThatImplementsInterface to not implement interface " + "FluentAssertions.Specs.IDummyInterface because we want to test the error message, but it does."); } [TestMethod] public void When_asserting_a_type_does_not_implement_a_NonInterface_type_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatDoesNotImplementInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotImplement(typeof(DateTime), "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<ArgumentException>() .WithMessage("Must be an interface Type.\r\nParameter name: interfaceType"); } #endregion #region NotImplementOfT [TestMethod] public void When_asserting_a_type_does_not_implementOfT_an_interface_which_it_does_not_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassThatDoesNotImplementInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotImplement<IDummyInterface>(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region HaveProperty [TestMethod] public void When_asserting_a_type_has_a_property_which_it_does_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveProperty(typeof(string), "PrivateWriteProtectedReadProperty") .Which.Should() .BeWritable(CSharpAccessModifier.Private) .And.BeReadable(CSharpAccessModifier.Protected); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_has_a_property_which_it_does_not_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithNoMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveProperty(typeof(string), "PublicProperty", "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected String FluentAssertions.Specs.ClassWithNoMembers.PublicProperty to exist because we want to " + "test the error message, but it does not."); } [TestMethod] public void When_asserting_a_type_has_a_property_which_it_has_with_a_different_type_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveProperty(typeof(int), "PrivateWriteProtectedReadProperty", "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected String FluentAssertions.Specs.ClassWithMembers.PrivateWriteProtectedReadProperty to be of type System.Int32 because we want to test the error message, but it is not."); } #endregion #region HavePropertyOfT [TestMethod] public void When_asserting_a_type_has_a_propertyOfT_which_it_does_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveProperty<string>("PrivateWriteProtectedReadProperty") .Which.Should() .BeWritable(CSharpAccessModifier.Private) .And.BeReadable(CSharpAccessModifier.Protected); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region NotHaveProperty [TestMethod] public void When_asserting_a_type_does_not_have_a_property_which_it_does_not_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof (ClassWithoutMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveProperty("Property"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_have_a_property_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof (ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveProperty("PrivateWriteProtectedReadProperty", "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected String FluentAssertions.Specs.ClassWithMembers.PrivateWriteProtectedReadProperty to not exist because we want to " + "test the error message, but it does."); } #endregion #region HaveExplicitProperty [TestMethod] public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof (IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitProperty(interfaceType, "ExplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_and_explicitly_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitProperty(interfaceType, "ImplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ImplicitStringProperty, but it does not."); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_not_implement_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitProperty(interfaceType, "NonExistantProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.NonExistantProperty, but it does not."); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_property_from_an_unimplemented_interface_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IDummyInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitProperty(interfaceType, "NonExistantProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " + "FluentAssertions.Specs.IDummyInterface, but it does not."); } #endregion #region HaveExplicitPropertyOfT [TestMethod] public void When_asserting_a_type_explicitlyOfT_implements_a_property_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitProperty<IExplicitInterface>("ExplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region NotHaveExplicitProperty [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitProperty(interfaceType, "ExplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ExplicitStringProperty, but it does."); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_and_explicitly_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ExplicitImplicitStringProperty, but it does."); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitProperty(interfaceType, "ImplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_not_implement_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitProperty(interfaceType, "NonExistantProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_property_from_an_unimplemented_interface_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IDummyInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitProperty(interfaceType, "NonExistantProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " + "FluentAssertions.Specs.IDummyInterface, but it does not."); } #endregion #region NotHaveExplicitPropertyOfT [TestMethod] public void When_asserting_a_type_does_not_explicitlyOfT_implement_a_property_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitProperty<IExplicitInterface>("ExplicitStringProperty"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ExplicitStringProperty, but it does."); } #endregion #region HaveExplicitMethod [TestMethod] public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitMethod(interfaceType, "ExplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_and_explicitly_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitMethod(interfaceType, "ImplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ImplicitMethod, but it does not."); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_not_implement_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.NonExistantMethod, but it does not."); } [TestMethod] public void When_asserting_a_type_explicitly_implements_a_method_from_an_unimplemented_interface_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IDummyInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitMethod(interfaceType, "NonExistantProperty", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " + "FluentAssertions.Specs.IDummyInterface, but it does not."); } #endregion #region HaveExplicitMethodOfT [TestMethod] public void When_asserting_a_type_explicitly_implementsOfT_a_method_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveExplicitMethod<IExplicitInterface>("ExplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region NotHaveExplicitMethod [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitMethod(interfaceType, "ExplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ExplicitMethod, but it does."); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_and_explicitly_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ExplicitImplicitMethod, but it does."); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitMethod(interfaceType, "ImplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_not_implement_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IExplicitInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_explicitly_implement_a_method_from_an_unimplemented_interface_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); var interfaceType = typeof(IDummyInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " + "FluentAssertions.Specs.IDummyInterface, but it does not."); } #endregion #region NotHaveExplicitMethodOfT [TestMethod] public void When_asserting_a_type_does_not_explicitly_implementOfT_a_method_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassExplicitlyImplementingInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .NotHaveExplicitMethod< IExplicitInterface>("ExplicitMethod", Enumerable.Empty<Type>()); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " + "FluentAssertions.Specs.IExplicitInterface.ExplicitMethod, but it does."); } #endregion #region HaveIndexer [TestMethod] public void When_asserting_a_type_has_an_indexer_which_it_does_then_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveIndexer(typeof(string), new[] { typeof(string) }) .Which.Should() .BeWritable(CSharpAccessModifier.Internal) .And.BeReadable(CSharpAccessModifier.Private); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_has_an_indexer_which_it_does_not_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithNoMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveIndexer(typeof(string), new [] {typeof(int), typeof(Type)}, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected String FluentAssertions.Specs.ClassWithNoMembers[System.Int32, System.Type] to exist because we want to test the error" + " message, but it does not."); } [TestMethod] public void When_asserting_a_type_has_an_indexer_with_different_parameters_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveIndexer(typeof(string), new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected String FluentAssertions.Specs.ClassWithMembers[System.Int32, System.Type] to exist because we want to test the error" + " message, but it does not."); } #endregion #region NotHaveIndexer [TestMethod] public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_not_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithoutMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveIndexer(new [] {typeof(string)}); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveIndexer(new [] {typeof(string)}, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected indexer FluentAssertions.Specs.ClassWithMembers[System.String] to not exist because we want to " + "test the error message, but it does."); } #endregion #region HaveConstructor [TestMethod] public void When_asserting_a_type_has_a_constructor_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveConstructor(new Type[] { typeof(string) }) .Which.Should() .HaveAccessModifier(CSharpAccessModifier.Private); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_has_a_constructor_which_it_does_not_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithNoMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveConstructor(new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected constructor FluentAssertions.Specs.ClassWithNoMembers(System.Int32, System.Type) to exist because " + "we want to test the error message, but it does not."); } #endregion #region HaveDefaultConstructor [TestMethod] public void When_asserting_a_type_has_a_default_constructor_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveDefaultConstructor() .Which.Should() .HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithNoMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveDefaultConstructor("because the compiler generates one even if not explicitly defined.") .Which.Should() .HaveAccessModifier(CSharpAccessModifier.Public); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } #endregion #region HaveMethod [TestMethod] public void When_asserting_a_type_has_a_method_which_it_does_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should() .HaveMethod("VoidMethod", new Type[] { }) .Which.Should() .HaveAccessModifier(CSharpAccessModifier.Private) .And.ReturnVoid(); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_has_a_method_which_it_does_not_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithNoMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveMethod("NonExistantMethod", new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected method FluentAssertions.Specs.ClassWithNoMembers.NonExistantMethod(System.Int32, System.Type) to exist " + "because we want to test the error message, but it does not."); } [TestMethod] public void When_asserting_a_type_has_a_method_with_different_parameter_types_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveMethod("VoidMethod", new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected method FluentAssertions.Specs.ClassWithMembers.VoidMethod(System.Int32, System.Type) to exist " + "because we want to test the error message, but it does not."); } #endregion #region NotHaveMethod [TestMethod] public void When_asserting_a_type_does_not_have_a_method_which_it_does_not_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithoutMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveMethod("NonExistantMethod", new Type[] {}); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_have_a_method_which_it_has_with_different_parameter_types_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveMethod("VoidMethod", new [] { typeof(int) }); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_type_does_not_have_that_method_which_it_does_it_fails_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- var type = typeof(ClassWithMembers); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().NotHaveMethod("VoidMethod", new Type[] {}, "because we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage( "Expected method Void FluentAssertions.Specs.ClassWithMembers.VoidMethod() to not exist because we want to " + "test the error message, but it does."); } #endregion #region HaveAccessModifier [TestMethod] public void When_asserting_a_public_type_is_public_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(IPublicInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Public); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_public_member_is_not_public_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(IPublicInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type .Should() .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type IPublicInterface to be Internal because we want to test the error message, but it " + "is Public."); } [TestMethod] public void When_asserting_an_internal_type_is_internal_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(InternalClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_an_internal_type_is_not_internal_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(InternalClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" + " error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type InternalClass to be ProtectedInternal because we want to test the error message, " + "but it is Internal."); } [TestMethod] public void When_asserting_a_nested_private_type_is_private_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- #if !WINRT && !WINDOWS_PHONE_APP Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance); #else Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "PrivateClass").AsType(); #endif //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Private); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_nested_private_type_is_not_private_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- #if !WINRT && !WINDOWS_PHONE_APP Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance); #else Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "PrivateClass").AsType(); #endif //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type PrivateClass to be Protected because we want to test the error message, but it " + "is Private."); } [TestMethod] public void When_asserting_a_nested_protected_type_is_protected_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- #if !WINRT && !WINDOWS_PHONE_APP Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance); #else Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "ProtectedEnum").AsType(); #endif //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Protected); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_nested_protected_type_is_not_protected_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- #if !WINRT && !WINDOWS_PHONE_APP Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance); #else Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "ProtectedEnum").AsType(); #endif //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Public); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type ProtectedEnum to be Public, but it is Protected."); } [TestMethod] public void When_asserting_a_nested_public_type_is_public_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(Nested.IPublicInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Public); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_nested_public_member_is_not_public_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(Nested.IPublicInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type .Should() .HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type IPublicInterface to be Internal because we want to test the error message, " + "but it is Public."); } [TestMethod] public void When_asserting_a_nested_internal_type_is_internal_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(Nested.InternalClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Internal); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_nested_internal_type_is_not_internal_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(Nested.InternalClass); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" + " error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type InternalClass to be ProtectedInternal because we want to test the error message, " + "but it is Internal."); } [TestMethod] public void When_asserting_a_nested_protected_internal_member_is_protected_internal_it_succeeds() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(Nested.IProtectedInternalInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldNotThrow(); } [TestMethod] public void When_asserting_a_nested_protected_internal_member_is_not_protected_internal_it_throws_with_a_useful_message() { //------------------------------------------------------------------------------------------------------------------- // Arrange //------------------------------------------------------------------------------------------------------------------- Type type = typeof(Nested.IProtectedInternalInterface); //------------------------------------------------------------------------------------------------------------------- // Act //------------------------------------------------------------------------------------------------------------------- Action act = () => type.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message"); //------------------------------------------------------------------------------------------------------------------- // Assert //------------------------------------------------------------------------------------------------------------------- act.ShouldThrow<AssertFailedException>() .WithMessage("Expected type IProtectedInternalInterface to be Private because we want to test the error " + "message, but it is ProtectedInternal."); } #endregion } #region Internal classes used in unit tests [DummyClass("Expected", true)] public class ClassWithAttribute { } public class ClassWithoutAttribute { } public class OtherClassWithoutAttribute { } [AttributeUsage(AttributeTargets.Class)] public class DummyClassAttribute : Attribute { public string Name { get; set; } public bool IsEnabled { get; set; } public DummyClassAttribute(string name, bool isEnabled) { Name = name; IsEnabled = isEnabled; } } public interface IDummyInterface { } public class ClassThatImplementsInterface : IDummyInterface { } public class ClassThatDoesNotImplementInterface { } public class ClassWithMembers { protected internal ClassWithMembers() { } private ClassWithMembers(String overload) { } protected string PrivateWriteProtectedReadProperty { get { return null; } private set { } } internal string this[string str] { private get { return str; } set { } } protected internal string this[int i] { get { return i.ToString(); } private set { } } private void VoidMethod() { } private void VoidMethod(string overload) { } } public class ClassExplicitlyImplementingInterface : IExplicitInterface { public string ImplicitStringProperty { get { return null; } private set { } } string IExplicitInterface.ExplicitStringProperty { set { } } public string ExplicitImplicitStringProperty { get; set; } string IExplicitInterface.ExplicitImplicitStringProperty { get; set; } public void ImplicitMethod() { } public void ImplicitMethod(string overload) { } void IExplicitInterface.ExplicitMethod() { } void IExplicitInterface.ExplicitMethod(string overload) { } public void ExplicitImplicitMethod() { } public void ExplicitImplicitMethod(string overload) { } void IExplicitInterface.ExplicitImplicitMethod() { } void IExplicitInterface.ExplicitImplicitMethod(string overload) { } } public interface IExplicitInterface { string ImplicitStringProperty { get; } string ExplicitStringProperty { set; } string ExplicitImplicitStringProperty { get; set; } void ImplicitMethod(); void ImplicitMethod(string overload); void ExplicitMethod(); void ExplicitMethod(string overload); void ExplicitImplicitMethod(); void ExplicitImplicitMethod(string overload); } public class ClassWithoutMembers { } public interface IPublicInterface { } internal class InternalClass { } class Nested { class PrivateClass { } protected enum ProtectedEnum { } public interface IPublicInterface { } internal class InternalClass { } protected internal interface IProtectedInternalInterface { } } #endregion } namespace FluentAssertions.Primitives { #pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec /// <summary> /// A class that intentionally has the exact same name and namespace as the ObjectAssertions from the FluentAssertions /// assembly. This class is used to test the behavior of comparisons on such types. /// </summary> internal class ObjectAssertions { } #pragma warning restore 436 }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Localisation; using osu.Game.Localisation; namespace osu.Game.Input.Bindings { public class GlobalActionContainer : DatabasedKeyBindingContainer<GlobalAction>, IHandleGlobalKeyboardInput { private readonly Drawable handler; private InputManager parentInputManager; public GlobalActionContainer(OsuGameBase game) : base(matchingMode: KeyCombinationMatchingMode.Modifiers) { if (game is IKeyBindingHandler<GlobalAction>) handler = game; } protected override void LoadComplete() { base.LoadComplete(); parentInputManager = GetContainingInputManager(); } public override IEnumerable<IKeyBinding> DefaultKeyBindings => GlobalKeyBindings .Concat(EditorKeyBindings) .Concat(InGameKeyBindings) .Concat(SongSelectKeyBindings) .Concat(AudioControlKeyBindings); public IEnumerable<KeyBinding> GlobalKeyBindings => new[] { new KeyBinding(InputKey.F6, GlobalAction.ToggleNowPlaying), new KeyBinding(InputKey.F8, GlobalAction.ToggleChat), new KeyBinding(InputKey.F9, GlobalAction.ToggleSocial), new KeyBinding(InputKey.F10, GlobalAction.ToggleGameplayMouseButtons), new KeyBinding(InputKey.F12, GlobalAction.TakeScreenshot), new KeyBinding(new[] { InputKey.Control, InputKey.Alt, InputKey.R }, GlobalAction.ResetInputSettings), new KeyBinding(new[] { InputKey.Control, InputKey.T }, GlobalAction.ToggleToolbar), new KeyBinding(new[] { InputKey.Control, InputKey.O }, GlobalAction.ToggleSettings), new KeyBinding(new[] { InputKey.Control, InputKey.D }, GlobalAction.ToggleBeatmapListing), new KeyBinding(new[] { InputKey.Control, InputKey.N }, GlobalAction.ToggleNotifications), new KeyBinding(new[] { InputKey.Control, InputKey.Shift, InputKey.S }, GlobalAction.ToggleSkinEditor), new KeyBinding(InputKey.Escape, GlobalAction.Back), new KeyBinding(InputKey.ExtraMouseButton1, GlobalAction.Back), new KeyBinding(new[] { InputKey.Alt, InputKey.Home }, GlobalAction.Home), new KeyBinding(InputKey.Up, GlobalAction.SelectPrevious), new KeyBinding(InputKey.Down, GlobalAction.SelectNext), new KeyBinding(InputKey.Space, GlobalAction.Select), new KeyBinding(InputKey.Enter, GlobalAction.Select), new KeyBinding(InputKey.KeypadEnter, GlobalAction.Select), new KeyBinding(new[] { InputKey.Control, InputKey.Shift, InputKey.R }, GlobalAction.RandomSkin), }; public IEnumerable<KeyBinding> EditorKeyBindings => new[] { new KeyBinding(new[] { InputKey.F1 }, GlobalAction.EditorComposeMode), new KeyBinding(new[] { InputKey.F2 }, GlobalAction.EditorDesignMode), new KeyBinding(new[] { InputKey.F3 }, GlobalAction.EditorTimingMode), new KeyBinding(new[] { InputKey.F4 }, GlobalAction.EditorSetupMode), new KeyBinding(new[] { InputKey.Control, InputKey.Shift, InputKey.A }, GlobalAction.EditorVerifyMode), new KeyBinding(new[] { InputKey.J }, GlobalAction.EditorNudgeLeft), new KeyBinding(new[] { InputKey.K }, GlobalAction.EditorNudgeRight), new KeyBinding(new[] { InputKey.G }, GlobalAction.EditorCycleGridDisplayMode), new KeyBinding(new[] { InputKey.F5 }, GlobalAction.EditorTestGameplay), new KeyBinding(new[] { InputKey.Control, InputKey.H }, GlobalAction.EditorFlipHorizontally), new KeyBinding(new[] { InputKey.Control, InputKey.J }, GlobalAction.EditorFlipVertically), }; public IEnumerable<KeyBinding> InGameKeyBindings => new[] { new KeyBinding(InputKey.Space, GlobalAction.SkipCutscene), new KeyBinding(InputKey.ExtraMouseButton2, GlobalAction.SkipCutscene), new KeyBinding(InputKey.Tilde, GlobalAction.QuickRetry), new KeyBinding(new[] { InputKey.Control, InputKey.Tilde }, GlobalAction.QuickExit), new KeyBinding(new[] { InputKey.F3 }, GlobalAction.DecreaseScrollSpeed), new KeyBinding(new[] { InputKey.F4 }, GlobalAction.IncreaseScrollSpeed), new KeyBinding(new[] { InputKey.Shift, InputKey.Tab }, GlobalAction.ToggleInGameInterface), new KeyBinding(InputKey.MouseMiddle, GlobalAction.PauseGameplay), new KeyBinding(InputKey.Space, GlobalAction.TogglePauseReplay), new KeyBinding(InputKey.Left, GlobalAction.SeekReplayBackward), new KeyBinding(InputKey.Right, GlobalAction.SeekReplayForward), new KeyBinding(InputKey.Control, GlobalAction.HoldForHUD), new KeyBinding(InputKey.Tab, GlobalAction.ToggleChatFocus), }; public IEnumerable<KeyBinding> SongSelectKeyBindings => new[] { new KeyBinding(InputKey.F1, GlobalAction.ToggleModSelection), new KeyBinding(InputKey.F2, GlobalAction.SelectNextRandom), new KeyBinding(new[] { InputKey.Shift, InputKey.F2 }, GlobalAction.SelectPreviousRandom), new KeyBinding(InputKey.F3, GlobalAction.ToggleBeatmapOptions) }; public IEnumerable<KeyBinding> AudioControlKeyBindings => new[] { new KeyBinding(new[] { InputKey.Alt, InputKey.Up }, GlobalAction.IncreaseVolume), new KeyBinding(new[] { InputKey.Alt, InputKey.Down }, GlobalAction.DecreaseVolume), new KeyBinding(new[] { InputKey.Alt, InputKey.Left }, GlobalAction.PreviousVolumeMeter), new KeyBinding(new[] { InputKey.Alt, InputKey.Right }, GlobalAction.NextVolumeMeter), new KeyBinding(new[] { InputKey.Control, InputKey.F4 }, GlobalAction.ToggleMute), new KeyBinding(InputKey.TrackPrevious, GlobalAction.MusicPrev), new KeyBinding(InputKey.F1, GlobalAction.MusicPrev), new KeyBinding(InputKey.TrackNext, GlobalAction.MusicNext), new KeyBinding(InputKey.F5, GlobalAction.MusicNext), new KeyBinding(InputKey.PlayPause, GlobalAction.MusicPlay), new KeyBinding(InputKey.F3, GlobalAction.MusicPlay) }; protected override IEnumerable<Drawable> KeyBindingInputQueue { get { // To ensure the global actions are handled with priority, this GlobalActionContainer is actually placed after game content. // It does not contain children as expected, so we need to forward the NonPositionalInputQueue from the parent input manager to correctly // allow the whole game to handle these actions. // An eventual solution to this hack is to create localised action containers for individual components like SongSelect, but this will take some rearranging. var inputQueue = parentInputManager?.NonPositionalInputQueue ?? base.KeyBindingInputQueue; return handler != null ? inputQueue.Prepend(handler) : inputQueue; } } } public enum GlobalAction { [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleChat))] ToggleChat, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleSocial))] ToggleSocial, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ResetInputSettings))] ResetInputSettings, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleToolbar))] ToggleToolbar, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleSettings))] ToggleSettings, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleBeatmapListing))] ToggleBeatmapListing, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.IncreaseVolume))] IncreaseVolume, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.DecreaseVolume))] DecreaseVolume, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleMute))] ToggleMute, // In-Game Keybindings [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SkipCutscene))] SkipCutscene, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.QuickRetry))] QuickRetry, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.TakeScreenshot))] TakeScreenshot, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleGameplayMouseButtons))] ToggleGameplayMouseButtons, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.Back))] Back, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.IncreaseScrollSpeed))] IncreaseScrollSpeed, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.DecreaseScrollSpeed))] DecreaseScrollSpeed, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.Select))] Select, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.QuickExit))] QuickExit, // Game-wide beatmap music controller keybindings [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.MusicNext))] MusicNext, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.MusicPrev))] MusicPrev, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.MusicPlay))] MusicPlay, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleNowPlaying))] ToggleNowPlaying, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SelectPrevious))] SelectPrevious, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SelectNext))] SelectNext, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.Home))] Home, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleNotifications))] ToggleNotifications, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.PauseGameplay))] PauseGameplay, // Editor [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorSetupMode))] EditorSetupMode, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorComposeMode))] EditorComposeMode, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorDesignMode))] EditorDesignMode, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorTimingMode))] EditorTimingMode, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.HoldForHUD))] HoldForHUD, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.RandomSkin))] RandomSkin, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.TogglePauseReplay))] TogglePauseReplay, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleInGameInterface))] ToggleInGameInterface, // Song select keybindings [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleModSelection))] ToggleModSelection, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SelectNextRandom))] SelectNextRandom, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SelectPreviousRandom))] SelectPreviousRandom, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleBeatmapOptions))] ToggleBeatmapOptions, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorVerifyMode))] EditorVerifyMode, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorNudgeLeft))] EditorNudgeLeft, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorNudgeRight))] EditorNudgeRight, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleSkinEditor))] ToggleSkinEditor, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.PreviousVolumeMeter))] PreviousVolumeMeter, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.NextVolumeMeter))] NextVolumeMeter, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SeekReplayForward))] SeekReplayForward, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.SeekReplayBackward))] SeekReplayBackward, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.ToggleChatFocus))] ToggleChatFocus, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorCycleGridDisplayMode))] EditorCycleGridDisplayMode, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorTestGameplay))] EditorTestGameplay, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorFlipHorizontally))] EditorFlipHorizontally, [LocalisableDescription(typeof(GlobalActionKeyBindingStrings), nameof(GlobalActionKeyBindingStrings.EditorFlipVertically))] EditorFlipVertically, } }
using System; using System.Reflection; using IBatisNet.Common.Test.Domain; using IBatisNet.Common.Utilities.Objects; using IBatisNet.Common.Utilities.Objects.Members; using NUnit.Framework; namespace IBatisNet.Common.Test.NUnit.CommonTests.Utilities { [TestFixture] public class PropertyAccessorPerformance { #region SetUp & TearDown /// <summary> /// SetUp /// </summary> [SetUp] public void SetUp() { } /// <summary> /// TearDown /// </summary> [TearDown] public void Dispose() { } #endregion /// <summary> /// Test integer property access performance /// </summary> [Test] public void TestGetIntegerPerformance() { const int TEST_ITERATIONS = 1000000; Property prop = new Property(); int test = -1; Timer timer = new Timer(); #region Direct access (fastest) GC.Collect(); GC.WaitForPendingFinalizers(); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { test = -1; test = prop.Int; Assert.AreEqual(int.MinValue, test); } timer.Stop(); double directAccessDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); #endregion #region IL Property accessor GC.Collect(); GC.WaitForPendingFinalizers(); IGetAccessorFactory factory = new GetAccessorFactory(true); IGetAccessor propertyAccessor = factory.CreateGetAccessor(typeof(Property), "Int"); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { test = -1; test = (int)propertyAccessor.Get(prop); Assert.AreEqual(int.MinValue, test); } timer.Stop(); double propertyAccessorDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double propertyAccessorRatio = propertyAccessorDuration / directAccessDuration; #endregion #region IBatisNet.Common.Utilities.Object.ReflectionInfo GC.Collect(); GC.WaitForPendingFinalizers(); ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(prop.GetType()); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { test = -1; PropertyInfo propertyInfo = (PropertyInfo)reflectionInfo.GetGetter("Int"); test = (int)propertyInfo.GetValue(prop, null); Assert.AreEqual(int.MinValue, test); } timer.Stop(); double reflectionInfoDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double reflectionInfoRatio = (float)reflectionInfoDuration / directAccessDuration; #endregion #region Reflection GC.Collect(); GC.WaitForPendingFinalizers(); Type type = prop.GetType(); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { test = -1; PropertyInfo propertyInfo = type.GetProperty("Int", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); test = (int)propertyInfo.GetValue(prop, null); Assert.AreEqual(int.MinValue, test); } timer.Stop(); double reflectionDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double reflectionRatio = reflectionDuration / directAccessDuration; #endregion #region ReflectionInvokeMember (slowest) GC.Collect(); GC.WaitForPendingFinalizers(); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { test = -1; test = (int)type.InvokeMember("Int", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance, null, prop, null); Assert.AreEqual(int.MinValue, test); } timer.Stop(); double reflectionInvokeMemberDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double reflectionInvokeMemberRatio = reflectionInvokeMemberDuration / directAccessDuration; #endregion // Print results Console.WriteLine("{0} property gets on integer...", TEST_ITERATIONS); Console.WriteLine("Direct access: \t\t{0} ", directAccessDuration.ToString("F3")); Console.WriteLine("IMemberAccessor: \t\t{0} Ratio: {1}", propertyAccessorDuration.ToString("F3"), propertyAccessorRatio.ToString("F3")); Console.WriteLine("IBatisNet ReflectionInfo: \t{0} Ratio: {1}", reflectionInfoDuration.ToString("F3"), reflectionInfoRatio.ToString("F3")); Console.WriteLine("ReflectionInvokeMember: \t{0} Ratio: {1}", reflectionInvokeMemberDuration.ToString("F3"), reflectionInvokeMemberRatio.ToString("F3")); Console.WriteLine("Reflection: \t\t\t{0} Ratio: {1}", reflectionDuration.ToString("F3"), reflectionRatio.ToString("F3")); } /// <summary> /// Test the performance of getting an integer property. /// </summary> [Test] public void TestSetIntegerPerformance() { const int TEST_ITERATIONS = 1000000; Property prop = new Property(); int value = 123; Timer timer = new Timer(); #region Direct access (fastest) GC.Collect(); GC.WaitForPendingFinalizers(); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { prop.Int = value; } timer.Stop(); double directAccessDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); #endregion #region Property accessor GC.Collect(); GC.WaitForPendingFinalizers(); ISetAccessorFactory factory = new SetAccessorFactory(true); ISetAccessor propertyAccessor = factory.CreateSetAccessor(typeof(Property), "Int"); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { propertyAccessor.Set(prop, value); } timer.Stop(); double propertyAccessorDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double propertyAccessorRatio = propertyAccessorDuration / directAccessDuration; #endregion #region IBatisNet.Common.Utilities.Object.ReflectionInfo GC.Collect(); GC.WaitForPendingFinalizers(); Type type = prop.GetType(); ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(type); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { PropertyInfo propertyInfo = (PropertyInfo)reflectionInfo.GetSetter("Int"); propertyInfo.SetValue(prop, value, null); } timer.Stop(); double reflectionInfoDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double reflectionInfoRatio = reflectionInfoDuration / directAccessDuration; #endregion #region Reflection GC.Collect(); GC.WaitForPendingFinalizers(); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { PropertyInfo propertyInfo = type.GetProperty("Int", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); propertyInfo.SetValue(prop, value, null); } timer.Stop(); double reflectionDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double reflectionRatio = reflectionDuration / directAccessDuration; #endregion #region ReflectionInvokeMember (slowest) GC.Collect(); GC.WaitForPendingFinalizers(); timer.Start(); for (int i = 0; i < TEST_ITERATIONS; i++) { type.InvokeMember("Int", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance, null, prop, new object[] { value }); } timer.Stop(); double reflectionInvokeMemberDuration = 1000000 * (timer.Duration / (double)TEST_ITERATIONS); double reflectionInvokeMemberRatio = reflectionInvokeMemberDuration / directAccessDuration; #endregion // Print results Console.WriteLine("{0} property sets on integer...", TEST_ITERATIONS); Console.WriteLine("Direct access: \t\t{0} ", directAccessDuration.ToString("F3")); Console.WriteLine("IMemberAccessor: \t\t{0} Ratio: {1}", propertyAccessorDuration.ToString("F3"), propertyAccessorRatio.ToString("F3")); Console.WriteLine("IBatisNet ReflectionInfo: \t{0} Ratio: {1}", reflectionInfoDuration.ToString("F3"), reflectionInfoRatio.ToString("F3")); Console.WriteLine("ReflectionInvokeMember: \t{0} Ratio: {1}", reflectionInvokeMemberDuration.ToString("F3"), reflectionInvokeMemberRatio.ToString("F3")); Console.WriteLine("Reflection: \t\t\t{0} Ratio: {1}", reflectionDuration.ToString("F3"), reflectionRatio.ToString("F3")); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D07_Country_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="D07_Country_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D06_Country"/> collection. /// </remarks> [Serializable] public partial class D07_Country_ReChild : BusinessBase<D07_Country_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Country_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name"); /// <summary> /// Gets or sets the Regions Child Name. /// </summary> /// <value>The Regions Child Name.</value> public string Country_Child_Name { get { return GetProperty(Country_Child_NameProperty); } set { SetProperty(Country_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D07_Country_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="D07_Country_ReChild"/> object.</returns> internal static D07_Country_ReChild NewD07_Country_ReChild() { return DataPortal.CreateChild<D07_Country_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="D07_Country_ReChild"/> object, based on given parameters. /// </summary> /// <param name="country_ID2">The Country_ID2 parameter of the D07_Country_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="D07_Country_ReChild"/> object.</returns> internal static D07_Country_ReChild GetD07_Country_ReChild(int country_ID2) { return DataPortal.FetchChild<D07_Country_ReChild>(country_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D07_Country_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D07_Country_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D07_Country_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D07_Country_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="country_ID2">The Country ID2.</param> protected void Child_Fetch(int country_ID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetD07_Country_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID2", country_ID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, country_ID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="D07_Country_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D07_Country_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D06_Country parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddD07_Country_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID2", parent.Country_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="D07_Country_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D06_Country parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateD07_Country_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID2", parent.Country_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="D07_Country_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D06_Country parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteD07_Country_ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Country_ID2", parent.Country_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); 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 } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using Document = Lucene.Net.Documents.Document; using Directory = Lucene.Net.Store.Directory; using FieldSelector = Lucene.Net.Documents.FieldSelector; using FieldSelectorResult = Lucene.Net.Documents.FieldSelectorResult; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; namespace Lucene.Net.Index { /// <summary> The SegmentMerger class combines two or more Segments, represented by an IndexReader ({@link #add}, /// into a single Segment. After adding the appropriate readers, call the merge method to combine the /// segments. /// <P> /// If the compoundFile flag is set, then the segments will be merged into a compound file. /// /// /// </summary> /// <seealso cref="merge"> /// </seealso> /// <seealso cref="add"> /// </seealso> public sealed class SegmentMerger { private void InitBlock() { termIndexInterval = IndexWriter.DEFAULT_TERM_INDEX_INTERVAL; } /// <summary>norms header placeholder </summary> internal static readonly byte[] NORMS_HEADER = new byte[]{(byte) 'N', (byte) 'R', (byte) 'M', unchecked((byte) -1)}; private Directory directory; private System.String segment; private int termIndexInterval; private System.Collections.ArrayList readers = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); private FieldInfos fieldInfos; private int mergedDocs; private CheckAbort checkAbort; // Whether we should merge doc stores (stored fields and // vectors files). When all segments we are merging // already share the same doc store files, we don't need // to merge the doc stores. private bool mergeDocStores; /// <summary>Maximum number of contiguous documents to bulk-copy /// when merging stored fields /// </summary> private const int MAX_RAW_MERGE_DOCS = 4192; /// <summary>This ctor used only by test code. /// /// </summary> /// <param name="dir">The Directory to merge the other segments into /// </param> /// <param name="name">The name of the new segment /// </param> public /*internal*/ SegmentMerger(Directory dir, System.String name) { InitBlock(); directory = dir; segment = name; } internal SegmentMerger(IndexWriter writer, System.String name, MergePolicy.OneMerge merge) { InitBlock(); directory = writer.GetDirectory(); segment = name; if (merge != null) checkAbort = new CheckAbort(merge, directory); termIndexInterval = writer.GetTermIndexInterval(); } internal bool HasProx() { return fieldInfos.HasProx(); } /// <summary> Add an IndexReader to the collection of readers that are to be merged</summary> /// <param name="reader"> /// </param> public /*internal*/ void Add(IndexReader reader) { readers.Add(reader); } /// <summary> </summary> /// <param name="i">The index of the reader to return /// </param> /// <returns> The ith reader to be merged /// </returns> internal IndexReader SegmentReader(int i) { return (IndexReader) readers[i]; } /// <summary> Merges the readers specified by the {@link #add} method into the directory passed to the constructor</summary> /// <returns> The number of documents that were merged /// </returns> /// <throws> CorruptIndexException if the index is corrupt </throws> /// <throws> IOException if there is a low-level IO error </throws> public /*internal*/ int Merge() { return Merge(true); } /// <summary> Merges the readers specified by the {@link #add} method /// into the directory passed to the constructor. /// </summary> /// <param name="mergeDocStores">if false, we will not merge the /// stored fields nor vectors files /// </param> /// <returns> The number of documents that were merged /// </returns> /// <throws> CorruptIndexException if the index is corrupt </throws> /// <throws> IOException if there is a low-level IO error </throws> internal int Merge(bool mergeDocStores) { this.mergeDocStores = mergeDocStores; // NOTE: it's important to add calls to // checkAbort.work(...) if you make any changes to this // method that will spend alot of time. The frequency // of this check impacts how long // IndexWriter.close(false) takes to actually stop the // threads. mergedDocs = MergeFields(); MergeTerms(); MergeNorms(); if (mergeDocStores && fieldInfos.HasVectors()) MergeVectors(); return mergedDocs; } /// <summary> close all IndexReaders that have been added. /// Should not be called before merge(). /// </summary> /// <throws> IOException </throws> public /*internal*/ void CloseReaders() { for (int i = 0; i < readers.Count; i++) { // close readers IndexReader reader = (IndexReader) readers[i]; reader.Close(); } } public /*internal*/ System.Collections.ArrayList CreateCompoundFile(System.String fileName) { CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, fileName, checkAbort); System.Collections.ArrayList files = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(IndexFileNames.COMPOUND_EXTENSIONS.Length + 1)); // Basic files for (int i = 0; i < IndexFileNames.COMPOUND_EXTENSIONS.Length; i++) { System.String ext = IndexFileNames.COMPOUND_EXTENSIONS[i]; if (ext.Equals(IndexFileNames.PROX_EXTENSION) && !HasProx()) continue; if (mergeDocStores || (!ext.Equals(IndexFileNames.FIELDS_EXTENSION) && !ext.Equals(IndexFileNames.FIELDS_INDEX_EXTENSION))) files.Add(segment + "." + ext); } // Fieldable norm files for (int i = 0; i < fieldInfos.Size(); i++) { FieldInfo fi = fieldInfos.FieldInfo(i); if (fi.isIndexed && !fi.omitNorms) { files.Add(segment + "." + IndexFileNames.NORMS_EXTENSION); break; } } // Vector files if (fieldInfos.HasVectors() && mergeDocStores) { for (int i = 0; i < IndexFileNames.VECTOR_EXTENSIONS.Length; i++) { files.Add(segment + "." + IndexFileNames.VECTOR_EXTENSIONS[i]); } } // Now merge all added files System.Collections.IEnumerator it = files.GetEnumerator(); while (it.MoveNext()) { cfsWriter.AddFile((System.String) it.Current); } // Perform the merge cfsWriter.Close(); return files; } private void AddIndexed(IndexReader reader, FieldInfos fieldInfos, ICollection<string> names, bool storeTermVectors, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool storePayloads, bool omitTf) { IEnumerator<string> i = names.GetEnumerator(); while (i.MoveNext()) { string field = i.Current; fieldInfos.Add(field, true, storeTermVectors, storePositionWithTermVector, storeOffsetWithTermVector, !reader.HasNorms(field), storePayloads, omitTf); } } private SegmentReader[] matchingSegmentReaders; private int[] rawDocLengths; private int[] rawDocLengths2; private void SetMatchingSegmentReaders() { // if the i'th reader is a SegmentReader and has // identical fieldName->number mapping the this // array will be non-null at position i: matchingSegmentReaders = new SegmentReader[readers.Count]; // if this reader is a SegmentReader, and all of its // fieldName->number mappings match the "merged" // FieldInfos, then we can do a bulk copy of the // stored fields for (int i = 0; i < readers.Count; i++) { IndexReader reader = (IndexReader)readers[i]; if (reader is SegmentReader) { SegmentReader segmentReader = (SegmentReader)reader; bool same = true; FieldInfos segmentFieldInfos = segmentReader.GetFieldInfos(); for (int j = 0; same && j < segmentFieldInfos.Size(); j++) same = fieldInfos.FieldName(j).Equals(segmentFieldInfos.FieldName(j)); if (same) matchingSegmentReaders[i] = segmentReader; } } // used for bulk-reading raw bytes for stored fields rawDocLengths = new int[MAX_RAW_MERGE_DOCS]; rawDocLengths2 = new int[MAX_RAW_MERGE_DOCS]; } /// <summary> </summary> /// <returns> The number of documents in all of the readers /// </returns> /// <throws> CorruptIndexException if the index is corrupt </throws> /// <throws> IOException if there is a low-level IO error </throws> private int MergeFields() { if (!mergeDocStores) { // When we are not merging by doc stores, that means // all segments were written as part of a single // autoCommit=false IndexWriter session, so their field // name -> number mapping are the same. So, we start // with the fieldInfos of the last segment in this // case, to keep that numbering. SegmentReader sr = (SegmentReader) readers[readers.Count - 1]; fieldInfos = (FieldInfos) sr.fieldInfos.Clone(); } else { fieldInfos = new FieldInfos(); // merge field names } for (int i = 0; i < readers.Count; i++) { IndexReader reader = (IndexReader) readers[i]; if (reader is SegmentReader) { SegmentReader segmentReader = (SegmentReader) reader; for (int j = 0; j < segmentReader.GetFieldInfos().Size(); j++) { FieldInfo fi = segmentReader.GetFieldInfos().FieldInfo(j); fieldInfos.Add(fi.name, fi.isIndexed, fi.storeTermVector, fi.storePositionWithTermVector, fi.storeOffsetWithTermVector, !reader.HasNorms(fi.name), fi.storePayloads, fi.omitTf); } } else { AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET), true, true, true, false, false); AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_POSITION), true, true, false, false, false); AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET), true, false, true, false, false); AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.TERMVECTOR), true, false, false, false, false); AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.OMIT_TF), false, false, false, false, true); AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.STORES_PAYLOADS), false, false, false, true, false); AddIndexed(reader, fieldInfos, reader.GetFieldNames(IndexReader.FieldOption.INDEXED), false, false, false, false, false); fieldInfos.Add(reader.GetFieldNames(IndexReader.FieldOption.UNINDEXED), false); } } fieldInfos.Write(directory, segment + ".fnm"); int docCount = 0; SetMatchingSegmentReaders(); if (mergeDocStores) { // for merging we don't want to compress/uncompress the data, so to tell the FieldsReader that we're // in merge mode, we use this FieldSelector FieldSelector fieldSelectorMerge = new AnonymousClassFieldSelector(this); // merge field values FieldsWriter fieldsWriter = new FieldsWriter(directory, segment, fieldInfos); try { for (int i = 0; i < readers.Count; i++) { IndexReader reader = (IndexReader)readers[i]; SegmentReader matchingSegmentReader = matchingSegmentReaders[i]; FieldsReader matchingFieldsReader; bool hasMatchingReader; if (matchingSegmentReader != null) { FieldsReader fieldsReader = matchingSegmentReader.GetFieldsReader(); if (fieldsReader != null && !fieldsReader.CanReadRawDocs()) { matchingFieldsReader = null; hasMatchingReader = false; } else { matchingFieldsReader = fieldsReader; hasMatchingReader = true; } } else { hasMatchingReader = false; matchingFieldsReader = null; } int maxDoc = reader.MaxDoc(); bool hasDeletions = reader.HasDeletions(); for (int j = 0; j < maxDoc; ) { if (!hasDeletions || !reader.IsDeleted(j)) { // skip deleted docs if (hasMatchingReader) { // We can optimize this case (doing a bulk // byte copy) since the field numbers are // identical int start = j; int numDocs = 0; do { j++; numDocs++; if (j >= maxDoc) break; if (hasDeletions && matchingSegmentReader.IsDeleted(j)) { j++; break; } } while (numDocs < MAX_RAW_MERGE_DOCS); IndexInput stream = matchingFieldsReader.RawDocs(rawDocLengths, start, numDocs); fieldsWriter.AddRawDocuments(stream, rawDocLengths, numDocs); docCount += numDocs; if (checkAbort != null) checkAbort.Work(300 * numDocs); } else { // NOTE: it's very important to first assign // to doc then pass it to // termVectorsWriter.addAllDocVectors; see // LUCENE-1282 Document doc = reader.Document(j, fieldSelectorMerge); fieldsWriter.AddDocument(doc); j++; docCount++; if (checkAbort != null) checkAbort.Work(300); } } else j++; } } } finally { fieldsWriter.Close(); } long fdxFileLength = directory.FileLength(segment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); // {{dougsale-2.4.0} // this shouldn't be a problem for us - if it is, // then it's not a JRE bug... //if (4+docCount*8 != fdxFileLength) // // This is most likely a bug in Sun JRE 1.6.0_04/_05; // // we detect that the bug has struck, here, and // // throw an exception to prevent the corruption from // // entering the index. See LUCENE-1282 for // // details. // throw new RuntimeException("mergeFields produced an invalid result: docCount is " + docCount + " but fdx file size is " + fdxFileLength + "; now aborting this merge to prevent index corruption"); } else // If we are skipping the doc stores, that means there // are no deletions in any of these segments, so we // just sum numDocs() of each segment to get total docCount for (int i = 0; i < readers.Count; i++) docCount += ((IndexReader)readers[i]).NumDocs(); return docCount; } [System.Serializable] private class AnonymousClassFieldSelector : FieldSelector { public AnonymousClassFieldSelector(SegmentMerger enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(SegmentMerger enclosingInstance) { this.enclosingInstance = enclosingInstance; } private SegmentMerger enclosingInstance; public SegmentMerger Enclosing_Instance { get { return enclosingInstance; } } public FieldSelectorResult Accept(System.String fieldName) { return FieldSelectorResult.LOAD_FOR_MERGE; } } /// <summary> Merge the TermVectors from each of the segments into the new one.</summary> /// <throws> IOException </throws> private void MergeVectors() { TermVectorsWriter termVectorsWriter = new TermVectorsWriter(directory, segment, fieldInfos); try { for (int r = 0; r < readers.Count; r++) { SegmentReader matchingSegmentReader = matchingSegmentReaders[r]; TermVectorsReader matchingVectorsReader; bool hasMatchingReader; if (matchingSegmentReader != null) { matchingVectorsReader = matchingSegmentReader.termVectorsReaderOrig; // If the TV* files are an older format then they // cannot read raw docs: if (matchingVectorsReader != null && !matchingVectorsReader.CanReadRawDocs()) { matchingVectorsReader = null; hasMatchingReader = false; } else hasMatchingReader = matchingVectorsReader != null; } else { hasMatchingReader = false; matchingVectorsReader = null; } IndexReader reader = (IndexReader)readers[r]; bool hasDeletions = reader.HasDeletions(); int maxDoc = reader.MaxDoc(); for (int docNum = 0; docNum < maxDoc; ) { // skip deleted docs if (!hasDeletions || !reader.IsDeleted(docNum)) { if (hasMatchingReader) { // We can optimize this case (doing a bulk // byte copy) since the field numbers are // identical int start = docNum; int numDocs = 0; do { docNum++; numDocs++; if (docNum >= maxDoc) break; if (hasDeletions && matchingSegmentReader.IsDeleted(docNum)) { docNum++; break; } } while (numDocs < MAX_RAW_MERGE_DOCS); matchingVectorsReader.RawDocs(rawDocLengths, rawDocLengths2, start, numDocs); termVectorsWriter.AddRawDocuments(matchingVectorsReader, rawDocLengths, rawDocLengths2, numDocs); if (checkAbort != null) checkAbort.Work(300 * numDocs); } else { // NOTE: it's very important to first assign // to vectors then pass it to // termVectorsWriter.addAllDocVectors; see // LUCENE-1282 TermFreqVector[] vectors = reader.GetTermFreqVectors(docNum); termVectorsWriter.AddAllDocVectors(vectors); docNum++; if (checkAbort != null) checkAbort.Work(300); } } else docNum++; } } } finally { termVectorsWriter.Close(); } long tvxSize = directory.FileLength(segment + "." + IndexFileNames.VECTORS_INDEX_EXTENSION); // {{dougsale-2.4.0} // this shouldn't be a problem for us - if it is, // then it's not a JRE bug //if (4 + mergedDocs * 16 != tvxSize) // // This is most likely a bug in Sun JRE 1.6.0_04/_05; // // we detect that the bug has struck, here, and // // throw an exception to prevent the corruption from // // entering the index. See LUCENE-1282 for // // details. // throw new RuntimeException("mergeVectors produced an invalid result: mergedDocs is " + mergedDocs + " but tvx size is " + tvxSize + "; now aborting this merge to prevent index corruption"); } private IndexOutput freqOutput = null; private IndexOutput proxOutput = null; private TermInfosWriter termInfosWriter = null; private int skipInterval; private int maxSkipLevels; private SegmentMergeQueue queue = null; private DefaultSkipListWriter skipListWriter = null; private void MergeTerms() { try { freqOutput = directory.CreateOutput(segment + ".frq"); if (HasProx()) proxOutput = directory.CreateOutput(segment + ".prx"); termInfosWriter = new TermInfosWriter(directory, segment, fieldInfos, termIndexInterval); skipInterval = termInfosWriter.skipInterval; maxSkipLevels = termInfosWriter.maxSkipLevels; skipListWriter = new DefaultSkipListWriter(skipInterval, maxSkipLevels, mergedDocs, freqOutput, proxOutput); queue = new SegmentMergeQueue(readers.Count); MergeTermInfos(); } finally { if (freqOutput != null) freqOutput.Close(); if (proxOutput != null) proxOutput.Close(); if (termInfosWriter != null) termInfosWriter.Close(); if (queue != null) queue.Close(); } } private void MergeTermInfos() { int base_Renamed = 0; int readerCount = readers.Count; for (int i = 0; i < readerCount; i++) { IndexReader reader = (IndexReader) readers[i]; TermEnum termEnum = reader.Terms(); SegmentMergeInfo smi = new SegmentMergeInfo(base_Renamed, termEnum, reader); int[] docMap = smi.GetDocMap(); if (docMap != null) { if (docMaps == null) { docMaps = new int[readerCount][]; delCounts = new int[readerCount]; } docMaps[i] = docMap; delCounts[i] = smi.reader.MaxDoc() - smi.reader.NumDocs(); } base_Renamed += reader.NumDocs(); if (smi.Next()) queue.Put(smi);// initialize queue else smi.Close(); } SegmentMergeInfo[] match = new SegmentMergeInfo[readers.Count]; while (queue.Size() > 0) { int matchSize = 0; // pop matching terms match[matchSize++] = (SegmentMergeInfo) queue.Pop(); Term term = match[0].term; SegmentMergeInfo top = (SegmentMergeInfo) queue.Top(); while (top != null && term.CompareTo(top.term) == 0) { match[matchSize++] = (SegmentMergeInfo) queue.Pop(); top = (SegmentMergeInfo) queue.Top(); } int df = MergeTermInfo(match, matchSize); // add new TermInfo if (checkAbort != null) checkAbort.Work(df / 3.0); while (matchSize > 0) { SegmentMergeInfo smi = match[--matchSize]; if (smi.Next()) queue.Put(smi); // restore queue else smi.Close(); // done with a segment } } } private TermInfo termInfo = new TermInfo(); // minimize consing /// <summary>Merge one term found in one or more segments. The array <code>smis</code> /// contains segments that are positioned at the same term. <code>N</code> /// is the number of cells in the array actually occupied. /// /// </summary> /// <param name="smis">array of segments /// </param> /// <param name="n">number of cells in the array actually occupied /// </param> /// <throws> CorruptIndexException if the index is corrupt </throws> /// <throws> IOException if there is a low-level IO error </throws> private int MergeTermInfo(SegmentMergeInfo[] smis, int n) { long freqPointer = freqOutput.GetFilePointer(); long proxPointer; if (proxOutput != null) proxPointer = proxOutput.GetFilePointer(); else proxPointer = 0; int df; if (fieldInfos.FieldInfo(smis[0].term.field).omitTf) { // append posting data df = AppendPostingsNoTf(smis, n); } else { df = AppendPostings(smis, n); } long skipPointer = skipListWriter.WriteSkip(freqOutput); if (df > 0) { // add an entry to the dictionary with pointers to prox and freq files termInfo.Set(df, freqPointer, proxPointer, (int) (skipPointer - freqPointer)); termInfosWriter.Add(smis[0].term, termInfo); } return df; } private byte[] payloadBuffer; private int[][] docMaps; internal int[][] GetDocMaps() { return docMaps; } private int[] delCounts; internal int[] GetDelCounts() { return delCounts; } /// <summary>Process postings from multiple segments all positioned on the /// same term. Writes out merged entries into freqOutput and /// the proxOutput streams. /// /// </summary> /// <param name="smis">array of segments /// </param> /// <param name="n">number of cells in the array actually occupied /// </param> /// <returns> number of documents across all segments where this term was found /// </returns> /// <throws> CorruptIndexException if the index is corrupt </throws> /// <throws> IOException if there is a low-level IO error </throws> private int AppendPostings(SegmentMergeInfo[] smis, int n) { int lastDoc = 0; int df = 0; // number of docs w/ term skipListWriter.ResetSkip(); bool storePayloads = fieldInfos.FieldInfo(smis[0].term.field).storePayloads; int lastPayloadLength = - 1; // ensures that we write the first length for (int i = 0; i < n; i++) { SegmentMergeInfo smi = smis[i]; TermPositions postings = smi.GetPositions(); System.Diagnostics.Debug.Assert(postings != null); int base_Renamed = smi.base_Renamed; int[] docMap = smi.GetDocMap(); postings.Seek(smi.termEnum); while (postings.Next()) { int doc = postings.Doc(); if (docMap != null) doc = docMap[doc]; // map around deletions doc += base_Renamed; // convert to merged space if (doc < 0 || (df > 0 && doc <= lastDoc)) throw new CorruptIndexException("docs out of order (" + doc + " <= " + lastDoc + " )"); df++; if ((df % skipInterval) == 0) { skipListWriter.SetSkipData(lastDoc, storePayloads, lastPayloadLength); skipListWriter.BufferSkip(df); } int docCode = (doc - lastDoc) << 1; // use low bit to flag freq=1 lastDoc = doc; int freq = postings.Freq(); if (freq == 1) { freqOutput.WriteVInt(docCode | 1); // write doc & freq=1 } else { freqOutput.WriteVInt(docCode); // write doc freqOutput.WriteVInt(freq); // write frequency in doc } /** See {@link DocumentWriter#writePostings(Posting[], String)} for * documentation about the encoding of positions and payloads */ int lastPosition = 0; // write position deltas for (int j = 0; j < freq; j++) { int position = postings.NextPosition(); int delta = position - lastPosition; if (storePayloads) { int payloadLength = postings.GetPayloadLength(); if (payloadLength == lastPayloadLength) { proxOutput.WriteVInt(delta * 2); } else { proxOutput.WriteVInt(delta * 2 + 1); proxOutput.WriteVInt(payloadLength); lastPayloadLength = payloadLength; } if (payloadLength > 0) { if (payloadBuffer == null || payloadBuffer.Length < payloadLength) { payloadBuffer = new byte[payloadLength]; } postings.GetPayload(payloadBuffer, 0); proxOutput.WriteBytes(payloadBuffer, 0, payloadLength); } } else { proxOutput.WriteVInt(delta); } lastPosition = position; } } } return df; } /// <summary> /// Process postings from multiple segments without tf, all positioned on the same term. /// Writes out merged entries only into freqOutput, proxOut is not written. /// </summary> /// <param name="smis">smis array of segments</param> /// <param name="n">number of cells in the array actually occupied</param> /// <returns></returns> private int AppendPostingsNoTf(SegmentMergeInfo[] smis, int n) { int lastDoc = 0; int df = 0; // number of docs w/ term skipListWriter.ResetSkip(); int lastPayloadLength = -1; // ensures that we write the first length for (int i = 0; i < n; i++) { SegmentMergeInfo smi = smis[i]; TermPositions postings = smi.GetPositions(); System.Diagnostics.Debug.Assert(postings != null); int base_Renamed = smi.base_Renamed; int[] docMap = smi.GetDocMap(); postings.Seek(smi.termEnum); while (postings.Next()) { int doc = postings.Doc(); if (docMap != null) doc = docMap[doc]; // map around deletions doc += base_Renamed; // convert to merged space if (doc < 0 || (df > 0 && doc <= lastDoc)) throw new CorruptIndexException("docs out of order (" + doc + " <= " + lastDoc + " )"); df++; if ((df % skipInterval) == 0) { skipListWriter.SetSkipData(lastDoc, false, lastPayloadLength); skipListWriter.BufferSkip(df); } int docCode = (doc - lastDoc); lastDoc = doc; freqOutput.WriteVInt(docCode); // write doc & freq=1 } } return df; } private void MergeNorms() { byte[] normBuffer = null; IndexOutput output = null; try { for (int i = 0; i < fieldInfos.Size(); i++) { FieldInfo fi = fieldInfos.FieldInfo(i); if (fi.isIndexed && !fi.omitNorms) { if (output == null) { output = directory.CreateOutput(segment + "." + IndexFileNames.NORMS_EXTENSION); output.WriteBytes(NORMS_HEADER, NORMS_HEADER.Length); } for (int j = 0; j < readers.Count; j++) { IndexReader reader = (IndexReader) readers[j]; int maxDoc = reader.MaxDoc(); if (normBuffer == null || normBuffer.Length < maxDoc) { // the buffer is too small for the current segment normBuffer = new byte[maxDoc]; } reader.Norms(fi.name, normBuffer, 0); if (!reader.HasDeletions()) { //optimized case for segments without deleted docs output.WriteBytes(normBuffer, maxDoc); } else { // this segment has deleted docs, so we have to // check for every doc if it is deleted or not for (int k = 0; k < maxDoc; k++) { if (!reader.IsDeleted(k)) { output.WriteByte(normBuffer[k]); } } } if (checkAbort != null) checkAbort.Work(maxDoc); } } } } finally { if (output != null) { output.Close(); } } } internal sealed class CheckAbort { private double workCount; private MergePolicy.OneMerge merge; private Directory dir; public CheckAbort(MergePolicy.OneMerge merge, Directory dir) { this.merge = merge; this.dir = dir; } /// <summary> Records the fact that roughly units amount of work /// have been done since this method was last called. /// When adding time-consuming code into SegmentMerger, /// you should test different values for units to ensure /// that the time in between calls to merge.checkAborted /// is up to ~ 1 second. /// </summary> public void Work(double units) { workCount += units; if (workCount >= 10000.0) { merge.CheckAborted(dir); workCount = 0; } } } } }
// 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 Xunit; namespace System.Diagnostics.TraceSourceTests { using Method = TestTraceListener.Method; public sealed class TraceSourceClassTests { [Fact] public void ConstrutorExceptionTest() { Assert.Throws<ArgumentNullException>(() => new TraceSource(null)); AssertExtensions.Throws<ArgumentException>("name", null, () => new TraceSource("")); } [Fact] public void DefaultListenerTest() { var trace = new TraceSource("TestTraceSource"); Assert.Equal(1, trace.Listeners.Count); Assert.IsType<DefaultTraceListener>(trace.Listeners[0]); } [Fact] public void SetSourceSwitchExceptionTest() { var trace = new TraceSource("TestTraceSource"); Assert.Throws<ArgumentNullException>(() => trace.Switch = null); } [Fact] public void SetSourceSwitchTest() { var trace = new TraceSource("TestTraceSource"); var @switch = new SourceSwitch("TestTraceSwitch"); trace.Switch = @switch; Assert.Equal(@switch, trace.Switch); } [Fact] public void DefaultLevelTest() { var trace = new TraceSource("TestTraceSource"); Assert.Equal(SourceLevels.Off, trace.Switch.Level); } [Fact] public void CloseTest() { var trace = new TraceSource("T1", SourceLevels.All); trace.Listeners.Clear(); var listener = new TestTraceListener(); trace.Listeners.Add(listener); trace.Close(); Assert.Equal(1, listener.GetCallCount(Method.Close)); // Assert that writing to a closed TraceSource is not an error. trace.TraceEvent(TraceEventType.Critical, 0); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static WeakReference PruneMakeRef() { return new WeakReference(new TraceSource("TestTraceSource")); } [Fact] public void PruneTest() { var strongTrace = new TraceSource("TestTraceSource"); var traceRef = PruneMakeRef(); Assert.True(traceRef.IsAlive); GC.Collect(2); Trace.Refresh(); Assert.False(traceRef.IsAlive); GC.Collect(2); Trace.Refresh(); } [Fact] public void TraceInformationTest() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = new TestTraceListener(); trace.Listeners.Add(listener); trace.TraceInformation("message"); Assert.Equal(0, listener.GetCallCount(Method.TraceData)); Assert.Equal(0, listener.GetCallCount(Method.Write)); Assert.Equal(1, listener.GetCallCount(Method.TraceEvent)); trace.TraceInformation("format", "arg1", "arg2"); Assert.Equal(2, listener.GetCallCount(Method.TraceEvent)); } [Theory] [InlineData(SourceLevels.Off, TraceEventType.Critical, 0)] [InlineData(SourceLevels.Critical, TraceEventType.Critical, 1)] [InlineData(SourceLevels.Critical, TraceEventType.Error, 0)] [InlineData(SourceLevels.Error, TraceEventType.Error, 1)] [InlineData(SourceLevels.Error, TraceEventType.Warning, 0)] [InlineData(SourceLevels.Warning, TraceEventType.Warning, 1)] [InlineData(SourceLevels.Warning, TraceEventType.Information, 0)] [InlineData(SourceLevels.Information, TraceEventType.Information, 1)] [InlineData(SourceLevels.Information, TraceEventType.Verbose, 0)] [InlineData(SourceLevels.Verbose, TraceEventType.Verbose, 1)] [InlineData(SourceLevels.All, TraceEventType.Critical, 1)] [InlineData(SourceLevels.All, TraceEventType.Verbose, 1)] // NOTE: tests to cover a TraceEventType value that is not in CoreFX (0x20 == TraceEventType.Start in 4.5) [InlineData(SourceLevels.Verbose, (TraceEventType)0x20, 0)] [InlineData(SourceLevels.All, (TraceEventType)0x20, 1)] public void SwitchLevelTest(SourceLevels sourceLevel, TraceEventType messageLevel, int expected) { var trace = new TraceSource("TestTraceSource"); var listener = new TestTraceListener(); trace.Listeners.Add(listener); trace.Switch.Level = sourceLevel; trace.TraceEvent(messageLevel, 0); Assert.Equal(expected, listener.GetCallCount(Method.TraceEvent)); } [Fact] public void NullSourceName() { AssertExtensions.Throws<ArgumentNullException>("name", () => new TraceSource(null)); AssertExtensions.Throws<ArgumentNullException>("name", () => new TraceSource(null, SourceLevels.All)); } [Fact] public void EmptySourceName() { AssertExtensions.Throws<ArgumentException>("name", null, () => new TraceSource(string.Empty)); AssertExtensions.Throws<ArgumentException>("name", null, () => new TraceSource(string.Empty, SourceLevels.All)); } } public sealed class TraceSourceTests_Default : TraceSourceTestsBase { // default mode: GlobalLock = true, AutoFlush = false, ThreadSafeListener = false } public sealed class TraceSourceTests_AutoFlush : TraceSourceTestsBase { internal override bool AutoFlush { get { return true; } } } public sealed class TraceSourceTests_NoGlobalLock : TraceSourceTestsBase { internal override bool UseGlobalLock { get { return false; } } } public sealed class TraceSourceTests_NoGlobalLock_AutoFlush : TraceSourceTestsBase { internal override bool UseGlobalLock { get { return false; } } internal override bool AutoFlush { get { return true; } } } public sealed class TraceSourceTests_ThreadSafeListener : TraceSourceTestsBase { internal override bool ThreadSafeListener { get { return true; } } } public sealed class TraceSourceTests_ThreadSafeListener_AutoFlush : TraceSourceTestsBase { internal override bool ThreadSafeListener { get { return true; } } internal override bool AutoFlush { get { return true; } } } // Defines abstract tests that will be executed in different modes via the above concrete classes. public abstract class TraceSourceTestsBase : IDisposable { void IDisposable.Dispose() { TraceTestHelper.ResetState(); } public TraceSourceTestsBase() { Trace.AutoFlush = AutoFlush; Trace.UseGlobalLock = UseGlobalLock; } // properties are overridden to define different "modes" of execution internal virtual bool UseGlobalLock { get { // ThreadSafeListener is only meaningful when not using a global lock, // so UseGlobalLock will be auto-disabled in that mode. return true && !ThreadSafeListener; } } internal virtual bool AutoFlush { get { return false; } } internal virtual bool ThreadSafeListener { get { return false; } } private TestTraceListener GetTraceListener() { return new TestTraceListener(ThreadSafeListener); } [Fact] public void FlushTest() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.Flush(); Assert.Equal(1, listener.GetCallCount(Method.Flush)); } [Fact] public void TraceEvent1Test() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.TraceEvent(TraceEventType.Verbose, 0); Assert.Equal(1, listener.GetCallCount(Method.TraceEvent)); } [Fact] public void TraceEvent2Test() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.TraceEvent(TraceEventType.Verbose, 0, "Message"); Assert.Equal(1, listener.GetCallCount(Method.TraceEvent)); var flushExpected = AutoFlush ? 1 : 0; Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush)); } [Fact] public void TraceEvent3Test() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.TraceEvent(TraceEventType.Verbose, 0, "Format", "Arg1", "Arg2"); Assert.Equal(1, listener.GetCallCount(Method.TraceEvent)); var flushExpected = AutoFlush ? 1 : 0; Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush)); } [Fact] public void TraceData1Test() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.TraceData(TraceEventType.Verbose, 0, new Object()); Assert.Equal(1, listener.GetCallCount(Method.TraceData)); var flushExpected = AutoFlush ? 1 : 0; Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush)); } [Fact] public void TraceData2Test() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.TraceData(TraceEventType.Verbose, 0, new Object[0]); Assert.Equal(1, listener.GetCallCount(Method.TraceData)); var flushExpected = AutoFlush ? 1 : 0; Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush)); } [Fact] public void TraceTransferTest() { var trace = new TraceSource("TestTraceSource", SourceLevels.All); var listener = GetTraceListener(); trace.Listeners.Add(listener); trace.TraceTransfer(1, "Trace transfer test message", Trace.CorrelationManager.ActivityId); Assert.Equal(1, listener.GetCallCount(Method.TraceTransfer)); var flushExpected = AutoFlush ? 1 : 0; Assert.Equal(flushExpected, listener.GetCallCount(Method.Flush)); } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using System.Net; using Apache.Http; using Apache.Http.Client; using Apache.Http.Impl.Client; using Couchbase.Lite; using Couchbase.Lite.Replicator; using Couchbase.Lite.Util; using NUnit.Framework; using Sharpen; namespace Couchbase.Lite.Replicator { public class ChangeTrackerTest : LiteTestCase { public const string Tag = "ChangeTracker"; /// <exception cref="System.Exception"></exception> public virtual void TestChangeTracker() { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); ChangeTrackerClient client = new _ChangeTrackerClient_31(changeTrackerFinishedSignal ); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .OneShot, false, 0, client); changeTracker.Start(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_31 : ChangeTrackerClient { public _ChangeTrackerClient_31(CountDownLatch changeTrackerFinishedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); } public HttpClient GetHttpClient() { return new DefaultHttpClient(); } private readonly CountDownLatch changeTrackerFinishedSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerLongPoll() { ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode.LongPoll); } /// <exception cref="System.Exception"></exception> public virtual void FailingTestChangeTrackerContinuous() { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); ChangeTrackerClient client = new _ChangeTrackerClient_72(changeTrackerFinishedSignal , changeReceivedSignal); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .Continuous, false, 0, client); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_72 : ChangeTrackerClient { public _ChangeTrackerClient_72(CountDownLatch changeTrackerFinishedSignal, CountDownLatch changeReceivedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.changeReceivedSignal = changeReceivedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { return new DefaultHttpClient(); } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CountDownLatch changeReceivedSignal; } /// <exception cref="System.Exception"></exception> public virtual void ChangeTrackerTestWithMode(ChangeTracker.ChangeTrackerMode mode ) { CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); CountDownLatch changeReceivedSignal = new CountDownLatch(1); Uri testURL = GetReplicationURL(); ChangeTrackerClient client = new _ChangeTrackerClient_119(changeTrackerFinishedSignal , changeReceivedSignal); ChangeTracker changeTracker = new ChangeTracker(testURL, mode, false, 0, client); changeTracker.Start(); try { bool success = changeReceivedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_119 : ChangeTrackerClient { public _ChangeTrackerClient_119(CountDownLatch changeTrackerFinishedSignal, CountDownLatch changeReceivedSignal) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.changeReceivedSignal = changeReceivedSignal; } public void ChangeTrackerStopped(ChangeTracker tracker) { changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); NUnit.Framework.Assert.AreEqual("*:1", seq.ToString()); changeReceivedSignal.CountDown(); } public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.SetResponder("_changes", new _Responder_136()); return mockHttpClient; } private sealed class _Responder_136 : CustomizableMockHttpClient.Responder { public _Responder_136() { } /// <exception cref="System.IO.IOException"></exception> public HttpResponse Execute(HttpRequestMessage httpUriRequest) { string json = "{\"results\":[\n" + "{\"seq\":\"*:1\",\"id\":\"doc1-138\",\"changes\":[{\"rev\":\"1-82d\"}]}],\n" + "\"last_seq\":\"*:50\"}"; return CustomizableMockHttpClient.GenerateHttpResponseObject(json); } } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CountDownLatch changeReceivedSignal; } public virtual void TestChangeTrackerWithConflictsIncluded() { Uri testURL = GetReplicationURL(); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, true, 0, null); NUnit.Framework.Assert.AreEqual("_changes?feed=longpoll&limit=50&heartbeat=300000&style=all_docs&since=0" , changeTracker.GetChangesFeedPath()); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerWithFilterURL() { Uri testURL = GetReplicationURL(); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, null); // set filter changeTracker.SetFilterName("filter"); // build filter map IDictionary<string, object> filterMap = new Dictionary<string, object>(); filterMap.Put("param", "value"); // set filter map changeTracker.SetFilterParams(filterMap); NUnit.Framework.Assert.AreEqual("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=filter&param=value" , changeTracker.GetChangesFeedPath()); } public virtual void TestChangeTrackerWithDocsIds() { Uri testURL = GetReplicationURL(); ChangeTracker changeTrackerDocIds = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, null); IList<string> docIds = new AList<string>(); docIds.AddItem("doc1"); docIds.AddItem("doc2"); changeTrackerDocIds.SetDocIDs(docIds); string docIdsEncoded = URLEncoder.Encode("[\"doc1\",\"doc2\"]"); string expectedFeedPath = string.Format("_changes?feed=longpoll&limit=50&heartbeat=300000&since=0&filter=_doc_ids&doc_ids=%s" , docIdsEncoded); string changesFeedPath = changeTrackerDocIds.GetChangesFeedPath(); NUnit.Framework.Assert.AreEqual(expectedFeedPath, changesFeedPath); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoffExceptions() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); TestChangeTrackerBackoff(mockHttpClient); } /// <exception cref="System.Exception"></exception> public virtual void TestChangeTrackerBackoffInvalidJson() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderReturnInvalidChangesFeedJson(); TestChangeTrackerBackoff(mockHttpClient); } /// <exception cref="System.Exception"></exception> private void TestChangeTrackerBackoff(CustomizableMockHttpClient mockHttpClient) { Uri testURL = GetReplicationURL(); CountDownLatch changeTrackerFinishedSignal = new CountDownLatch(1); ChangeTrackerClient client = new _ChangeTrackerClient_234(changeTrackerFinishedSignal , mockHttpClient); ChangeTracker changeTracker = new ChangeTracker(testURL, ChangeTracker.ChangeTrackerMode .LongPoll, false, 0, client); changeTracker.Start(); // sleep for a few seconds Sharpen.Thread.Sleep(5 * 1000); // make sure we got less than 10 requests in those 10 seconds (if it was hammering, we'd get a lot more) NUnit.Framework.Assert.IsTrue(mockHttpClient.GetCapturedRequests().Count < 25); NUnit.Framework.Assert.IsTrue(changeTracker.backoff.GetNumAttempts() > 0); mockHttpClient.ClearResponders(); mockHttpClient.AddResponderReturnEmptyChangesFeed(); // at this point, the change tracker backoff should cause it to sleep for about 3 seconds // and so lets wait 3 seconds until it wakes up and starts getting valid responses Sharpen.Thread.Sleep(3 * 1000); // now find the delta in requests received in a 2s period int before = mockHttpClient.GetCapturedRequests().Count; Sharpen.Thread.Sleep(2 * 1000); int after = mockHttpClient.GetCapturedRequests().Count; // assert that the delta is high, because at this point the change tracker should // be hammering away NUnit.Framework.Assert.IsTrue((after - before) > 25); // the backoff numAttempts should have been reset to 0 NUnit.Framework.Assert.IsTrue(changeTracker.backoff.GetNumAttempts() == 0); changeTracker.Stop(); try { bool success = changeTrackerFinishedSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _ChangeTrackerClient_234 : ChangeTrackerClient { public _ChangeTrackerClient_234(CountDownLatch changeTrackerFinishedSignal, CustomizableMockHttpClient mockHttpClient) { this.changeTrackerFinishedSignal = changeTrackerFinishedSignal; this.mockHttpClient = mockHttpClient; } public void ChangeTrackerStopped(ChangeTracker tracker) { Log.V(ChangeTrackerTest.Tag, "changeTrackerStopped"); changeTrackerFinishedSignal.CountDown(); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { object seq = change.Get("seq"); Log.V(ChangeTrackerTest.Tag, "changeTrackerReceivedChange: " + seq.ToString()); } public HttpClient GetHttpClient() { return mockHttpClient; } private readonly CountDownLatch changeTrackerFinishedSignal; private readonly CustomizableMockHttpClient mockHttpClient; } } }
// Copyright (c) 2015 Alachisoft // // 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 Alachisoft.ContentOptimization.Caching; using System.Threading; using Alachisoft.NCache.Web.Caching; using System.Collections; using System.Reflection; using Alachisoft.NCache.ContentOptimization.Diagnostics; using Alachisoft.ContentOptimization.Diagnostics.Logging; namespace Alachisoft.NCache.ContentOptimization.Caching { class CacheAdapter : ICache { private const string VIEWSTATE_TAG = "NC_ASP.net_viewstate_data"; public static Version Version { get { AssemblyName name = typeof(Cache).Assembly.GetName(); return name.Version; } } /// <summary> /// Class to hold byte[] because NCache throws internal exceptions if value is byte[] /// </summary> [Serializable] class ByteArray { public byte[] Value { get; private set; } public ByteArray(byte[] value) { this.Value = value; } } Cache cache; string cacheName; string sessionCacheNaame; String sessionApppId; System.Timers.Timer reloadTimer; const string LOCK_GROUP = "NCPStreamLocks"; public Expiration DefaultExpiration { get; set; } /// <summary> /// Retry interval in seconds /// </summary> public int RetryInterval { get; set; } public bool Loaded { get; private set; } public bool AsyncMode { get; set; } /// <summary> /// Size of cache stream chunk in KBs /// </summary> public int StreamBlockSize { get; set; } /// <summary> /// No. of blocks to read in bulk from Cache /// </summary> public int BulkGets { get; set; } public bool UseRemoteDependency { get; set; } public FileBasedTraceProvider TraceProvider{ get; set; } public CacheAdapter(string cacheName) { StreamBlockSize = 64; BulkGets = 1; this.cacheName = cacheName; reloadTimer = new System.Timers.Timer(); reloadTimer.AutoReset = false; reloadTimer.Elapsed += new System.Timers.ElapsedEventHandler(reloadTimer_Elapsed); } public bool Load() { reloadTimer.Stop(); bool loaded = true; try { cache = NCache.Web.Caching.NCache.InitializeCache(cacheName); } catch (Exception ex) { loaded = false; FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not initialize cache due to exception: {0}", ex.Message); } Loaded = loaded; if (!loaded) ScheduleReload(); return loaded; } public bool Contains(string key) { if (!Loaded) return false; bool exists; try { exists = cache.Contains(key); } catch (Exception ex) { OnError(ex); FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not access cache due to exception: {0}", ex.Message); exists = false; } return exists; } public bool Insert(string key, object value) { return Insert(key, value, DefaultExpiration); } public bool Insert(string key, object value, Expiration expiration) { CacheItem cacheItem = CreateCacheItem(value, expiration); if (!Loaded) return false; else { cache.Insert(key, cacheItem); return true; } } public bool InsertWithReleaseLock(string key, object value, object lockHandle, Expiration expiration) { if (!Loaded) return false; if (value is byte[]) value = new ByteArray((byte[])value); CacheItem item = CreateCacheItem(value, expiration); LockHandle handle = lockHandle as LockHandle; try { cache.Insert(key, item, handle, true); return true; } catch(Exception ex) { FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not add item to cache due to exception: {0}", ex.Message); return false; } } public IEnumerable<DictionaryEntry> GetBulk(params string[] keys) { IDictionary items = cache.GetBulk(keys); foreach (DictionaryEntry entry in items) yield return new DictionaryEntry(entry.Key, SafeConvert(entry.Value)); } public object Get(string key) { if (!Loaded) return null; object value; try { value = cache.Get(key); } catch (Exception ex) { OnError(ex); value = null; FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not read item from cache due to exception: {0}", ex.Message); } value = SafeConvert(value); return value; } public object GetWithLock(string key, int interval, bool acquireLock, out object lochkHandle) { if (!Loaded) { lochkHandle = null; return null; } DateTime startTime = DateTime.Now; object value = null; LockHandle handle = null; TimeSpan lockInterval = new TimeSpan(0, 0, 0, 0, interval); while (startTime.AddMilliseconds(interval) >= DateTime.Now) { handle = null; //lochkHandle as LockHandle; if(cache != null) value = cache.Get(key, lockInterval, ref handle, true); if (value != null) break; if (value == null && handle == null) break; Thread.Sleep(500); } if (value == null && handle != null) { if (cache != null) { cache.Unlock(key); value = cache.Get(key, lockInterval, ref handle, true); } } if (value != null) lochkHandle = handle; else lochkHandle = null; return value; } public bool Remove(string key) { if (!Loaded) return false; bool removed = true; try { cache.Remove(key); } catch (Exception ex) { OnError(ex); removed = false; FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not remove item from cache due to exception: {0}", ex.Message); } return removed; } public bool Lock(string key, TimeSpan lockTimeout) { if (!Loaded) return false; bool success = true; LockHandle handle; try { success = cache.Lock(key, lockTimeout, out handle); } catch(Exception ex) { return false; } return success; } public void Unlock(string key) { if (!Loaded) return; try { cache.Unlock(key); } catch(Exception ex) {} } public void ReleaseLock(string lockId) { Remove(lockId); } public ICache GetSynchronized(ReaderWriterLock syncLock) { return this; } public ICache GetSynchronized() { return this; } void OnAsyncItemAdded(string key, object result) { if (result is Exception) { var ex = (Exception)result; OnError(ex); FileBasedTraceProvider.Current.WriteTrace(TraceSeverity.Exception, "Could not add item to cache due to exception: {0}", ex.Message); } } void reloadTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Load(); } static object SafeConvert(object value) { if (value is ByteArray) value = ((ByteArray)value).Value; return value; } CacheItem CreateCacheItem(object value, Expiration expiration) { DateTime absolute = Cache.NoAbsoluteExpiration; TimeSpan sliding = Cache.NoSlidingExpiration; if (expiration != null) { switch (expiration.ExpirationType) { case ExpirationType.Absolute: absolute = DateTime.Now.AddMinutes(expiration.Duration); break; case ExpirationType.Sliding: sliding = TimeSpan.FromMinutes(expiration.Duration); break; } } CacheItem item = new CacheItem(value); item.AbsoluteExpiration = absolute; item.SlidingExpiration = sliding; return item; } void ScheduleReload() { Loaded = false; if (cache != null) cache.Dispose(); cache = null; if (RetryInterval > 0) { reloadTimer.Interval = RetryInterval * 1000; // convert to miliseconds reloadTimer.Start(); } } void OnError(Exception ex) { /* TODO: We've requested NCache Team to throw a DependencyKeyNotFoundException so we don't have to compare the text. * This is one of the several possibilities in which cache should not be disposed * This error currently won't arise in Async mode so we've only handled it here * we should improve this. * * PS: When two parallel read requests for same BLOB comes then both start adding the stream to cache * the second request removes the items added by first request and so the dependency key is lost */ if (ErrorRequiresReload(ex)) ScheduleReload(); } bool ErrorRequiresReload(Exception ex) { bool requiresReload = true; if (ex is Alachisoft.NCache.Runtime.Exceptions.OperationFailedException && ex.Message == "One of the dependency keys does not exist.") requiresReload = false; else if (ex is Alachisoft.NCache.Runtime.Exceptions.AggregateException) { var aggregateEx = (Alachisoft.NCache.Runtime.Exceptions.AggregateException)ex; var exRequiresReload = Array.Find(aggregateEx.InnerExceptions, ErrorRequiresReload); requiresReload = exRequiresReload != null; } return requiresReload; } public void Dispose() { reloadTimer.Dispose(); if (cache != null) cache.Dispose(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>ThirdPartyAppAnalyticsLink</c> resource.</summary> public sealed partial class ThirdPartyAppAnalyticsLinkName : gax::IResourceName, sys::IEquatable<ThirdPartyAppAnalyticsLinkName> { /// <summary>The possible contents of <see cref="ThirdPartyAppAnalyticsLinkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c> /// . /// </summary> CustomerCustomerLink = 1, } private static gax::PathTemplate s_customerCustomerLink = new gax::PathTemplate("customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}"); /// <summary> /// Creates a <see cref="ThirdPartyAppAnalyticsLinkName"/> 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="ThirdPartyAppAnalyticsLinkName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ThirdPartyAppAnalyticsLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ThirdPartyAppAnalyticsLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ThirdPartyAppAnalyticsLinkName"/> with the pattern /// <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="ThirdPartyAppAnalyticsLinkName"/> constructed from the provided ids. /// </returns> public static ThirdPartyAppAnalyticsLinkName FromCustomerCustomerLink(string customerId, string customerLinkId) => new ThirdPartyAppAnalyticsLinkName(ResourceNameType.CustomerCustomerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerLinkId, nameof(customerLinkId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with /// pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with pattern /// <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </returns> public static string Format(string customerId, string customerLinkId) => FormatCustomerCustomerLink(customerId, customerLinkId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with /// pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with pattern /// <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </returns> public static string FormatCustomerCustomerLink(string customerId, string customerLinkId) => s_customerCustomerLink.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customerLinkId, nameof(customerLinkId))); /// <summary> /// Parses the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> 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}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="ThirdPartyAppAnalyticsLinkName"/> if successful.</returns> public static ThirdPartyAppAnalyticsLinkName Parse(string thirdPartyAppAnalyticsLinkName) => Parse(thirdPartyAppAnalyticsLinkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> 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}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// 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="ThirdPartyAppAnalyticsLinkName"/> if successful.</returns> public static ThirdPartyAppAnalyticsLinkName Parse(string thirdPartyAppAnalyticsLinkName, bool allowUnparsed) => TryParse(thirdPartyAppAnalyticsLinkName, allowUnparsed, out ThirdPartyAppAnalyticsLinkName 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="ThirdPartyAppAnalyticsLinkName"/> /// 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}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ThirdPartyAppAnalyticsLinkName"/>, 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 thirdPartyAppAnalyticsLinkName, out ThirdPartyAppAnalyticsLinkName result) => TryParse(thirdPartyAppAnalyticsLinkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> /// 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}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// 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="ThirdPartyAppAnalyticsLinkName"/>, 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 thirdPartyAppAnalyticsLinkName, bool allowUnparsed, out ThirdPartyAppAnalyticsLinkName result) { gax::GaxPreconditions.CheckNotNull(thirdPartyAppAnalyticsLinkName, nameof(thirdPartyAppAnalyticsLinkName)); gax::TemplatedResourceName resourceName; if (s_customerCustomerLink.TryParseName(thirdPartyAppAnalyticsLinkName, out resourceName)) { result = FromCustomerCustomerLink(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(thirdPartyAppAnalyticsLinkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ThirdPartyAppAnalyticsLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string customerLinkId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; CustomerLinkId = customerLinkId; } /// <summary> /// Constructs a new instance of a <see cref="ThirdPartyAppAnalyticsLinkName"/> class from the component parts /// of pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> public ThirdPartyAppAnalyticsLinkName(string customerId, string customerLinkId) : this(ResourceNameType.CustomerCustomerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerLinkId, nameof(customerLinkId))) { } /// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>CustomerLink</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string CustomerLinkId { 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.CustomerCustomerLink: return s_customerCustomerLink.Expand(CustomerId, CustomerLinkId); 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 ThirdPartyAppAnalyticsLinkName); /// <inheritdoc/> public bool Equals(ThirdPartyAppAnalyticsLinkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ThirdPartyAppAnalyticsLinkName a, ThirdPartyAppAnalyticsLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ThirdPartyAppAnalyticsLinkName a, ThirdPartyAppAnalyticsLinkName b) => !(a == b); } public partial class ThirdPartyAppAnalyticsLink { /// <summary> /// <see cref="ThirdPartyAppAnalyticsLinkName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal ThirdPartyAppAnalyticsLinkName ResourceNameAsThirdPartyAppAnalyticsLinkName { get => string.IsNullOrEmpty(ResourceName) ? null : ThirdPartyAppAnalyticsLinkName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var syntaxKindsMissing = new HashSet<SyntaxKind>(); // AllInOneCSharpCode has no deconstruction or declaration expression syntaxKindsMissing.Add(SyntaxKind.TypedVariableComponent); syntaxKindsMissing.Add(SyntaxKind.ParenthesizedVariableComponent); syntaxKindsMissing.Add(SyntaxKind.SingleVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.ParenthesizedVariableDesignation); syntaxKindsMissing.Add(SyntaxKind.DeconstructionDeclarationStatement); syntaxKindsMissing.Add(SyntaxKind.VariableComponentAssignment); syntaxKindsMissing.Add(SyntaxKind.ForEachComponentStatement); syntaxKindsMissing.Add(SyntaxKind.DeclarationExpression); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(syntaxKindsMissing); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineAnalyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using (var workspace = await TestWorkspace.CreateCSharpAsync(source, TestOptions.Regular)) { var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, document, new Text.TextSpan(0, document.GetTextAsync().Result.Length), logAnalyzerExceptionAsDiagnostics: true)); } } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using (var workspace = await TestWorkspace.CreateCSharpAsync(TestResource.AllInOneCSharpCode, TestOptions.Regular)) { var currentProject = workspace.CurrentSolution.Projects.Single(); var additionalDocId = DocumentId.CreateNewId(currentProject.Id); var newSln = workspace.CurrentSolution.AddAdditionalDocument(additionalDocId, "add.config", SourceText.From("random text")); currentProject = newSln.Projects.Single(); var additionalDocument = currentProject.GetAdditionalDocument(additionalDocId); AdditionalText additionalStream = new AdditionalTextDocument(additionalDocument.State); AnalyzerOptions options = new AnalyzerOptions(ImmutableArray.Create(additionalStream)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var sourceDocument = currentProject.Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, sourceDocument, new Text.TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new TestDiagnosticAnalyzerService(LanguageNames.CSharp, analyzer); diagnosticService.GetDiagnosticDescriptors(projectOpt: null); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool OpenFileOnly(Workspace workspace) => false; public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SyntaxAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); } public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) { context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); } private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(analyzer, ideEngineDocument, new Text.TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = await TestWorkspace.CreateCSharpAsync(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); } public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } } }
using System; using NUnit.Framework; using ProtoCore.DSASM.Mirror; using ProtoTestFx.TD; namespace ProtoTest.TD.Imperative { class BlockSyntax { public TestFrameWork thisTest = new TestFrameWork(); string testPath = "..\\..\\..\\Scripts\\TD\\Imperative\\BlockSyntax\\"; [SetUp] public void Setup() { } [Test] [Category("SmokeTest")] public void T01_TestImpInsideImp() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string code = @" [Imperative] { x = 5; [Imperative] { y = 5; } }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); // thisTest.Verify("x", 5); // thisTest.Verify("y", 5); }); } [Test] [Category("SmokeTest")] public void T02_TestAssocInsideImp() { string src = @"x; y; z; w; f; [Imperative] { x = 5.1; z = y; w = z * 2; [Associative] { y = 5; z = x; x = 35; i = 3; } f = i; }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("x").Payload == 35); Assert.IsTrue((Int64)mirror.GetValue("z").Payload == 35); Assert.IsTrue((Int64)mirror.GetValue("y").Payload == 5); Assert.IsTrue(mirror.GetValue("w").DsasmValue.optype == ProtoCore.DSASM.AddressType.Null); Assert.IsTrue(mirror.GetValue("f").DsasmValue.optype == ProtoCore.DSASM.AddressType.Null); } [Test] [Category("SmokeTest")] public void T03_TestImpInsideAssoc() { string src = @"x; y; z; w; f; [Associative] { x = 5.1; z = y; w = z * 2; [Imperative] { y = 5; z = x; x = 35; i = 3; } f = i; }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("x").Payload == 35); Assert.IsTrue((Int64)mirror.GetValue("z").Payload == 5); Assert.IsTrue((Int64)mirror.GetValue("y").Payload == 5); Assert.IsTrue((Int64)mirror.GetValue("w").Payload == 10); Assert.IsTrue(mirror.GetValue("f").DsasmValue.optype == ProtoCore.DSASM.AddressType.Null); } [Test] [Category("SmokeTest")] public void T04_TestImperativeBlockWithMissingBracket_negative() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string src = @"[Imperative] { x = 5.1; "; ExecutionMirror mirror = thisTest.RunScriptSource(src); }); } [Test] [Category("SmokeTest")] public void T05_TestImperativeBlockWithMissingBracket_negative() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string src = @"[Imperative] x = 5.1; }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); }); } [Test] [Category("SmokeTest")] public void T06_TestNestedImpBlockWithMissingBracket_negative() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string src = @"[Imperative] { x = 5.1; [Associative] { }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); }); } [Test] [Category("SmokeTest")] public void T07_TestBlockWithIncorrectBlockName_negative() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string src = @"[imperitive] { x = 5.1; }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); }); } [Test] [Category("SmokeTest")] public void T08_TestBlockWithIncorrectBlockName_negative() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string code = @"[Imperative] { x = 5.1; [assoc] { y = 2; } }"; ExecutionMirror mirro = thisTest.RunScriptSource(code); }); } [Test] [Category("SmokeTest")] public void T09_Defect_1449829() { string src = @"b; [Associative] { a = 2; [Imperative] { b = 1; if(a == 2 ) { b = 2; } else { b = 4; } } } "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("b").Payload == 2); } [Test] [Category("SmokeTest")] public void T10_Defect_1449732() { string src = @"c; [Imperative] { def fn1:int(a:int,b:int) { return = a + b -1; } c = fn1(3,2); } "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("c").Payload == 4); } [Test] [Category("SmokeTest")] public void T11_Defect_1450174() { string src = @"c; [Imperative] { def function1:double(a:int,b:double) { return = a * b; } c = function1(2 + 3,4.0 + 6.0 / 4.0); } "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((double)mirror.GetValue("c").Payload == 27.5); } [Test] [Category("SmokeTest")] public void T12_Defect_1450599() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string src = @"[Imperative] x = 5; } "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("x").Payload == 5); }); } [Test] [Category("SmokeTest")] public void T13_Defect_1450527() { string src = @"temp; [Associative] { a = 1; temp=0; [Imperative] { i = 0; if(i <= a) { temp = temp + 1; } } a = 2; } "; ExecutionMirror mirror = thisTest.RunScriptSource(src); thisTest.Verify("temp", 2); } [Test] [Category("SmokeTest")] public void T14_Defect_1450550() { string src = @"a; [Associative] { a = 4; b = a*2; x = [Imperative] { def fn:int(a:int) { return = a; } _i = fn(0); return = _i; } a = x; }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 0); } [Test] [Category("SmokeTest")] public void T15_Defect_1452044() { string src = @"b; [Associative] { a = 2; [Imperative] { b = 2 * a; } }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("b").Payload == 4); } [Test] [Category("SmokeTest")] public void T16__Defect_1452588() { string src = @"x; [Imperative] { a = { 1,2,3,4,5 }; for( y in a ) { x = 5; } }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("x").Payload == 5); } [Test] [Category("SmokeTest")] public void T17__Defect_1452588_2() { string src = @"c; [Imperative] { a = 1; if( a == 1 ) { if( a + 1 == 2) b = 2; } c = a; }"; ExecutionMirror mirror = thisTest.RunScriptSource(src); Assert.IsTrue((Int64)mirror.GetValue("c").Payload == 1); } [Test] [Category("SmokeTest")] public void T18__Negative_Block_Syntax() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string src = @"x = 1; y = {Imperative] { return = x + 1; } "; ExecutionMirror mirror = thisTest.RunScriptSource(src); }); } [Test] [Category("SmokeTest")] public void T19_Imperative_Nested() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string code = @" [Imperative] { a=1; [Imperative] { b=a+1; } } "; ExecutionMirror mirror = thisTest.RunScriptSource(code); }); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using Icu; using SIL.Extensions; using SIL.Keyboarding; using SIL.Xml; namespace SIL.WritingSystems { /// <summary> /// The LdmlDatamapper Reads and Writes WritingSystemDefinitions to LDML files. A typical consuming application should not /// need to use the LdmlDataMapper directly but should rather use an IWritingSystemRepository (such as the /// LdmlInfolderWritingSystemRepository) to manage it's writing systems. /// The LdmlDatamapper is tightly tied to the CLDR version of LDML. If the LdmlDatamapper refuses to Read a /// particular Ldml file it may need to be migrated to the latest version. Please use the /// LdmlInFolderWritingSystemRepository class for this purpose. /// Please note that the LdmlDataMapper.Write method can round trip data that it does not understand if passed an /// appropriate stream or xmlreader produced from the old file. /// Be aware that as of Jul-5-2011 an exception was made for certain well defined Fieldworks LDML files whose contained /// Rfc5646 tag begin with "x-". These will load correctly, albeit in a transformed state, in spite of being "Version 0". /// Furthermore writing systems containing RfcTags beginning with "x-" and that have a matching Fieldworks conform LDML file /// in the repository will not be changed including no marking with "version 1". /// </summary> /// <remarks> /// LDML reference: http://www.unicode.org/reports/tr35/ /// </remarks> public class LdmlDataMapper { /// <summary> /// This is the current version of the LDML data and is mostly used for migration purposes. /// This should not be confused with the version of the locale data contained in this writing system. /// That information is stored in the "VersionNumber" property. /// </summary> public const int CurrentLdmlVersion = 3; private static readonly XNamespace Palaso = "urn://palaso.org/ldmlExtensions/v1"; private static readonly XNamespace Sil = "urn://www.sil.org/ldml/0.1"; /// <summary> /// Mapping of font engine attribute to FontEngines enumeration. /// </summary> private static readonly Dictionary<string, FontEngines> EngineToFontEngines = new Dictionary<string, FontEngines> { {"ot", FontEngines.OpenType}, {"gr", FontEngines.Graphite} }; /// <summary> /// Mapping of FontEngines enumeration to font engine attribute. /// If the engine is none, leave an empty string /// </summary> private static readonly Dictionary<FontEngines, string> FontEnginesToEngine = new Dictionary<FontEngines, string> { {FontEngines.None, string.Empty}, {FontEngines.OpenType, "ot"}, {FontEngines.Graphite, "gr"} }; /// <summary> /// Mapping of font role/type attribute to FontRoles enumeration /// If this attribute is missing, the font role default is used /// </summary> private static readonly Dictionary<string, FontRoles> RoleToFontRoles = new Dictionary<string, FontRoles> { {string.Empty, FontRoles.Default}, {"default", FontRoles.Default}, {"heading", FontRoles.Heading}, {"emphasis", FontRoles.Emphasis} }; /// <summary> /// Mapping of FontRoles enumeration to font role/type attribute /// </summary> private static readonly Dictionary<FontRoles, string> FontRolesToRole = new Dictionary<FontRoles, string> { {FontRoles.Default, "default"}, {FontRoles.Heading, "heading"}, {FontRoles.Emphasis, "emphasis"} }; /// <summary> /// Mapping of spell checking type attribute to SpellCheckDictionaryFormat enumeration /// </summary> private static readonly Dictionary<string, SpellCheckDictionaryFormat> SpellCheckToSpecllCheckDictionaryFormats = new Dictionary <string, SpellCheckDictionaryFormat> { {"hunspell", SpellCheckDictionaryFormat.Hunspell}, {"wordlist", SpellCheckDictionaryFormat.Wordlist}, {"lift", SpellCheckDictionaryFormat.Lift} }; /// <summary> /// Mapping of SpellCheckDictionaryFormat enumeration to spell checking type attribute /// </summary> private static readonly Dictionary<SpellCheckDictionaryFormat, string> SpellCheckDictionaryFormatsToSpellCheck = new Dictionary <SpellCheckDictionaryFormat, string> { {SpellCheckDictionaryFormat.Hunspell, "hunspell"}, {SpellCheckDictionaryFormat.Wordlist, "wordlist"}, {SpellCheckDictionaryFormat.Lift, "lift"} }; /// <summary> /// Mapping of keyboard type attribute to KeyboardFormat enumeration /// </summary> private static readonly Dictionary<string, KeyboardFormat> KeyboardToKeyboardFormat = new Dictionary<string, KeyboardFormat> { {string.Empty, KeyboardFormat.Unknown}, {"kmn", KeyboardFormat.Keyman }, {"kmx", KeyboardFormat.CompiledKeyman}, {"msklc", KeyboardFormat.Msklc}, {"ldml", KeyboardFormat.Ldml}, {"keylayout", KeyboardFormat.Keylayout} }; /// <summary> /// Mapping of KeyboardFormat enumeration to keyboard type attribute /// </summary> private static readonly Dictionary<KeyboardFormat, string> KeyboardFormatToKeyboard = new Dictionary<KeyboardFormat, string> { {KeyboardFormat.Keyman, "kmn"}, {KeyboardFormat.CompiledKeyman, "kmx"}, {KeyboardFormat.Msklc, "msklc"}, {KeyboardFormat.Ldml, "ldml"}, {KeyboardFormat.Keylayout, "keylayout"} }; /// <summary> /// Mapping of context attribute to PunctuationPatternContext enumeration /// </summary> private static readonly Dictionary<string, PunctuationPatternContext> ContextToPunctuationPatternContext = new Dictionary<string, PunctuationPatternContext> { {"init", PunctuationPatternContext.Initial}, {"medial", PunctuationPatternContext.Medial}, {"final", PunctuationPatternContext.Final}, {"break", PunctuationPatternContext.Break}, {"isolate", PunctuationPatternContext.Isolate} }; /// <summary> /// Mapping of PunctuationPatternContext enumeration to context attribute /// </summary> private static readonly Dictionary<PunctuationPatternContext, string> PunctuationPatternContextToContext = new Dictionary<PunctuationPatternContext, string> { {PunctuationPatternContext.Initial, "init"}, {PunctuationPatternContext.Medial, "medial"}, {PunctuationPatternContext.Final, "final"}, {PunctuationPatternContext.Break, "break"}, {PunctuationPatternContext.Isolate, "isolate"} }; /// <summary> /// Mapping of paraContinueType attribute to QuotationParagraphContinueType enumeration /// </summary> private static readonly Dictionary<string, QuotationParagraphContinueType> QuotationToQuotationParagraphContinueTypes = new Dictionary<string, QuotationParagraphContinueType> { {string.Empty, QuotationParagraphContinueType.None}, {"all", QuotationParagraphContinueType.All}, {"outer", QuotationParagraphContinueType.Outermost}, {"inner", QuotationParagraphContinueType.Innermost} }; /// <summary> /// Mapping of QuotationParagraphContinueType enumeration to paraContinueType attribute /// </summary> private static readonly Dictionary<QuotationParagraphContinueType, string> QuotationParagraphContinueTypesToQuotation = new Dictionary<QuotationParagraphContinueType, string> { {QuotationParagraphContinueType.None, string.Empty}, {QuotationParagraphContinueType.All, "all"}, {QuotationParagraphContinueType.Outermost, "outer"}, {QuotationParagraphContinueType.Innermost, "inner"} }; /// <summary> /// Mapping of quotation marking system attribute to QuotationMarkingSystemType enumeration /// </summary> private static readonly Dictionary<string, QuotationMarkingSystemType> QuotationToQuotationMarkingSystemTypes = new Dictionary<string, QuotationMarkingSystemType> { {string.Empty, QuotationMarkingSystemType.Normal}, {"narrative", QuotationMarkingSystemType.Narrative} }; /// <summary> /// Mapping of QuotationMarkingSystemType enumeration to quotation marking system attribute /// </summary> private static readonly Dictionary<QuotationMarkingSystemType, string> QuotationMarkingSystemTypesToQuotation = new Dictionary<QuotationMarkingSystemType, string> { {QuotationMarkingSystemType.Normal, string.Empty}, {QuotationMarkingSystemType.Narrative, "narrative"} }; private readonly IWritingSystemFactory _writingSystemFactory; public LdmlDataMapper(IWritingSystemFactory writingSystemFactory) { _writingSystemFactory = writingSystemFactory; } public void Read(string filePath, WritingSystemDefinition ws) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (ws == null) { throw new ArgumentNullException("ws"); } XElement element = XElement.Load(filePath); ReadLdml(element, ws); } public void Read(XmlReader xmlReader, WritingSystemDefinition ws) { if (xmlReader == null) { throw new ArgumentNullException("xmlReader"); } if (ws == null) { throw new ArgumentNullException("ws"); } var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto, ValidationType = ValidationType.None, XmlResolver = null, DtdProcessing = DtdProcessing.Parse }; using (XmlReader reader = XmlReader.Create(xmlReader, settings)) { XElement element = XElement.Load(reader); ReadLdml(element, ws); } } public static void WriteLdmlText(XmlWriter writer, string text) { // Not all Unicode characters are valid in an XML document, so we need to create // the <cp hex="X"> elements to replace the invalid characters. // Note: While 0xD (carriage return) is a valid XML character, it is automatically // either dropped or converted to 0xA by any conforming XML parser, so we also make a <cp> // element for that one. var sb = new StringBuilder(text.Length); for (int i=0; i < text.Length; i++) { int code = Char.ConvertToUtf32(text, i); if ((code == 0x9) || (code == 0xA) || (code >= 0x20 && code <= 0xD7FF) || (code >= 0xE000 && code <= 0xFFFD) || (code >= 0x10000 && code <= 0x10FFFF)) { sb.Append(Char.ConvertFromUtf32(code)); } else { writer.WriteString(sb.ToString()); writer.WriteStartElement("cp"); writer.WriteAttributeString("hex", String.Format("{0:X}", code)); writer.WriteEndElement(); sb = new StringBuilder(text.Length - i); } if (Char.IsSurrogatePair(text, i)) { i++; } } writer.WriteString(sb.ToString()); } /// <summary> /// Read the LDML file at the root element and populate the writing system. /// </summary> /// <param name="element">Root element</param> /// <param name="ws">Writing System to populate</param> /// <remarks> /// For elements that have * annotation in the LDML spec, we use the extensions NonAltElement /// and NonAltElements to ignore the elements that have the alt attribute. /// </remarks> private void ReadLdml(XElement element, WritingSystemDefinition ws) { Debug.Assert(element != null); Debug.Assert(ws != null); if (element.Name != "ldml") throw new ApplicationException("Unable to load writing system definition: Missing <ldml> tag."); ResetWritingSystemDefinition(ws); XElement identityElem = element.Element("identity"); if (identityElem != null) ReadIdentityElement(identityElem, ws); // Check for the proper LDML version after reading identity element so that we have the proper language tag if an error occurs. foreach (XElement specialElem in element.NonAltElements("special")) CheckVersion(specialElem, ws); XElement charactersElem = element.Element("characters"); if (charactersElem != null) ReadCharactersElement(charactersElem, ws); XElement delimitersElem = element.Element("delimiters"); if (delimitersElem != null) ReadDelimitersElement(delimitersElem, ws); XElement layoutElem = element.Element("layout"); if (layoutElem != null) ReadLayoutElement(layoutElem, ws); XElement numbersElem = element.Element("numbers"); if (numbersElem != null) ReadNumbersElement(numbersElem, ws); XElement collationsElem = element.Element("collations"); if (collationsElem != null) ReadCollationsElement(collationsElem, ws); foreach (XElement specialElem in element.NonAltElements("special")) ReadTopLevelSpecialElement(specialElem, ws); // Validate collations after all of them have been read in (for self-referencing imports) foreach (CollationDefinition cd in ws.Collations) { string message; cd.Validate(out message); } ws.Id = string.Empty; ws.AcceptChanges(); } /// <summary> /// Resets all of the properties of the writing system definition that might not get set when reading the LDML file. /// </summary> private void ResetWritingSystemDefinition(WritingSystemDefinition ws) { ws.VersionNumber = null; ws.VersionDescription = null; ws.WindowsLcid = null; ws.DefaultRegion = null; ws.CharacterSets.Clear(); ws.MatchedPairs.Clear(); ws.PunctuationPatterns.Clear(); ws.QuotationMarks.Clear(); ws.QuotationParagraphContinueType = QuotationParagraphContinueType.None; ws.RightToLeftScript = false; ws.DefaultCollationType = null; ws.Collations.Clear(); ws.Fonts.Clear(); ws.SpellCheckDictionaries.Clear(); ws.KnownKeyboards.Clear(); } private void CheckVersion(XElement specialElem, WritingSystemDefinition ws) { // Flag invalid versions (0-2 inclusive) from reading legacy LDML files // We're intentionally not using WritingSystemLDmlVersionGetter and the // cheeck for Flex7V0Compatible because the migrator will have handled that. if (!string.IsNullOrEmpty((string) specialElem.Attribute(XNamespace.Xmlns + "fw")) || !string.IsNullOrEmpty((string) specialElem.Attribute(XNamespace.Xmlns + "palaso"))) { string version = "0"; // Palaso namespace XElement versionElem = specialElem.Element(Palaso + "version"); if (versionElem != null) { version = (string)versionElem.Attribute("value"); version = string.IsNullOrEmpty(version) ? "0" : version; } throw new ApplicationException(String.Format( "The LDML tag '{0}' is version {1}. Version {2} was expected.", ws.LanguageTag, version, CurrentLdmlVersion )); } } private void ReadTopLevelSpecialElement(XElement specialElem, WritingSystemDefinition ws) { XElement externalResourcesElem = specialElem.Element(Sil + "external-resources"); if (externalResourcesElem != null) { ReadFontElement(externalResourcesElem, ws); ReadSpellcheckElement(externalResourcesElem, ws); ReadKeyboardElement(externalResourcesElem, ws); } } private void ReadFontElement(XElement externalResourcesElem, WritingSystemDefinition ws) { foreach (XElement fontElem in externalResourcesElem.NonAltElements(Sil + "font")) { var fontName = (string) fontElem.Attribute("name"); if (!string.IsNullOrEmpty(fontName)) { var fd = new FontDefinition(fontName); // Types (space separate list) var roles = (string) fontElem.Attribute("types"); if (!String.IsNullOrEmpty(roles)) { IEnumerable<string> roleList = roles.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); foreach (string roleEntry in roleList) { fd.Roles |= RoleToFontRoles[roleEntry]; } } else { fd.Roles = FontRoles.Default; } // Relative Size fd.RelativeSize = (float?) fontElem.Attribute("size") ?? 1.0f; // Minversion fd.MinVersion = (string) fontElem.Attribute("minversion"); // Features (space separated list of key=value pairs) fd.Features = (string) fontElem.Attribute("features"); // Language fd.Language = (string) fontElem.Attribute("lang"); // OpenType language fd.OpenTypeLanguage = (string) fontElem.Attribute("otlang"); // Font Engine (space separated list) supercedes legacy isGraphite flag // If attribute is missing it is assumed to be "gr ot" var engines = (string) fontElem.Attribute("engines") ?? "gr ot"; IEnumerable<string> engineList = engines.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); foreach (string engineEntry in engineList) fd.Engines |= (EngineToFontEngines[engineEntry]); // Subset fd.Subset = (string) fontElem.Attribute("subset"); // URL elements foreach (XElement urlElem in fontElem.NonAltElements(Sil + "url")) fd.Urls.Add(urlElem.Value); ws.Fonts.Add(fd); } } } private void ReadSpellcheckElement(XElement externalResourcesElem, WritingSystemDefinition ws) { foreach (XElement scElem in externalResourcesElem.NonAltElements(Sil + "spellcheck")) { var type = (string) scElem.Attribute("type"); if (!string.IsNullOrEmpty(type)) { var scd = new SpellCheckDictionaryDefinition(SpellCheckToSpecllCheckDictionaryFormats[type]); // URL elements foreach (XElement urlElem in scElem.NonAltElements(Sil + "url")) scd.Urls.Add(urlElem.Value); ws.SpellCheckDictionaries.Add(scd); } } } private void ReadKeyboardElement(XElement externalResourcesElem, WritingSystemDefinition ws) { foreach (XElement kbdElem in externalResourcesElem.NonAltElements(Sil + "kbd")) { var id = (string) kbdElem.Attribute("id"); if (!string.IsNullOrEmpty(id)) { KeyboardFormat format = KeyboardToKeyboardFormat[(string) kbdElem.Attribute("type") ?? string.Empty]; IKeyboardDefinition keyboard = Keyboard.Controller.CreateKeyboard(id, format, kbdElem.NonAltElements(Sil + "url").Select(u => (string) u)); ws.KnownKeyboards.Add(keyboard); } } } private void ReadIdentityElement(XElement identityElem, WritingSystemDefinition ws) { Debug.Assert(identityElem.Name == "identity"); XElement versionElem = identityElem.Element("version"); if (versionElem != null) { ws.VersionNumber = (string) versionElem.Attribute("number") ?? string.Empty; ws.VersionDescription = (string) versionElem; } XElement generationElem = identityElem.Element("generation"); DateTime modified = DateTime.UtcNow; if (generationElem != null) { string dateTime = (string) generationElem.Attribute("date") ?? string.Empty; // Previous versions of LDML Data Mapper allowed generation date to be in CVS format // This is deprecated so we only handle ISO 8601 format if (DateTimeExtensions.IsISO8601DateTime(dateTime)) modified = DateTimeExtensions.ParseISO8601DateTime(dateTime); } ws.DateModified = modified; string language = identityElem.GetAttributeValue("language", "type"); string script = identityElem.GetAttributeValue("script", "type"); string region = identityElem.GetAttributeValue("territory", "type"); string variant = identityElem.GetAttributeValue("variant", "type"); ws.LanguageTag = IetfLanguageTag.Create(language, script, region, variant); // TODO: Parse rest of special element. Currently only handling a subset XElement specialElem = identityElem.NonAltElement("special"); if (specialElem != null) { XElement silIdentityElem = specialElem.Element(Sil + "identity"); if (silIdentityElem != null) { ws.WindowsLcid = (string) silIdentityElem.Attribute("windowsLCID"); ws.DefaultRegion = (string) silIdentityElem.Attribute("defaultRegion"); // Update the variant name if a non-wellknown private use variant exists var variantName = (string) silIdentityElem.Attribute("variantName") ?? String.Empty; int index = IetfLanguageTag.GetIndexOfFirstNonCommonPrivateUseVariant(ws.Variants); if (!string.IsNullOrEmpty(variantName) && (index != -1)) { ws.Variants[index] = new VariantSubtag(ws.Variants[index], variantName); } } } } private void ReadCharactersElement(XElement charactersElem, WritingSystemDefinition ws) { foreach (XElement exemplarCharactersElem in charactersElem.NonAltElements("exemplarCharacters")) ReadExemplarCharactersElem(exemplarCharactersElem, ws); XElement specialElem = charactersElem.NonAltElement("special"); if (specialElem != null) { foreach (XElement exemplarCharactersElem in specialElem.NonAltElements(Sil + "exemplarCharacters")) { // Sil:exemplarCharacters are required to have a type if (!string.IsNullOrEmpty((string) exemplarCharactersElem.Attribute("type"))) ReadExemplarCharactersElem(exemplarCharactersElem, ws); } } } private void ReadExemplarCharactersElem(XElement exemplarCharactersElem, WritingSystemDefinition ws) { string type = (string) exemplarCharactersElem.Attribute("type") ?? "main"; var csd = new CharacterSetDefinition(type); var unicodeSet = (string) exemplarCharactersElem; csd.Characters.AddRange(type == "footnotes" ? unicodeSet.Trim('[', ']').Split(' ').Select(c => c.Trim('{', '}')) : UnicodeSet.ToCharacters(unicodeSet)); ws.CharacterSets.Add(csd); } private void ReadDelimitersElement(XElement delimitersElem, WritingSystemDefinition ws) { string open, close; string level1Continue = null; string level2Continue = null; // A bit strange, but we need to read the special element first to get everything we need to write // level 1 and 2. So we just store everything but 1 and 2 in a list and add them after we add 1 and 2. var specialQuotationMarks = new List<QuotationMark>(); XElement specialElem = delimitersElem.NonAltElement("special"); if (specialElem != null) { XElement matchedPairsElem = specialElem.Element(Sil + "matched-pairs"); if (matchedPairsElem != null) { foreach (XElement matchedPairElem in matchedPairsElem.NonAltElements(Sil + "matched-pair")) { open = (string) matchedPairElem.Attribute("open"); close = (string) matchedPairElem.Attribute("close"); bool paraClose = (bool?) matchedPairElem.Attribute("paraClose") ?? false; var mp = new MatchedPair(open, close, paraClose); ws.MatchedPairs.Add(mp); } } XElement punctuationPatternsElem = specialElem.Element(Sil + "punctuation-patterns"); if (punctuationPatternsElem != null) { foreach (XElement punctuationPatternElem in punctuationPatternsElem.NonAltElements(Sil + "punctuation-pattern")) { var pattern = (string) punctuationPatternElem.Attribute("pattern"); PunctuationPatternContext ppc = ContextToPunctuationPatternContext[(string) punctuationPatternElem.Attribute("context")]; var pp = new PunctuationPattern(pattern, ppc); ws.PunctuationPatterns.Add(pp); } } XElement quotationsElem = specialElem.Element(Sil + "quotation-marks"); if (quotationsElem != null) { string paraContinueType = (string)quotationsElem.Attribute("paraContinueType") ?? string.Empty; ws.QuotationParagraphContinueType = QuotationToQuotationParagraphContinueTypes[paraContinueType]; level1Continue = (string)quotationsElem.Element(Sil + "quotationContinue"); level2Continue = (string)quotationsElem.Element(Sil + "alternateQuotationContinue"); foreach (XElement quotationElem in quotationsElem.NonAltElements(Sil + "quotation")) { open = (string) quotationElem.Attribute("open"); close = (string) quotationElem.Attribute("close"); var cont = (string) quotationElem.Attribute("continue"); int level = (int?) quotationElem.Attribute("level") ?? 1; var type = (string) quotationElem.Attribute("type"); QuotationMarkingSystemType qmType = !string.IsNullOrEmpty(type) ? QuotationToQuotationMarkingSystemTypes[type] : QuotationMarkingSystemType.Normal; var qm = new QuotationMark(open, close, cont, level, qmType); specialQuotationMarks.Add(qm); } } } // level 1: quotationStart, quotationEnd open = (string)delimitersElem.NonAltElement("quotationStart"); close = (string)delimitersElem.NonAltElement("quotationEnd"); if (!string.IsNullOrEmpty(open) || !string.IsNullOrEmpty(close) || !string.IsNullOrEmpty(level1Continue)) { var qm = new QuotationMark(open, close, level1Continue, 1, QuotationMarkingSystemType.Normal); ws.QuotationMarks.Add(qm); } // level 2: alternateQuotationStart, alternateQuotationEnd open = (string)delimitersElem.NonAltElement("alternateQuotationStart"); close = (string)delimitersElem.NonAltElement("alternateQuotationEnd"); if (!string.IsNullOrEmpty(open) || !string.IsNullOrEmpty(close) || !string.IsNullOrEmpty(level2Continue)) { var qm = new QuotationMark(open, close, level2Continue, 2, QuotationMarkingSystemType.Normal); ws.QuotationMarks.Add(qm); } ws.QuotationMarks.AddRange(specialQuotationMarks); } private void ReadLayoutElement(XElement layoutElem, WritingSystemDefinition ws) { // The orientation node has two attributes, "lines" and "characters" which define direction of writing. // The valid values are: "top-to-bottom", "bottom-to-top", "left-to-right", and "right-to-left" // Currently we only handle horizontal character orders with top-to-bottom line order, so // any value other than characters right-to-left, we treat as our default left-to-right order. // This probably works for many scripts such as various East Asian scripts which traditionally // are top-to-bottom characters and right-to-left lines, but can also be written with // left-to-right characters and top-to-bottom lines. //Debug.Assert(layoutElem.NodeType == XmlNodeType.Element && layoutElem.Name == "layout"); XElement orientationElem = layoutElem.NonAltElement("orientation"); if (orientationElem != null) { XElement characterOrderElem = orientationElem.NonAltElement("characterOrder"); if (characterOrderElem != null) ws.RightToLeftScript = ((string) characterOrderElem == "right-to-left"); } } // Numbering system gets added to the character set definition private void ReadNumbersElement(XElement numbersElem, WritingSystemDefinition ws) { XElement defaultNumberingSystemElem = numbersElem.NonAltElement("defaultNumberingSystem"); if (defaultNumberingSystemElem != null) { var id = (string) defaultNumberingSystemElem; XElement numberingSystemsElem = numbersElem.NonAltElements("numberingSystem") .FirstOrDefault(e => id == (string) e.Attribute("id") && (string) e.Attribute("type") == "numeric"); if (numberingSystemsElem != null) { var csd = new CharacterSetDefinition("numeric"); // Only handle numeric types var digits = (string) numberingSystemsElem.Attribute("digits"); foreach (char charItem in digits) csd.Characters.Add(charItem.ToString(CultureInfo.InvariantCulture)); ws.CharacterSets.Add(csd); } } } private void ReadCollationsElement(XElement collationsElem, WritingSystemDefinition ws) { XElement defaultCollationElem = collationsElem.Element("defaultCollation"); ws.DefaultCollationType = (string) defaultCollationElem; foreach (XElement collationElem in collationsElem.NonAltElements("collation")) ReadCollationElement(collationElem, ws); } private void ReadCollationElement(XElement collationElem, WritingSystemDefinition ws) { var collationType = (string)collationElem.Attribute("type"); if (!string.IsNullOrEmpty(collationType)) { CollationDefinition cd = null; XElement specialElem = collationElem.NonAltElement("special"); if ((specialElem != null) && (specialElem.HasElements)) { string specialType = (specialElem.Elements().First().Name.LocalName); switch (specialType) { case "simple": cd = ReadCollationRulesForCustomSimple(collationElem, specialElem, collationType); break; case "reordered": // Skip for now break; } } else { cd = ReadCollationRulesForCustomIcu(collationElem, ws, collationType); } // Only add collation definition if it's been set if (cd != null) ws.Collations.Add(cd); } } private SimpleRulesCollationDefinition ReadCollationRulesForCustomSimple(XElement collationElem, XElement specialElem, string collationType) { XElement simpleElem = specialElem.Element(Sil + "simple"); bool needsCompiling = (bool?) specialElem.Attribute(Sil + "needscompiling") ?? false; var scd = new SimpleRulesCollationDefinition(collationType) {SimpleRules = ((string) simpleElem).Replace("\n", "\r\n")}; if (!needsCompiling) { scd.CollationRules = LdmlCollationParser.GetIcuRulesFromCollationNode(collationElem); scd.IsValid = true; } return scd; } private IcuRulesCollationDefinition ReadCollationRulesForCustomIcu(XElement collationElem, WritingSystemDefinition ws, string collationType) { var icd = new IcuRulesCollationDefinition(collationType) {WritingSystemFactory = _writingSystemFactory, OwningWritingSystemDefinition = ws}; icd.Imports.AddRange(collationElem.NonAltElements("import").Select(ie => new IcuCollationImport((string) ie.Attribute("source"), (string) ie.Attribute("type")))); icd.IcuRules = LdmlCollationParser.GetIcuRulesFromCollationNode(collationElem); return icd; } /// <summary> /// Utility to get or create the special element with SIL namespace /// </summary> /// <param name="element">parent element of the special element</param> /// <returns></returns> private XElement GetOrCreateSpecialElement(XElement element) { // Create element XElement specialElem = element.GetOrCreateElement("special"); specialElem.SetAttributeValue(XNamespace.Xmlns + "sil", Sil); return specialElem; } /// <summary> /// Utility to remove empty elements. Since isEmpty is true for "<element />" /// but false for "<element></element>", we have to check both cases /// </summary> /// <param name="element">XElement to remove if it's empty or has 0 contents/attributes/elements</param> private void RemoveIfEmpty(ref XElement element) { if (element != null) { if (element.IsEmpty || (string.IsNullOrEmpty((string)element) && !element.HasElements && !element.HasAttributes)) { element.Remove(); element = null; } } } /// <summary> /// The "oldFile" parameter allows the LdmldataMapper to allow data that it doesn't understand to be roundtripped. /// </summary> /// <param name="filePath"></param> /// <param name="ws"></param> /// <param name="oldFile"></param> public void Write(string filePath, WritingSystemDefinition ws, Stream oldFile) { if (filePath == null) { throw new ArgumentNullException("filePath"); } if (ws == null) { throw new ArgumentNullException("ws"); } // We don't want to run any risk of persisting an invalid writing system in an LDML. string message; if (!ws.ValidateLanguageTag(out message)) throw new ArgumentException(string.Format("The writing system's IETF language tag is invalid: {0}", message), "ws"); XmlReader reader = null; try { XElement element; if (oldFile != null) { var readerSettings = new XmlReaderSettings { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Auto, ValidationType = ValidationType.None, XmlResolver = null, DtdProcessing = DtdProcessing.Parse }; reader = XmlReader.Create(oldFile, readerSettings); element = XElement.Load(reader); } else { element = new XElement("ldml"); } // Use Canonical xml settings suitable for use in Chorus applications // except NewLineOnAttributes to conform to SLDR files var writerSettings = CanonicalXmlSettings.CreateXmlWriterSettings(); writerSettings.NewLineOnAttributes = false; using (var writer = XmlWriter.Create(filePath, writerSettings)) { WriteLdml(writer, element, ws); writer.Close(); } } finally { if (reader != null) { reader.Close(); } } } /// <summary> /// The "oldFileReader" parameter allows the LdmldataMapper to allow data that it doesn't understand to be roundtripped. /// </summary> /// <param name="xmlWriter"></param> /// <param name="ws"></param> /// <param name="oldFileReader"></param> public void Write(XmlWriter xmlWriter, WritingSystemDefinition ws, XmlReader oldFileReader) { if (xmlWriter == null) { throw new ArgumentNullException("xmlWriter"); } if (ws == null) { throw new ArgumentNullException("ws"); } // We don't want to run any risk of persisting an invalid writing system in an LDML. string message; if (!ws.ValidateLanguageTag(out message)) throw new ArgumentException(string.Format("The writing system's IETF language tag is invalid: {0}", message), "ws"); XElement element = oldFileReader != null ? XElement.Load(oldFileReader) : new XElement("ldml"); WriteLdml(xmlWriter, element, ws); } /// <summary> /// Update element based on the writing system model. At the end, write the contents to LDML /// </summary> /// <param name="writer"></param> /// <param name="element"></param> /// <param name="ws"></param> private void WriteLdml(XmlWriter writer, XElement element, WritingSystemDefinition ws) { Debug.Assert(element != null); Debug.Assert(ws != null); XElement identityElem = element.GetOrCreateElement("identity"); WriteIdentityElement(identityElem, ws); RemoveIfEmpty(ref identityElem); XElement charactersElem = element.GetOrCreateElement("characters"); WriteCharactersElement(charactersElem, ws); RemoveIfEmpty(ref charactersElem); XElement delimitersElem = element.GetOrCreateElement("delimiters"); WriteDelimitersElement(delimitersElem, ws); RemoveIfEmpty(ref delimitersElem); XElement layoutElem = element.GetOrCreateElement("layout"); WriteLayoutElement(layoutElem, ws); RemoveIfEmpty(ref layoutElem); XElement numbersElem = element.GetOrCreateElement("numbers"); WriteNumbersElement(numbersElem, ws); RemoveIfEmpty(ref numbersElem); XElement collationsElem = element.GetOrCreateElement("collations"); WriteCollationsElement(collationsElem, ws); RemoveIfEmpty(ref collationsElem); // Can have multiple specials. Find the one with SIL namespace and external-resources. // Also handle case where we create special because writingsystem has entries to write XElement specialElem = element.NonAltElements("special").FirstOrDefault( e => !string.IsNullOrEmpty((string) e.Attribute(XNamespace.Xmlns+"sil")) && e.NonAltElement(Sil + "external-resources") != null); if (specialElem == null && (ws.Fonts.Count > 0 || ws.KnownKeyboards.Count > 0 || ws.SpellCheckDictionaries.Count > 0)) { // Create special element specialElem = GetOrCreateSpecialElement(element); } if (specialElem != null) { WriteTopLevelSpecialElements(specialElem, ws); RemoveIfEmpty(ref specialElem); } element.WriteTo(writer); } private void WriteIdentityElement(XElement identityElem, WritingSystemDefinition ws) { Debug.Assert(identityElem != null); Debug.Assert(ws != null); // Remove non-special elements to repopulate later // Preserve special because we don't recreate all its contents identityElem.NonAltElements().Where(e => e.Name != "special").Remove(); // Version is required. If VersionNumber is blank, the empty attribute is still written XElement versionElem = identityElem.GetOrCreateElement("version"); versionElem.SetAttributeValue("number", ws.VersionNumber); if (!string.IsNullOrEmpty(ws.VersionDescription)) versionElem.SetValue(ws.VersionDescription); // Write generation date with UTC so no more ambiguity on timezone identityElem.SetAttributeValue("generation", "date", ws.DateModified.ToISO8601TimeFormatWithUTCString()); WriteLanguageTagElements(identityElem, ws.LanguageTag); // Create special element if data needs to be written int index = IetfLanguageTag.GetIndexOfFirstNonCommonPrivateUseVariant(ws.Variants); string variantName = string.Empty; if (index != -1) variantName = ws.Variants[index].Name; if (!string.IsNullOrEmpty(ws.WindowsLcid) || !string.IsNullOrEmpty(ws.DefaultRegion) || !string.IsNullOrEmpty(variantName)) { XElement specialElem = GetOrCreateSpecialElement(identityElem); XElement silIdentityElem = specialElem.GetOrCreateElement(Sil + "identity"); // uid and revid attributes are left intact silIdentityElem.SetOptionalAttributeValue("windowsLCID", ws.WindowsLcid); silIdentityElem.SetOptionalAttributeValue("defaultRegion", ws.DefaultRegion); silIdentityElem.SetOptionalAttributeValue("variantName", variantName); // Move special to the end of the identity block (preserving order) specialElem.Remove(); identityElem.Add(specialElem); } } private void WriteLanguageTagElements(XElement identityElem, string languageTag) { string language, script, region, variant; IetfLanguageTag.TryGetParts(languageTag, out language, out script, out region, out variant); // language element is required identityElem.SetAttributeValue("language", "type", language); // write the rest if they have contents if (!string.IsNullOrEmpty(script)) identityElem.SetAttributeValue("script", "type", script); if (!string.IsNullOrEmpty(region)) identityElem.SetAttributeValue("territory", "type", region); if (!string.IsNullOrEmpty(variant)) identityElem.SetAttributeValue("variant", "type", variant); } private void WriteCharactersElement(XElement charactersElem, WritingSystemDefinition ws) { Debug.Assert(charactersElem != null); Debug.Assert(ws != null); // Remove exemplarCharacters and special sil:exemplarCharacters elements to repopulate later charactersElem.NonAltElements("exemplarCharacters").Remove(); XElement specialElem = charactersElem.NonAltElement("special"); if (specialElem != null) { specialElem.NonAltElements(Sil + "exemplarCharacters").Remove(); RemoveIfEmpty(ref specialElem); } foreach (CharacterSetDefinition csd in ws.CharacterSets) { XElement exemplarCharactersElem; switch (csd.Type) { // These character sets go to the normal LDML exemplarCharacters space // http://unicode.org/reports/tr35/tr35-general.html#Exemplars case "main": case "auxiliary": case "index": case "punctuation": exemplarCharactersElem = new XElement("exemplarCharacters", UnicodeSet.ToPattern(csd.Characters)); // Assume main set doesn't have an attribute type if (csd.Type != "main") exemplarCharactersElem.SetAttributeValue("type", csd.Type); charactersElem.Add(exemplarCharactersElem); break; // Numeric characters will be written in the numbers element case "numeric": break; // All others go to special Sil:exemplarCharacters default: string unicodeSet = csd.Type == "footnotes" ? string.Format("[{0}]", string.Join(" ", csd.Characters.Select(c => c.Length > 1 ? string.Format("{{{0}}}", c) : c))) : UnicodeSet.ToPattern(csd.Characters); exemplarCharactersElem = new XElement(Sil + "exemplarCharacters", unicodeSet); exemplarCharactersElem.SetAttributeValue("type", csd.Type); specialElem = GetOrCreateSpecialElement(charactersElem); specialElem.Add(exemplarCharactersElem); break; } } } private void WriteDelimitersElement(XElement delimitersElem, WritingSystemDefinition ws) { Debug.Assert(delimitersElem != null); Debug.Assert(ws != null); // Remove non-special elements to repopulate later delimitersElem.NonAltElements().Where(e => e.Name != "special").Remove(); // Level 1 normal => quotationStart and quotationEnd QuotationMark qm1 = ws.QuotationMarks.FirstOrDefault(q => q.Level == 1 && q.Type == QuotationMarkingSystemType.Normal); if (qm1 != null) { var quotationStartElem = new XElement("quotationStart", qm1.Open); var quotationEndElem = new XElement("quotationEnd", qm1.Close); delimitersElem.Add(quotationStartElem); delimitersElem.Add(quotationEndElem); } // Level 2 normal => alternateQuotationStart and alternateQuotationEnd QuotationMark qm2 = ws.QuotationMarks.FirstOrDefault(q => q.Level == 2 && q.Type == QuotationMarkingSystemType.Normal); if (qm2 != null) { var alternateQuotationStartElem = new XElement("alternateQuotationStart", qm2.Open); var alternateQuotationEndElem = new XElement("alternateQuotationEnd", qm2.Close); delimitersElem.Add(alternateQuotationStartElem); delimitersElem.Add(alternateQuotationEndElem); } // Remove special Sil:matched-pairs elements to repopulate later XElement specialElem = delimitersElem.NonAltElement("special"); XElement matchedPairsElem; if (specialElem != null) { matchedPairsElem = specialElem.NonAltElement(Sil + "matched-pairs"); if (matchedPairsElem != null) { matchedPairsElem.NonAltElements(Sil + "matched-pair").Remove(); RemoveIfEmpty(ref matchedPairsElem); } RemoveIfEmpty(ref specialElem); } foreach (var mp in ws.MatchedPairs) { var matchedPairElem = new XElement(Sil + "matched-pair"); // open and close are required matchedPairElem.SetAttributeValue("open", mp.Open); matchedPairElem.SetAttributeValue("close", mp.Close); matchedPairElem.SetAttributeValue("paraClose", mp.ParagraphClose); // optional, default to false? specialElem = GetOrCreateSpecialElement(delimitersElem); matchedPairsElem = specialElem.GetOrCreateElement(Sil + "matched-pairs"); matchedPairsElem.Add(matchedPairElem); } // Remove special Sil:punctuation-patterns elements to repopulate later XElement punctuationPatternsElem; if (specialElem != null) { punctuationPatternsElem = specialElem.NonAltElement(Sil + "punctuation-patterns"); if (punctuationPatternsElem != null) { punctuationPatternsElem.NonAltElements(Sil + "punctuation-pattern").Remove(); RemoveIfEmpty(ref punctuationPatternsElem); } RemoveIfEmpty(ref specialElem); } foreach (var pp in ws.PunctuationPatterns) { var punctuationPatternElem = new XElement(Sil + "punctuation-pattern"); // text is required punctuationPatternElem.SetAttributeValue("pattern", pp.Pattern); punctuationPatternElem.SetAttributeValue("context", PunctuationPatternContextToContext[pp.Context]); specialElem = GetOrCreateSpecialElement(delimitersElem); punctuationPatternsElem = specialElem.GetOrCreateElement(Sil + "punctuation-patterns"); punctuationPatternsElem.Add(punctuationPatternElem); } // Remove sil:quotation elements where type is blank or narrative. Also remove quotation continue elements. // These will be repopulated later XElement quotationmarksElem = null; if (specialElem != null) { quotationmarksElem = specialElem.NonAltElement(Sil + "quotation-marks"); if (quotationmarksElem != null) { quotationmarksElem.NonAltElements(Sil + "quotation").Where(e => string.IsNullOrEmpty((string) e.Attribute("type"))).Remove(); quotationmarksElem.NonAltElements(Sil + "quotation").Where(e => (string) e.Attribute("type") == "narrative").Remove(); quotationmarksElem.NonAltElements(Sil + "quotationContinue").Remove(); quotationmarksElem.NonAltElements(Sil + "alternateQuotationContinue").Remove(); RemoveIfEmpty(ref quotationmarksElem); } RemoveIfEmpty(ref specialElem); } if (qm1 != null) { var level1ContinuerElem = new XElement(Sil + "quotationContinue", qm1.Continue); specialElem = GetOrCreateSpecialElement(delimitersElem); quotationmarksElem = specialElem.GetOrCreateElement(Sil + "quotation-marks"); quotationmarksElem.Add(level1ContinuerElem); } if (qm2 != null && !string.IsNullOrEmpty(qm2.Continue)) { var level2ContinuerElem = new XElement(Sil + "alternateQuotationContinue", qm2.Continue); specialElem = GetOrCreateSpecialElement(delimitersElem); quotationmarksElem = specialElem.GetOrCreateElement(Sil + "quotation-marks"); quotationmarksElem.Add(level2ContinuerElem); } foreach (QuotationMark qm in ws.QuotationMarks) { // Level 1 and 2 normal have already been written if (!((qm.Level == 1 || qm.Level == 2) && qm.Type == QuotationMarkingSystemType.Normal)) { var quotationElem = new XElement(Sil + "quotation"); // open and level required quotationElem.SetAttributeValue("open", qm.Open); quotationElem.SetOptionalAttributeValue("close", qm.Close); quotationElem.SetOptionalAttributeValue("continue", qm.Continue); quotationElem.SetAttributeValue("level", qm.Level); // normal quotation mark can have no attribute defined. Narrative --> "narrative" quotationElem.SetOptionalAttributeValue("type", QuotationMarkingSystemTypesToQuotation[qm.Type]); specialElem = GetOrCreateSpecialElement(delimitersElem); quotationmarksElem = specialElem.GetOrCreateElement(Sil + "quotation-marks"); quotationmarksElem.Add(quotationElem); } } if ((ws.QuotationParagraphContinueType != QuotationParagraphContinueType.None) && (quotationmarksElem != null)) { quotationmarksElem.SetAttributeValue("paraContinueType", QuotationParagraphContinueTypesToQuotation[ws.QuotationParagraphContinueType]); } } private void WriteLayoutElement(XElement layoutElem, WritingSystemDefinition ws) { Debug.Assert(layoutElem != null); Debug.Assert(ws != null); // Remove characterOrder element to repopulate later XElement orientationElem = layoutElem.NonAltElement("orientation"); if (orientationElem != null) { orientationElem.NonAltElements().Where(e => e.Name == "characterOrder").Remove(); RemoveIfEmpty(ref orientationElem); } // we generally don't need to write out default values, but SLDR seems to always write characterOrder orientationElem = layoutElem.GetOrCreateElement("orientation"); XElement characterOrderElem = orientationElem.GetOrCreateElement("characterOrder"); characterOrderElem.SetValue(ws.RightToLeftScript ? "right-to-left" : "left-to-right"); // Ignore lineOrder } private void WriteNumbersElement(XElement numbersElem, WritingSystemDefinition ws) { Debug.Assert(numbersElem != null); Debug.Assert(ws != null); // Save off defaultNumberingSystem if it exists. string defaultNumberingSystem = "standard"; XElement defaultNumberingSystemElem = numbersElem.NonAltElement("defaultNumberingSystem"); if (defaultNumberingSystemElem != null && !string.IsNullOrEmpty((string) defaultNumberingSystemElem)) defaultNumberingSystem = (string) defaultNumberingSystemElem; // Remove defaultNumberingSystem and numberingSystems elements of type "numeric" to repopulate later numbersElem.NonAltElements("defaultNumberingSystem").Remove(); numbersElem.NonAltElements("numberingSystem").Where(e => (string) e.Attribute("id") == defaultNumberingSystem && (string) e.Attribute("type") == "numeric" && e.Attribute("alt") == null).Remove(); CharacterSetDefinition csd; if (ws.CharacterSets.TryGet("numeric", out csd)) { // Create defaultNumberingSystem element and add as the first child if (defaultNumberingSystemElem == null) { defaultNumberingSystemElem = new XElement("defaultNumberingSystem", defaultNumberingSystem); numbersElem.AddFirst(defaultNumberingSystemElem); } // Populate numbering system element var numberingSystemsElem = new XElement("numberingSystem"); numberingSystemsElem.SetAttributeValue("id", defaultNumberingSystem); numberingSystemsElem.SetAttributeValue("type", csd.Type); string digits = string.Join("", csd.Characters); numberingSystemsElem.SetAttributeValue("digits", digits); numbersElem.Add(numberingSystemsElem); } } private void WriteCollationsElement(XElement collationsElem, WritingSystemDefinition ws) { // Preserve exisiting collations since we don't process them all // Remove only the collations we can repopulate from the writing system collationsElem.NonAltElements("collation").Where(ce => ce.NonAltElements("special").Elements().All(se => se.Name != (Sil + "reordered"))).Remove(); // if there will be no collation elements, don't write out defaultCollation element if (!collationsElem.Elements("collation").Any() && ws.Collations.All(c => c is SystemCollationDefinition)) return; XElement defaultCollationElem = collationsElem.GetOrCreateElement("defaultCollation"); defaultCollationElem.SetValue(ws.DefaultCollationType); foreach (CollationDefinition collation in ws.Collations) WriteCollationElement(collationsElem, collation); } private void WriteCollationElement(XElement collationsElem, CollationDefinition collation) { Debug.Assert(collationsElem != null); Debug.Assert(collation != null); // SystemCollationDefinition is application-specific and not written to LDML if (collation is SystemCollationDefinition) return; var collationElem = new XElement("collation", new XAttribute("type", collation.Type)); collationsElem.Add(collationElem); string message; collation.Validate(out message); var icuCollation = collation as IcuRulesCollationDefinition; if (icuCollation != null) WriteCollationRulesFromCustomIcu(collationElem, icuCollation); var simpleCollation = collation as SimpleRulesCollationDefinition; if (simpleCollation != null) WriteCollationRulesFromCustomSimple(collationElem, simpleCollation); } private void WriteCollationRulesFromCustomIcu(XElement collationElem, IcuRulesCollationDefinition icd) { foreach (IcuCollationImport import in icd.Imports) { var importElem = new XElement("import", new XAttribute("source", import.LanguageTag)); if (!string.IsNullOrEmpty(import.Type)) importElem.Add(new XAttribute("type", import.Type)); collationElem.Add(importElem); } // If collation invalid because we couldn't parse the icu rules, write a comment to send back to SLDR if (!icd.IsValid) collationElem.Add(new XComment(string.Format("Unable to parse the ICU rules with ICU version {0}", Wrapper.IcuVersion))); // If collation valid and icu rules exist, populate icu rules if (!string.IsNullOrEmpty(icd.IcuRules)) collationElem.Add(new XElement("cr", new XCData(icd.IcuRules))); } private void WriteCollationRulesFromCustomSimple(XElement collationElem, SimpleRulesCollationDefinition scd) { // If collation valid and icu rules exist, populate icu rules if (!string.IsNullOrEmpty(scd.CollationRules)) collationElem.Add(new XElement("cr", new XCData(scd.CollationRules))); XElement specialElem = GetOrCreateSpecialElement(collationElem); // SLDR generally doesn't include needsCompiling if false specialElem.SetAttributeValue(Sil + "needsCompiling", scd.IsValid ? null : "true"); specialElem.Add(new XElement(Sil + "simple", new XCData(scd.SimpleRules))); } private void WriteTopLevelSpecialElements(XElement specialElem, WritingSystemDefinition ws) { XElement externalResourcesElem = specialElem.GetOrCreateElement(Sil + "external-resources"); WriteFontElement(externalResourcesElem, ws); WriteSpellcheckElement(externalResourcesElem, ws); WriteKeyboardElement(externalResourcesElem, ws); } private void WriteFontElement(XElement externalResourcesElem, WritingSystemDefinition ws) { Debug.Assert(externalResourcesElem != null); Debug.Assert(ws != null); // Remove sil:font elements to repopulate later externalResourcesElem.NonAltElements(Sil + "font").Remove(); foreach (FontDefinition font in ws.Fonts) { var fontElem = new XElement(Sil + "font"); fontElem.SetAttributeValue("name", font.Name); // Generate space-separated list of font roles if (font.Roles != FontRoles.Default) { var fontRoleList = new List<string>(); foreach (FontRoles fontRole in Enum.GetValues(typeof(FontRoles))) { if ((font.Roles & fontRole) != 0) fontRoleList.Add(FontRolesToRole[fontRole]); } fontElem.SetAttributeValue("types", string.Join(" ", fontRoleList)); } if (font.RelativeSize != 1.0f) fontElem.SetAttributeValue("size", font.RelativeSize); fontElem.SetOptionalAttributeValue("minversion", font.MinVersion); fontElem.SetOptionalAttributeValue("features", font.Features); fontElem.SetOptionalAttributeValue("lang", font.Language); fontElem.SetOptionalAttributeValue("otlang", font.OpenTypeLanguage); fontElem.SetOptionalAttributeValue("subset", font.Subset); // Generate space-separated list of font engines if (font.Engines != (FontEngines.Graphite | FontEngines.OpenType)) { var fontEngineList = new List<string>(); foreach (FontEngines fontEngine in Enum.GetValues(typeof (FontEngines))) { if ((font.Engines & fontEngine) != 0) fontEngineList.Add(FontEnginesToEngine[fontEngine]); } fontElem.SetAttributeValue("engines", fontEngineList.Count == 0 ? null : string.Join(" ", fontEngineList)); } foreach (var url in font.Urls) fontElem.Add(new XElement(Sil + "url", url)); externalResourcesElem.Add(fontElem); } } private void WriteSpellcheckElement(XElement externalResourcesElem, WritingSystemDefinition ws) { Debug.Assert(externalResourcesElem != null); Debug.Assert(ws != null); // Remove sil:spellcheck elements to repopulate later externalResourcesElem.NonAltElements(Sil + "spellcheck").Remove(); foreach (SpellCheckDictionaryDefinition scd in ws.SpellCheckDictionaries) { var scElem = new XElement(Sil + "spellcheck"); scElem.SetAttributeValue("type", SpellCheckDictionaryFormatsToSpellCheck[scd.Format]); // URL elements foreach (var url in scd.Urls) { var urlElem = new XElement(Sil + "url", url); scElem.Add(urlElem); } externalResourcesElem.Add(scElem); } } private void WriteKeyboardElement(XElement externalResourcesElem, WritingSystemDefinition ws) { Debug.Assert(externalResourcesElem != null); Debug.Assert(ws != null); // Remove sil:kbd elements to repopulate later externalResourcesElem.NonAltElements(Sil + "kbd").Remove(); // Don't include unknown system keyboard definitions foreach (IKeyboardDefinition keyboard in ws.KnownKeyboards.Where(kbd=>kbd.Format != KeyboardFormat.Unknown)) { var kbdElem = new XElement(Sil + "kbd"); // id required kbdElem.SetAttributeValue("id", keyboard.Id); if (!string.IsNullOrEmpty(keyboard.Id)) { kbdElem.SetAttributeValue("type", KeyboardFormatToKeyboard[keyboard.Format]); foreach (var url in keyboard.Urls) { var urlElem = new XElement(Sil + "url", url); kbdElem.Add(urlElem); } } externalResourcesElem.Add(kbdElem); } } } }
// 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.Globalization; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public class SortedListTests : RemoteExecutorTestBase { [Fact] public void Ctor_Empty() { var sortList = new SortedList(); Assert.Equal(0, sortList.Count); Assert.Equal(0, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Ctor_Int(int initialCapacity) { var sortList = new SortedList(initialCapacity); Assert.Equal(0, sortList.Count); Assert.Equal(initialCapacity, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0 } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Ctor_IComparer_Int(int initialCapacity) { var sortList = new SortedList(new CustomComparer(), initialCapacity); Assert.Equal(0, sortList.Count); Assert.Equal(initialCapacity, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0 } [Fact] public void Ctor_IComparer() { var sortList = new SortedList(new CustomComparer()); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IComparer_Null() { var sortList = new SortedList((IComparer)null); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(0, false)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(100, false)] public void Ctor_IDictionary(int count, bool sorted) { var hashtable = new Hashtable(); if (sorted) { // Create a hashtable in the correctly sorted order for (int i = 0; i < count; i++) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } else { // Create a hashtable in the wrong order and make sure it is sorted for (int i = count - 1; i >= 0; i--) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } var sortList = new SortedList(hashtable); Assert.Equal(count, sortList.Count); Assert.True(sortList.Capacity >= sortList.Count); for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i.ToString("D2"); Assert.Equal(sortList.GetByIndex(i), value); Assert.Equal(hashtable[key], sortList[key]); } Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(0, false)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(100, false)] public void Ctor_IDictionary_IComparer(int count, bool sorted) { var hashtable = new Hashtable(); if (sorted) { // Create a hashtable in the correctly sorted order for (int i = count - 1; i >= 0; i--) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } else { // Create a hashtable in the wrong order and make sure it is sorted for (int i = 0; i < count; i++) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } var sortList = new SortedList(hashtable, new CustomComparer()); Assert.Equal(count, sortList.Count); Assert.True(sortList.Capacity >= sortList.Count); for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i.ToString("D2"); string expectedValue = "Value_" + (count - i - 1).ToString("D2"); Assert.Equal(sortList.GetByIndex(i), expectedValue); Assert.Equal(hashtable[key], sortList[key]); } Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IDictionary_IComparer_Null() { var sortList = new SortedList(new Hashtable(), null); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttribute_Empty() { Assert.Equal("Count = 0", DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList())); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttribute_NormalList() { var list = new SortedList() { { "a", 1 }, { "b", 2 } }; DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list); PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items"); object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance); Assert.Equal(list.Count, items.Length); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttribute_SynchronizedList() { var list = SortedList.Synchronized(new SortedList() { { "a", 1 }, { "b", 2 } }); DebuggerAttributeInfo debuggerAttribute = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), list); PropertyInfo infoProperty = debuggerAttribute.Properties.Single(property => property.Name == "Items"); object[] items = (object[])infoProperty.GetValue(debuggerAttribute.Instance); Assert.Equal(list.Count, items.Length); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttribute_NullSortedList_ThrowsArgumentNullException() { bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "This test intentionally reflects on an internal member of SortedList. Cannot do that on UaoAot.")] public void EnsureCapacity_NewCapacityLessThanMin_CapsToMaxArrayLength() { // A situation like this occurs for very large lengths of SortedList. // To avoid allocating several GBs of memory and making this test run for a very // long time, we can use reflection to invoke SortedList's growth method manually. // This is relatively brittle, as it relies on accessing a private method via reflection // that isn't guaranteed to be stable. const int InitialCapacity = 10; const int MinCapacity = InitialCapacity * 2 + 1; var sortedList = new SortedList(InitialCapacity); MethodInfo ensureCapacity = sortedList.GetType().GetMethod("EnsureCapacity", BindingFlags.NonPublic | BindingFlags.Instance); ensureCapacity.Invoke(sortedList, new object[] { MinCapacity }); Assert.Equal(MinCapacity, sortedList.Capacity); } [Fact] public void Add() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; sortList2.Add(key, value); Assert.True(sortList2.ContainsKey(key)); Assert.True(sortList2.ContainsValue(value)); Assert.Equal(i, sortList2.IndexOfKey(key)); Assert.Equal(i, sortList2.IndexOfValue(value)); Assert.Equal(i + 1, sortList2.Count); } }); } [Fact] public void Add_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null AssertExtensions.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Clear(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { sortList2.Clear(); Assert.Equal(0, sortList2.Count); sortList2.Clear(); Assert.Equal(0, sortList2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void Clone(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { SortedList sortListClone = (SortedList)sortList2.Clone(); Assert.Equal(sortList2.Count, sortListClone.Count); Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize); Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly); for (int i = 0; i < sortListClone.Count; i++) { Assert.Equal(sortList2[i], sortListClone[i]); } }); } [Fact] public void Clone_IsShallowCopy() { var sortList = new SortedList(); for (int i = 0; i < 10; i++) { sortList.Add(i, new Foo()); } SortedList sortListClone = (SortedList)sortList.Clone(); string stringValue = "Hello World"; for (int i = 0; i < 10; i++) { Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue); } // Now we remove an object from the original list, but this should still be present in the clone sortList.RemoveAt(9); Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue); stringValue = "Good Bye"; ((Foo)sortList[0]).StringValue = stringValue; Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue); Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue); // If we change the object, of course, the previous should not happen sortListClone[0] = new Foo(); Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue); stringValue = "Hello World"; Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue); } [Fact] public void ContainsKey() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { string key = "Key_" + i; sortList2.Add(key, i); Assert.True(sortList2.Contains(key)); Assert.True(sortList2.ContainsKey(key)); } Assert.False(sortList2.ContainsKey("Non_Existent_Key")); for (int i = 0; i < sortList2.Count; i++) { string removedKey = "Key_" + i; sortList2.Remove(removedKey); Assert.False(sortList2.Contains(removedKey)); Assert.False(sortList2.ContainsKey(removedKey)); } }); } [Fact] public void ContainsKey_NullKey_ThrowsArgumentNullException() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null }); } [Fact] public void ContainsValue() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { sortList2.Add(i, "Value_" + i); Assert.True(sortList2.ContainsValue("Value_" + i)); } Assert.False(sortList2.ContainsValue("Non_Existent_Value")); for (int i = 0; i < sortList2.Count; i++) { sortList2.Remove(i); Assert.False(sortList2.ContainsValue("Value_" + i)); } }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public void CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { var array = new object[index + count]; sortList2.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { int actualIndex = i - index; string key = "Key_" + actualIndex.ToString("D2"); string value = "Value_" + actualIndex; DictionaryEntry entry = (DictionaryEntry)array[i]; Assert.Equal(key, entry.Key); Assert.Equal(value, entry.Value); } }); } [Fact] public void CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional AssertExtensions.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0 AssertExtensions.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Fact] public void GetByIndex() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { Assert.Equal(i, sortList2.GetByIndex(i)); int i2 = sortList2.IndexOfKey(i); Assert.Equal(i, i2); i2 = sortList2.IndexOfValue(i); Assert.Equal(i, i2); } }); } [Fact] public void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetEnumerator_IDictionaryEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator()); IDictionaryEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(enumerator.Current, enumerator.Entry); Assert.Equal(enumerator.Entry.Key, enumerator.Key); Assert.Equal(enumerator.Entry.Value, enumerator.Value); Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key); Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public void GetEnumerator_IDictionaryEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IDictionaryEnumerator enumerator = sortList2.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw if index < 0 enumerator = sortList2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw after resetting enumerator = sortList2.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw if the current index is >= count enumerator = sortList2.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetEnumerator_IEnumerator(int count) { SortedList sortList = Helpers.CreateIntSortedList(count); Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator()); IEnumerator enumerator = sortList.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current; Assert.Equal(sortList.GetKey(counter), dictEntry.Key); Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } } [Fact] public void GetEnumerator_StartOfEnumeration_Clone() { SortedList sortedList = Helpers.CreateIntSortedList(10); IDictionaryEnumerator enumerator = sortedList.GetEnumerator(); ICloneable cloneableEnumerator = (ICloneable)enumerator; IDictionaryEnumerator clonedEnumerator = (IDictionaryEnumerator)cloneableEnumerator.Clone(); Assert.NotSame(enumerator, clonedEnumerator); // Cloned and original enumerators should enumerate separately. Assert.True(enumerator.MoveNext()); Assert.Equal(sortedList[0], enumerator.Value); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(sortedList[0], enumerator.Value); Assert.Equal(sortedList[0], clonedEnumerator.Value); // Cloned and original enumerators should enumerate in the same sequence. for (int i = 1; i < sortedList.Count; i++) { Assert.True(enumerator.MoveNext()); Assert.NotEqual(enumerator.Current, clonedEnumerator.Current); Assert.True(clonedEnumerator.MoveNext()); Assert.Equal(enumerator.Current, clonedEnumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Equal(sortedList[sortedList.Count - 1], clonedEnumerator.Value); Assert.False(clonedEnumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Value); Assert.Throws<InvalidOperationException>(() => clonedEnumerator.Value); } [Fact] public void GetEnumerator_InMiddleOfEnumeration_Clone() { SortedList sortedList = Helpers.CreateIntSortedList(10); IEnumerator enumerator = sortedList.GetEnumerator(); enumerator.MoveNext(); ICloneable cloneableEnumerator = (ICloneable)enumerator; // Cloned and original enumerators should start at the same spot, even // if the original is in the middle of enumeration. IEnumerator clonedEnumerator = (IEnumerator)cloneableEnumerator.Clone(); Assert.Equal(enumerator.Current, clonedEnumerator.Current); for (int i = 0; i < sortedList.Count - 1; i++) { Assert.True(clonedEnumerator.MoveNext()); } Assert.False(clonedEnumerator.MoveNext()); } [Fact] public void GetEnumerator_IEnumerator_Invalid() { SortedList sortList = Helpers.CreateIntSortedList(100); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator(); enumerator.MoveNext(); sortList.Add(101, 101); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current throws if index < 0 enumerator = sortList.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throw after resetting enumerator = sortList.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throw if the current index is >= count enumerator = sortList.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetKeyList(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys1 = sortList2.GetKeyList(); IList keys2 = sortList2.GetKeyList(); // Test we have copied the correct keys Assert.Equal(count, keys1.Count); Assert.Equal(count, keys2.Count); for (int i = 0; i < keys1.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(key, keys1[i]); Assert.Equal(key, keys2[i]); Assert.True(sortList2.ContainsKey(keys1[i])); } }); } [Fact] public void GetKeyList_IsSameAsKeysProperty() { var sortList = Helpers.CreateIntSortedList(10); Assert.Same(sortList.GetKeyList(), sortList.Keys); } [Fact] public void GetKeyList_IListProperties() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.True(keys.IsReadOnly); Assert.True(keys.IsFixedSize); Assert.False(keys.IsSynchronized); Assert.Equal(sortList2.SyncRoot, keys.SyncRoot); }); } [Fact] public void GetKeyList_Contains() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); for (int i = 0; i < keys.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.True(keys.Contains(key)); } Assert.False(keys.Contains("Key_101")); // No such key }); } [Fact] public void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type }); } [Fact] public void GetKeyList_IndexOf() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); for (int i = 0; i < keys.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(i, keys.IndexOf(key)); } Assert.Equal(-1, keys.IndexOf("Key_101")); }); } [Fact] public void GetKeyList_IndexOf_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); AssertExtensions.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public void GetKeyList_CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { object[] array = new object[index + count]; IList keys = sortList2.GetKeyList(); keys.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(keys[i - index], array[i]); } }); } [Fact] public void GetKeyList_CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => keys.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => keys.CopyTo(new object[100], -1)); // Index + list.Count > array.Count AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => keys.CopyTo(new object[150], 51)); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetKeyList_GetEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator()); IEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { object key = keys[counter]; DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal(key, entry.Key); Assert.Equal(sortList2[key], entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public void GetKeyList_GetEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IEnumerator enumerator = keys.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current etc. throw if index < 0 enumerator = keys.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw after resetting enumerator = keys.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw if the current index is >= count enumerator = keys.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<NotSupportedException>(() => keys.Add(101)); Assert.Throws<NotSupportedException>(() => keys.Clear()); Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101)); Assert.Throws<NotSupportedException>(() => keys.Remove(1)); Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => keys[0] = 101); }); } [Theory] [InlineData(0)] [InlineData(100)] public void GetKey(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key))); } }); } [Fact] public void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetValueList(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values1 = sortList2.GetValueList(); IList values2 = sortList2.GetValueList(); // Test we have copied the correct values Assert.Equal(count, values1.Count); Assert.Equal(count, values2.Count); for (int i = 0; i < values1.Count; i++) { string value = "Value_" + i; Assert.Equal(value, values1[i]); Assert.Equal(value, values2[i]); Assert.True(sortList2.ContainsValue(values2[i])); } }); } [Fact] public void GetValueList_IsSameAsValuesProperty() { var sortList = Helpers.CreateIntSortedList(10); Assert.Same(sortList.GetValueList(), sortList.Values); } [Fact] public void GetValueList_IListProperties() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.True(values.IsReadOnly); Assert.True(values.IsFixedSize); Assert.False(values.IsSynchronized); Assert.Equal(sortList2.SyncRoot, values.SyncRoot); }); } [Fact] public void GetValueList_Contains() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); for (int i = 0; i < values.Count; i++) { string value = "Value_" + i; Assert.True(values.Contains(value)); } // No such value Assert.False(values.Contains("Value_101")); Assert.False(values.Contains(101)); Assert.False(values.Contains(null)); }); } [Fact] public void GetValueList_IndexOf() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); for (int i = 0; i < values.Count; i++) { string value = "Value_" + i; Assert.Equal(i, values.IndexOf(value)); } Assert.Equal(-1, values.IndexOf(101)); }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public void GetValueList_CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { object[] array = new object[index + count]; IList values = sortList2.GetValueList(); values.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(values[i - index], array[i]); } }); } [Fact] public void GetValueList_CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => values.CopyTo(null, 0)); // Array is null AssertExtensions.Throws<ArgumentException>("array", null, () => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional -- in netfx ParamName is null AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0 AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public void GetValueList_GetEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.NotSame(values.GetEnumerator(), values.GetEnumerator()); IEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { object key = values[counter]; DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal(key, entry.Key); Assert.Equal(sortList2[key], entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public void ValueList_GetEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IEnumerator enumerator = values.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current etc. throw if index < 0 enumerator = values.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw after resetting enumerator = values.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw if the current index is >= count enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.Throws<NotSupportedException>(() => values.Add(101)); Assert.Throws<NotSupportedException>(() => values.Clear()); Assert.Throws<NotSupportedException>(() => values.Insert(0, 101)); Assert.Throws<NotSupportedException>(() => values.Remove(1)); Assert.Throws<NotSupportedException>(() => values.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => values[0] = 101); }); } [Fact] public void IndexOfKey() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; int index = sortList2.IndexOfKey(key); Assert.Equal(i, index); Assert.Equal(value, sortList2.GetByIndex(index)); } Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key")); string removedKey = "Key_01"; sortList2.Remove(removedKey); Assert.Equal(-1, sortList2.IndexOfKey(removedKey)); }); } [Fact] public void IndexOfKey_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null }); } [Fact] public void IndexOfValue() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { string value = "Value_" + i; int index = sortList2.IndexOfValue(value); Assert.Equal(i, index); Assert.Equal(value, sortList2.GetByIndex(index)); } Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value")); string removedKey = "Key_01"; string removedValue = "Value_1"; sortList2.Remove(removedKey); Assert.Equal(-1, sortList2.IndexOfValue(removedValue)); Assert.Equal(-1, sortList2.IndexOfValue(null)); sortList2.Add("Key_101", null); Assert.NotEqual(-1, sortList2.IndexOfValue(null)); }); } [Fact] public void IndexOfValue_SameValue() { var sortList1 = new SortedList(); sortList1.Add("Key_0", "Value_0"); sortList1.Add("Key_1", "Value_Same"); sortList1.Add("Key_2", "Value_Same"); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Equal(1, sortList2.IndexOfValue("Value_Same")); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(4)] [InlineData(5000)] public void Capacity_Get_Set(int capacity) { var sortList = new SortedList(); sortList.Capacity = capacity; Assert.Equal(capacity, sortList.Capacity); // Ensure nothing changes if we set capacity to the same value again sortList.Capacity = capacity; Assert.Equal(capacity, sortList.Capacity); } [Fact] public void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count }); } [Fact] public void Capacity_Set_Invalid() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0 }); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotIntMaxValueArrayIndexSupported))] public void Capacity_Excessive() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] public void Item_Get(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; Assert.Equal(value, sortList2[key]); } Assert.Null(sortList2["No Such Key"]); string removedKey = "Key_01"; sortList2.Remove(removedKey); Assert.Null(sortList2[removedKey]); }); } [Fact] public void Item_Get_DifferentCulture() { RemoteInvoke(() => { var sortList = new SortedList(); try { var cultureNames = new string[] { "cs-CZ","da-DK","de-DE","el-GR","en-US", "es-ES","fi-FI","fr-FR","hu-HU","it-IT", "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL", "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR", "zh-CN","zh-HK","zh-TW" }; var installedCultures = new CultureInfo[cultureNames.Length]; var cultureDisplayNames = new string[installedCultures.Length]; int uniqueDisplayNameCount = 0; foreach (string cultureName in cultureNames) { var culture = new CultureInfo(cultureName); installedCultures[uniqueDisplayNameCount] = culture; cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName; sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture); uniqueDisplayNameCount++; } // In Czech ch comes after h if the comparer changes based on the current culture of the thread // we will not be able to find some items CultureInfo.CurrentCulture = new CultureInfo("cs-CZ"); for (int i = 0; i < uniqueDisplayNameCount; i++) { Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]); } } catch (CultureNotFoundException) { } return SuccessExitCode; }).Dispose(); } [Fact] public void Item_Set() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Change existing keys for (int i = 0; i < sortList2.Count; i++) { sortList2[i] = i + 1; Assert.Equal(i + 1, sortList2[i]); // Make sure nothing bad happens when we try to set the key to its current valeu sortList2[i] = i + 1; Assert.Equal(i + 1, sortList2[i]); } // Add new keys sortList2[101] = 2048; Assert.Equal(2048, sortList2[101]); sortList2[102] = null; Assert.Equal(null, sortList2[102]); }); } [Fact] public void Item_Set_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null }); } [Fact] public void RemoveAt() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Remove from end for (int i = sortList2.Count - 1; i >= 0; i--) { sortList2.RemoveAt(i); Assert.False(sortList2.ContainsKey(i)); Assert.False(sortList2.ContainsValue(i)); Assert.Equal(i, sortList2.Count); } }); } [Fact] public void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count }); } [Fact] public void Remove() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Remove from the end for (int i = sortList2.Count - 1; i >= 0; i--) { sortList2.Remove(i); Assert.False(sortList2.ContainsKey(i)); Assert.False(sortList2.ContainsValue(i)); Assert.Equal(i, sortList2.Count); } sortList2.Remove(101); // No such key }); } [Fact] public void Remove_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null }); } [Fact] public void SetByIndex() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { sortList2.SetByIndex(i, i + 1); Assert.Equal(i + 1, sortList2.GetByIndex(i)); } }); } [Fact] public void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeExeption() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count }); } [Fact] public void Synchronized_IsSynchronized() { SortedList sortList = SortedList.Synchronized(new SortedList()); Assert.True(sortList.IsSynchronized); } [Fact] public void Synchronized_NullList_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null } [Fact] public void TrimToSize() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 10; i++) { sortList2.RemoveAt(0); } sortList2.TrimToSize(); Assert.Equal(sortList2.Count, sortList2.Capacity); sortList2.Clear(); sortList2.TrimToSize(); Assert.Equal(0, sortList2.Capacity); }); } private class Foo { public string StringValue { get; set; } = "Hello World"; } private class CustomComparer : IComparer { public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString()); } } public class SortedList_SyncRootTests { private SortedList _sortListDaughter; private SortedList _sortListGrandDaughter; private const int NumberOfElements = 100; [Fact] [OuterLoop] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "https://github.com/dotnet/corefx/pull/34339")] // Changed behavior public void GetSyncRootBasic() { // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother SortedList // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var sortListMother = new SortedList(); for (int i = 0; i < NumberOfElements; i++) { sortListMother.Add("Key_" + i, "Value_" + i); } Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(SortedList)); SortedList sortListSon = SortedList.Synchronized(sortListMother); _sortListGrandDaughter = SortedList.Synchronized(sortListSon); _sortListDaughter = SortedList.Synchronized(sortListMother); Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot); Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot); Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot); Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot); Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot); //we are going to rumble with the SortedLists with some threads var workers = new Task[4]; for (int i = 0; i < workers.Length; i += 2) { var name = "Thread_worker_" + i; var action1 = new Action(() => AddMoreElements(name)); var action2 = new Action(RemoveElements); workers[i] = Task.Run(action1); workers[i + 1] = Task.Run(action2); } Task.WaitAll(workers); // Checking time // Now lets see how this is done. // Either there are some elements or none var sortListPossible = new SortedList(); for (int i = 0; i < NumberOfElements; i++) { sortListPossible.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < workers.Length; i++) { sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } //lets check the values if IDictionaryEnumerator enumerator = sortListMother.GetEnumerator(); while (enumerator.MoveNext()) { Assert.True(sortListPossible.ContainsKey(enumerator.Key)); Assert.True(sortListPossible.ContainsValue(enumerator.Value)); } } private void AddMoreElements(string threadName) { _sortListGrandDaughter.Add("Key_" + threadName, threadName); } private void RemoveElements() { _sortListDaughter.Clear(); } } }
using System; using System.Data; using FirebirdSql.Data.FirebirdClient; namespace MyMeta.Firebird { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IDomains))] #endif public class FirebirdDomains : Domains { public FirebirdDomains() { } internal DataColumn f_TypeNameComplete = null; override internal void LoadAll() { try { FbConnection cn = new FirebirdSql.Data.FirebirdClient.FbConnection(this._dbRoot.ConnectionString); cn.Open(); DataTable metaData = cn.GetSchema("Domains", null); cn.Close(); if(metaData.Columns.Contains("DOMAIN_DATA_TYPE")) { metaData.Columns["DOMAIN_DATA_TYPE"].ColumnName = "DATA_TYPE"; } PopulateArray(metaData); LoadExtraData(cn); } catch(Exception ex) { string m = ex.Message; } } private void LoadExtraData(FbConnection cn) { try { int dialect = 1; try { FbConnectionStringBuilder cnString = new FbConnectionStringBuilder(cn.ConnectionString); dialect = cnString.Dialect; } catch {} string select = "select f.rdb$field_name, f.rdb$field_scale AS SCALE, f.rdb$field_type as FTYPE, f.rdb$field_sub_type AS SUBTYPE, f.rdb$dimensions AS DIM from rdb$fields f, rdb$types t where t.rdb$field_name='RDB$FIELD_TYPE' and f.rdb$field_type=t.rdb$type and not f.rdb$field_name starting with 'RDB$' ORDER BY f.rdb$field_name;"; // Column Data FbDataAdapter adapter = new FbDataAdapter(select, cn); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); // Dimension Data string dimSelect = "select r.rdb$field_name AS Name, d.rdb$dimension as DIM, d.rdb$lower_bound as L, d.rdb$upper_bound as U from rdb$fields f, rdb$field_dimensions d, rdb$relation_fields r where f.rdb$field_name = d.rdb$field_name and f.rdb$field_name=r.rdb$field_source and not f.rdb$field_name starting with 'RDB$' order by d.rdb$dimension;"; FbDataAdapter dimAdapter = new FbDataAdapter(dimSelect, cn); DataTable dimTable = new DataTable(); dimAdapter.Fill(dimTable); if(this._array.Count > 0) { Domain dom = this._array[0] as Domain; f_TypeNameComplete = new DataColumn("TYPE_NAME_COMPLETE", typeof(string)); dom._row.Table.Columns.Add(f_TypeNameComplete); short ftype = 0; short dim = 0; DataRowCollection rows = dataTable.Rows; int count = this._array.Count; Domain d = null; for( int index = 0; index < count; index++) { d = (Domain)this[index]; if(d.DataTypeName == "bigint") { d._row["DATA_TYPE"] = "BIGINT"; d._row["TYPE_NAME_COMPLETE"] = "BIGINT"; continue; } // Step 1: DataTypeName ftype = (short)rows[index]["FTYPE"]; switch(ftype) { case 7: d._row["DATA_TYPE"] = "SMALLINT"; break; case 8: d._row["DATA_TYPE"] = "INTEGER"; break; case 9: d._row["DATA_TYPE"] = "QUAD"; break; case 10: d._row["DATA_TYPE"] = "FLOAT"; break; case 11: d._row["DATA_TYPE"] = "DOUBLE PRECISION"; break; case 12: d._row["DATA_TYPE"] = "DATE"; break; case 13: d._row["DATA_TYPE"] = "TIME"; break; case 14: d._row["DATA_TYPE"] = "CHAR"; break; case 16: d._row["DATA_TYPE"] = "NUMERIC"; break; case 27: d._row["DATA_TYPE"] = "DOUBLE PRECISION"; break; // case 35: // d._row["DATA_TYPE"] = "DATE"; // break; case 35: if(dialect > 2) { d._row["DATA_TYPE"] = "TIMESTAMP"; } else { d._row["DATA_TYPE"] = "DATE"; } break; case 37: d._row["DATA_TYPE"] = "VARCHAR"; break; case 40: d._row["DATA_TYPE"] = "CSTRING"; break; case 261: short subtype = (short)rows[index]["SUBTYPE"]; switch(subtype) { case 0: d._row["DATA_TYPE"] = "BLOB(BINARY)"; break; case 1: d._row["DATA_TYPE"] = "BLOB(TEXT)"; break; default: d._row["DATA_TYPE"] = "BLOB(UNKNOWN)"; break; } break; } short scale = (short)rows[index]["SCALE"]; if(scale < 0) { d._row["DATA_TYPE"] = "NUMERIC"; d._row["NUMERIC_SCALE"] = Math.Abs(scale); } object o = null; // Step 2: DataTypeNameComplete string s = d._row["DATA_TYPE"] as string; switch(s) { case "VARCHAR": case "CHAR": d._row["TYPE_NAME_COMPLETE"] = s + "(" + d.CharacterMaxLength + ")"; break; case "NUMERIC": switch((int)d._row["DOMAIN_SIZE"]) { case 2: d._row["TYPE_NAME_COMPLETE"] = s + "(4, " + d.NumericScale.ToString() + ")"; break; case 4: d._row["TYPE_NAME_COMPLETE"] = s + "(9, " + d.NumericScale.ToString() + ")"; break; case 8: d._row["TYPE_NAME_COMPLETE"] = s + "(15, " + d.NumericScale.ToString() + ")"; break; default: d._row["TYPE_NAME_COMPLETE"] = "NUMERIC(18,0)"; break; } break; case "BLOB(TEXT)": case "BLOB(BINARY)": d._row["TYPE_NAME_COMPLETE"] = "BLOB"; break; default: d._row["TYPE_NAME_COMPLETE"] = s; break; } s = d._row["TYPE_NAME_COMPLETE"] as string; dim = 0; o = rows[index]["DIM"]; if(o != DBNull.Value) { dim = (short)o; } if(dim > 0) { dimTable.DefaultView.RowFilter = "Name = '" + d.Name + "'"; dimTable.DefaultView.Sort = "DIM"; string a = "["; bool bFirst = true; foreach(DataRowView vrow in dimTable.DefaultView) { DataRow row = vrow.Row; if(!bFirst) a += ","; a += row["L"].ToString() + ":" + row["U"].ToString(); bFirst = false; } a += "]"; d._row["TYPE_NAME_COMPLETE"] = s + a; d._row["DATA_TYPE"] = d._row["DATA_TYPE"] + ":A"; } } } } catch(Exception ex) { string e = ex.Message; } } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Text; namespace OpenADK.Library.Tools.XPath { /// <summary> /// Contains built-in functions that are automatically registered with /// SifXPathContext using the namespace prefix "adk" /// </summary> public class AdkFunctions { /// <summary> /// Returns the string converted to all Upper case /// </summary> /// <param name="str"> The string to convert to upper case, or null</param> /// <returns></returns> public static String toUpperCase( String str ) { if ( str == null ) { return null; } return str.ToUpper(); } /// <summary> /// Returns the string converted to all Lower case /// </summary> /// <param name="str">The string to convert to lower case, or null</param> /// <returns></returns> public static String toLowerCase( String str ) { if ( str == null ) { return null; } return str.ToLower(); } /// <summary> /// Returns true if the two strings are equal, ignoring any differences in /// case /// </summary> /// <param name="str1"></param> /// <param name="str2"></param> /// <returns>true if both strings are equal, differing only by the case of the /// letters</returns> public static bool equalsIgnoreCase( String str1, String str2 ) { if ( str1 == null ) { return str2 == null; } return String.Compare( str1, str2, true ) == 0; } /// <summary> /// Pads the beginning of the Source string with the specified PadChar /// character so that the source string is at least Width characters in length. /// </summary> /// <remarks> /// If the Source string is already equal to or greater than Width, /// no action is taken. /// </remarks> /// <param name="source">The string to start with</param> /// <param name="padding">The string to use for padding (only the first char will be used)</param> /// <param name="width">The length the final string should be</param> /// <returns>The padded string or 'Null' if the source is null</returns> public static String padBegin( String source, String padding, int width ) { return pad( source, padding, width, true ); } /// <summary> /// Pads the end of the Source string with the specified PadChar /// character so that the source string is at least Width characters in length. /// </summary> /// <remarks> /// If the Source string is already equal to or greater than Width, /// no action is taken. /// </remarks> /// <param name="source">The string to start with</param> /// <param name="padding">The string to use for padding (only the first char will be used)</param> /// <param name="width">The length the final string should be</param> /// <returns>The padded string or 'Null' if the source is null</returns> public static String padEnd( String source, String padding, int width ) { return pad( source, padding, width, false ); } private static String pad( String source, String pad, int width, bool padBeginning ) { if ( source == null ) { return null; } if ( source.Length >= width || pad == null ) { return source; } StringBuilder str = new StringBuilder( width ); char padChar = pad[0]; int padLength = width - source.Length; if ( padBeginning ) { // put the padding on the beginning for ( int i = 0; i < padLength; i++ ) { str.Append( padChar ); } str.Append( source ); } else { // put the padding on the end str.Append( source ); for ( int i = 0; i < padLength; i++ ) { str.Append( padChar ); } } return str.ToString(); } /// <summary> /// Converts the source string to 'Proper' case. In general, this means /// capitalizing the first letter of each word. However, in some cases, such /// as O'Reilly, letters within the word will be capitalized as well. /// </summary> /// <param name="source"></param> /// <returns></returns> public static String toProperCase( String source ) { if ( source == null ) { return null; } try { StringBuilder b = new StringBuilder( source.Trim() ); int indexIntoWord = 1; for ( int i = 0; i < b.Length; i++ ) { char c = b[i]; switch ( c ) { case ' ': case '\t': case '\r': case '\n': indexIntoWord = 0; break; case '\'': if ( indexIntoWord < 3 ) { indexIntoWord = 0; } break; default: if ( indexIntoWord == 1 ) { b[i] = Char.ToUpper( c ); } else { b[i] = Char.ToLower( c ); } break; } indexIntoWord++; } return b.ToString(); } catch ( Exception ) { return source; } } /// <summary> /// Used internally by the ADK /// </summary> /// <returns></returns> public static bool x() { return true; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Web.Services3; using WebsitePanel.EnterpriseServer; using WebsitePanel.EnterpriseServer.HostedSolution; namespace WebsitePanel.FixDefaultPublicFolderMailbox { /// <summary> /// ES Proxy class /// </summary> public class ES { private static ServerContext serverContext = null; public static void InitializeServices(ServerContext context) { serverContext = context; } public static ES Services { get { return new ES(); } } public esSystem System { get { return GetCachedProxy<esSystem>(); } } public esApplicationsInstaller ApplicationsInstaller { get { return GetCachedProxy<esApplicationsInstaller>(); } } public esAuditLog AuditLog { get { return GetCachedProxy<esAuditLog>(); } } public esAuthentication Authentication { get { return GetCachedProxy<esAuthentication>(false); } } public esComments Comments { get { return GetCachedProxy<esComments>(); } } public esDatabaseServers DatabaseServers { get { return GetCachedProxy<esDatabaseServers>(); } } public esFiles Files { get { return GetCachedProxy<esFiles>(); } } public esFtpServers FtpServers { get { return GetCachedProxy<esFtpServers>(); } } public esMailServers MailServers { get { return GetCachedProxy<esMailServers>(); } } public esOperatingSystems OperatingSystems { get { return GetCachedProxy<esOperatingSystems>(); } } public esPackages Packages { get { return GetCachedProxy<esPackages>(); } } public esScheduler Scheduler { get { return GetCachedProxy<esScheduler>(); } } public esTasks Tasks { get { return GetCachedProxy<esTasks>(); } } public esServers Servers { get { return GetCachedProxy<esServers>(); } } public esStatisticsServers StatisticsServers { get { return GetCachedProxy<esStatisticsServers>(); } } public esUsers Users { get { return GetCachedProxy<esUsers>(); } } public esWebServers WebServers { get { return GetCachedProxy<esWebServers>(); } } public esSharePointServers SharePointServers { get { return GetCachedProxy<esSharePointServers>(); } } public esImport Import { get { return GetCachedProxy<esImport>(); } } public esBackup Backup { get { return GetCachedProxy<esBackup>(); } } public esExchangeServer ExchangeServer { get { return GetCachedProxy<esExchangeServer>(); } } public esOrganizations Organizations { get { return GetCachedProxy<esOrganizations>(); } } protected ES() { } protected virtual T GetCachedProxy<T>() { return GetCachedProxy<T>(true); } protected virtual T GetCachedProxy<T>(bool secureCalls) { if (serverContext == null) { throw new Exception("Server context is not specified"); } Type t = typeof(T); string key = t.FullName + ".ServiceProxy"; T proxy = (T)Activator.CreateInstance(t); object p = proxy; // configure proxy EnterpriseServerProxyConfigurator cnfg = new EnterpriseServerProxyConfigurator(); cnfg.EnterpriseServerUrl = serverContext.Server; if (secureCalls) { cnfg.Username = serverContext.Username; cnfg.Password = serverContext.Password; } cnfg.Configure((WebServicesClientProtocol)p); return proxy; } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Client-side channel credentials. Used for creation of a secure channel. /// </summary> public abstract class ChannelCredentials { static readonly ChannelCredentials InsecureInstance = new InsecureCredentialsImpl(); readonly Lazy<ChannelCredentialsSafeHandle> cachedNativeCredentials; /// <summary> /// Creates a new instance of channel credentials /// </summary> public ChannelCredentials() { // Native credentials object need to be kept alive once initialized for subchannel sharing to work correctly // with secure connections. See https://github.com/grpc/grpc/issues/15207. // We rely on finalizer to clean up the native portion of ChannelCredentialsSafeHandle after the ChannelCredentials // instance becomes unused. this.cachedNativeCredentials = new Lazy<ChannelCredentialsSafeHandle>(() => CreateNativeCredentials()); } /// <summary> /// Returns instance of credentials that provides no security and /// will result in creating an unsecure channel with no encryption whatsoever. /// </summary> public static ChannelCredentials Insecure { get { return InsecureInstance; } } /// <summary> /// Creates a new instance of <c>ChannelCredentials</c> class by composing /// given channel credentials with call credentials. /// </summary> /// <param name="channelCredentials">Channel credentials.</param> /// <param name="callCredentials">Call credentials.</param> /// <returns>The new composite <c>ChannelCredentials</c></returns> public static ChannelCredentials Create(ChannelCredentials channelCredentials, CallCredentials callCredentials) { return new CompositeChannelCredentials(channelCredentials, callCredentials); } /// <summary> /// Gets native object for the credentials, creating one if it already doesn't exist. May return null if insecure channel /// should be created. Caller must not call <c>Dispose()</c> on the returned native credentials as their lifetime /// is managed by this class (and instances of native credentials are cached). /// </summary> /// <returns>The native credentials.</returns> internal ChannelCredentialsSafeHandle GetNativeCredentials() { return cachedNativeCredentials.Value; } /// <summary> /// Creates a new native object for the credentials. May return null if insecure channel /// should be created. For internal use only, use <see cref="GetNativeCredentials"/> instead. /// </summary> /// <returns>The native credentials.</returns> internal abstract ChannelCredentialsSafeHandle CreateNativeCredentials(); /// <summary> /// Returns <c>true</c> if this credential type allows being composed by <c>CompositeCredentials</c>. /// </summary> internal virtual bool IsComposable { get { return false; } } private sealed class InsecureCredentialsImpl : ChannelCredentials { internal override ChannelCredentialsSafeHandle CreateNativeCredentials() { return null; } } } /// <summary> /// Callback invoked with the expected targetHost and the peer's certificate. /// If false is returned by this callback then it is treated as a /// verification failure and the attempted connection will fail. /// Invocation of the callback is blocking, so any /// implementation should be light-weight. /// Note that the callback can potentially be invoked multiple times, /// concurrently from different threads (e.g. when multiple connections /// are being created for the same credentials). /// </summary> /// <param name="context">The <see cref="T:Grpc.Core.VerifyPeerContext"/> associated with the callback</param> /// <returns>true if verification succeeded, false otherwise.</returns> /// Note: experimental API that can change or be removed without any prior notice. public delegate bool VerifyPeerCallback(VerifyPeerContext context); /// <summary> /// Client-side SSL credentials. /// </summary> public sealed class SslCredentials : ChannelCredentials { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<SslCredentials>(); readonly string rootCertificates; readonly KeyCertificatePair keyCertificatePair; readonly VerifyPeerCallback verifyPeerCallback; /// <summary> /// Creates client-side SSL credentials loaded from /// disk file pointed to by the GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable. /// If that fails, gets the roots certificates from a well known place on disk. /// </summary> public SslCredentials() : this(null, null, null) { } /// <summary> /// Creates client-side SSL credentials from /// a string containing PEM encoded root certificates. /// </summary> public SslCredentials(string rootCertificates) : this(rootCertificates, null, null) { } /// <summary> /// Creates client-side SSL credentials. /// </summary> /// <param name="rootCertificates">string containing PEM encoded server root certificates.</param> /// <param name="keyCertificatePair">a key certificate pair.</param> public SslCredentials(string rootCertificates, KeyCertificatePair keyCertificatePair) : this(rootCertificates, keyCertificatePair, null) { } /// <summary> /// Creates client-side SSL credentials. /// </summary> /// <param name="rootCertificates">string containing PEM encoded server root certificates.</param> /// <param name="keyCertificatePair">a key certificate pair.</param> /// <param name="verifyPeerCallback">a callback to verify peer's target name and certificate.</param> /// Note: experimental API that can change or be removed without any prior notice. public SslCredentials(string rootCertificates, KeyCertificatePair keyCertificatePair, VerifyPeerCallback verifyPeerCallback) { this.rootCertificates = rootCertificates; this.keyCertificatePair = keyCertificatePair; this.verifyPeerCallback = verifyPeerCallback; } /// <summary> /// PEM encoding of the server root certificates. /// </summary> public string RootCertificates { get { return this.rootCertificates; } } /// <summary> /// Client side key and certificate pair. /// If null, client will not use key and certificate pair. /// </summary> public KeyCertificatePair KeyCertificatePair { get { return this.keyCertificatePair; } } // Composing composite makes no sense. internal override bool IsComposable { get { return true; } } internal override ChannelCredentialsSafeHandle CreateNativeCredentials() { IntPtr verifyPeerCallbackTag = IntPtr.Zero; if (verifyPeerCallback != null) { verifyPeerCallbackTag = new VerifyPeerCallbackRegistration(verifyPeerCallback).CallbackRegistration.Tag; } return ChannelCredentialsSafeHandle.CreateSslCredentials(rootCertificates, keyCertificatePair, verifyPeerCallbackTag); } private class VerifyPeerCallbackRegistration { readonly VerifyPeerCallback verifyPeerCallback; readonly NativeCallbackRegistration callbackRegistration; public VerifyPeerCallbackRegistration(VerifyPeerCallback verifyPeerCallback) { this.verifyPeerCallback = verifyPeerCallback; this.callbackRegistration = NativeCallbackDispatcher.RegisterCallback(HandleUniversalCallback); } public NativeCallbackRegistration CallbackRegistration => callbackRegistration; private int HandleUniversalCallback(IntPtr arg0, IntPtr arg1, IntPtr arg2, IntPtr arg3, IntPtr arg4, IntPtr arg5) { return VerifyPeerCallbackHandler(arg0, arg1, arg2 != IntPtr.Zero); } private int VerifyPeerCallbackHandler(IntPtr targetName, IntPtr peerPem, bool isDestroy) { if (isDestroy) { this.callbackRegistration.Dispose(); return 0; } try { var context = new VerifyPeerContext(Marshal.PtrToStringAnsi(targetName), Marshal.PtrToStringAnsi(peerPem)); return this.verifyPeerCallback(context) ? 0 : 1; } catch (Exception e) { // eat the exception, we must not throw when inside callback from native code. Logger.Error(e, "Exception occurred while invoking verify peer callback handler."); // Return validation failure in case of exception. return 1; } } } } /// <summary> /// Credentials that allow composing one <see cref="ChannelCredentials"/> object and /// one or more <see cref="CallCredentials"/> objects into a single <see cref="ChannelCredentials"/>. /// </summary> internal sealed class CompositeChannelCredentials : ChannelCredentials { readonly ChannelCredentials channelCredentials; readonly CallCredentials callCredentials; /// <summary> /// Initializes a new instance of <c>CompositeChannelCredentials</c> class. /// The resulting credentials object will be composite of all the credentials specified as parameters. /// </summary> /// <param name="channelCredentials">channelCredentials to compose</param> /// <param name="callCredentials">channelCredentials to compose</param> public CompositeChannelCredentials(ChannelCredentials channelCredentials, CallCredentials callCredentials) { this.channelCredentials = GrpcPreconditions.CheckNotNull(channelCredentials); this.callCredentials = GrpcPreconditions.CheckNotNull(callCredentials); GrpcPreconditions.CheckArgument(channelCredentials.IsComposable, "Supplied channel credentials do not allow composition."); } internal override ChannelCredentialsSafeHandle CreateNativeCredentials() { using (var callCreds = callCredentials.ToNativeCredentials()) { var nativeComposite = ChannelCredentialsSafeHandle.CreateComposite(channelCredentials.GetNativeCredentials(), callCreds); if (nativeComposite.IsInvalid) { throw new ArgumentException("Error creating native composite credentials. Likely, this is because you are trying to compose incompatible credentials."); } return nativeComposite; } } } }
using System; using System.IO; namespace NVcdiff { /// <summary> /// Decoder for VCDIFF (RFC 3284) streams. /// </summary> public sealed class VcdiffDecoder { #region Fields /// <summary> /// Reader containing original data, if any. May be null. /// If non-null, will be readable and seekable. /// </summary> Stream original; /// <summary> /// Stream containing delta data. Will be readable. /// </summary> Stream delta; /// <summary> /// Stream containing target data. Will be readable, /// writable and seekable. /// </summary> Stream output; /// <summary> /// Code table to use for decoding. /// </summary> CodeTable codeTable = CodeTable.Default; /// <summary> /// Address cache to use when decoding; must be reset before decoding each window. /// Default to the default size. /// </summary> AddressCache cache = new AddressCache(4, 3); #endregion #region Constructor /// <summary> /// Sole constructor; private to prevent instantiation from /// outside the class. /// </summary> VcdiffDecoder(Stream original, Stream delta, Stream output) { this.original = original; this.delta = delta; this.output = output; } #endregion #region Public interface /// <summary> /// Decodes an original stream and a delta stream, writing to a target stream. /// The original stream may be null, so long as the delta stream never /// refers to it. The original and delta streams must be readable, and the /// original stream (if any) and the target stream must be seekable. /// The target stream must be writable and readable. The original and target /// streams are rewound to their starts before any data is read; the relevant data /// must occur at the beginning of the original stream, and any data already present /// in the target stream may be overwritten. The delta data must begin /// wherever the delta stream is currently positioned. The delta stream must end /// after the last window. The streams are not disposed by this method. /// </summary> /// <param name="original">Stream containing delta. May be null.</param> /// <param name="delta">Stream containing delta data.</param> /// <param name="output">Stream to write resulting data to.</param> public static void Decode (Stream original, Stream delta, Stream output) { #region Simple argument checking if (original != null && (!original.CanRead || !original.CanSeek)) { throw new ArgumentException ("Must be able to read and seek in original stream", "original"); } if (delta==null) { throw new ArgumentNullException("delta"); } if (!delta.CanRead) { throw new ArgumentException ("Unable to read from delta stream"); } if (output==null) { throw new ArgumentNullException("output"); } if (!output.CanWrite || !output.CanRead || !output.CanSeek) { throw new ArgumentException ("Must be able to read, write and seek in output stream", "output"); } #endregion // Now the arguments are checked, we construct an instance of the // class and ask it to do the decoding. VcdiffDecoder instance = new VcdiffDecoder(original, delta, output); instance.Decode(); } #endregion #region Private methods /// <summary> /// Top-level decoding method. When this method exits, all decoding has been performed. /// </summary> void Decode() { ReadHeader(); while (DecodeWindow()); } /// <summary> /// Read the header, including any custom code table. The delta stream is left /// positioned at the start of the first window. /// </summary> void ReadHeader() { byte[] header = IOHelper.CheckedReadBytes(delta, 4); if (header[0] != 0xd6 || header[1] != 0xc3 || header[2] != 0xc4) { throw new VcdiffFormatException("Invalid VCDIFF header in delta stream"); } if (header[3] != 0) { throw new VcdiffFormatException("VcdiffDecoder can only read delta streams of version 0"); } // Load the header indicator byte headerIndicator = IOHelper.CheckedReadByte(delta); if ((headerIndicator&1) != 0) { throw new VcdiffFormatException ("VcdiffDecoder does not handle delta stream using secondary compressors"); } bool customCodeTable = ((headerIndicator&2) != 0); bool applicationHeader = ((headerIndicator&4) != 0); if ((headerIndicator & 0xf8) != 0) { throw new VcdiffFormatException ("Invalid header indicator - bits 3-7 not all zero."); } // Load the custom code table, if there is one if (customCodeTable) { ReadCodeTable(); } // Ignore the application header if we have one. This tells xdelta3 what the right filenames are. if (applicationHeader) { int appHeaderLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); IOHelper.CheckedReadBytes(delta, appHeaderLength); } } /// <summary> /// Reads the custom code table, if there is one /// </summary> void ReadCodeTable() { // The length given includes the nearSize and sameSize bytes int compressedTableLength = IOHelper.ReadBigEndian7BitEncodedInt(delta)-2; int nearSize = IOHelper.CheckedReadByte(delta); int sameSize = IOHelper.CheckedReadByte(delta); byte[] compressedTableData = IOHelper.CheckedReadBytes(delta, compressedTableLength); byte[] defaultTableData = CodeTable.Default.GetBytes(); MemoryStream tableOriginal = new MemoryStream(defaultTableData, false); MemoryStream tableDelta = new MemoryStream(compressedTableData, false); byte[] decompressedTableData = new byte[1536]; MemoryStream tableOutput = new MemoryStream(decompressedTableData, true); VcdiffDecoder.Decode(tableOriginal, tableDelta, tableOutput); if (tableOutput.Position != 1536) { throw new VcdiffFormatException("Compressed code table was incorrect size"); } codeTable = new CodeTable(decompressedTableData); cache = new AddressCache(nearSize, sameSize); } /// <summary> /// Reads and decodes a window, returning whether or not there was /// any more data to read. /// </summary> /// <returns> /// Whether or not the delta stream had reached the end of its data. /// </returns> bool DecodeWindow () { int windowIndicator = delta.ReadByte(); // Have we finished? if (windowIndicator==-1) { return false; } // Check EOF marker (8th bit). // For ability to read VCDIFF file from the middle of the stream. if (windowIndicator==128) { return false; } // The stream to load source data from for this window, if any Stream sourceStream; // Where to reposition the source stream to after reading from it, if anywhere int sourceStreamPostReadSeek=-1; // xdelta3 uses an undocumented extra bit which indicates that there are an extra // 4 bytes at the end of the encoding for the window bool hasAdler32Checksum = ((windowIndicator&4)==4); // Get rid of the checksum bit for the rest windowIndicator &= 0xfb; // Work out what the source data is, and detect invalid window indicators switch (windowIndicator&3) { // No source data used in this window case 0: sourceStream = null; break; // Source data comes from the original stream case 1: if (original==null) { throw new VcdiffFormatException ("Source stream requested by delta but not provided by caller."); } sourceStream = original; break; case 2: sourceStream = output; sourceStreamPostReadSeek = (int)output.Position; break; case 3: throw new VcdiffFormatException ("Invalid window indicator - bits 0 and 1 both set."); default: throw new VcdiffFormatException("Invalid window indicator - bits 3-7 not all zero."); } // Read the source data, if any byte[] sourceData = null; int sourceLength = 0; if (sourceStream != null) { sourceLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); int sourcePosition = IOHelper.ReadBigEndian7BitEncodedInt(delta); sourceStream.Position = sourcePosition; sourceData = IOHelper.CheckedReadBytes(sourceStream, sourceLength); // Reposition the source stream if appropriate if (sourceStreamPostReadSeek != -1) { sourceStream.Position = sourceStreamPostReadSeek; } } // Read how long the delta encoding is - then ignore it IOHelper.ReadBigEndian7BitEncodedInt(delta); // Read how long the target window is int targetLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); byte[] targetData = new byte[targetLength]; MemoryStream targetDataStream = new MemoryStream(targetData, true); // Read the indicator and the lengths of the different data sections byte deltaIndicator = IOHelper.CheckedReadByte(delta); if (deltaIndicator != 0) { throw new VcdiffFormatException("VcdiffDecoder is unable to handle compressed delta sections."); } int addRunDataLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); int instructionsLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); int addressesLength = IOHelper.ReadBigEndian7BitEncodedInt(delta); // If we've been given a checksum, we have to read it and we might as well // use it to check the data. int checksumInFile=0; if (hasAdler32Checksum) { byte[] checksumBytes = IOHelper.CheckedReadBytes(delta, 4); checksumInFile = (checksumBytes[0]<<24) | (checksumBytes[1]<<16) | (checksumBytes[2]<<8) | checksumBytes[3]; } // Read all the data for this window byte[] addRunData = IOHelper.CheckedReadBytes(delta, addRunDataLength); byte[] instructions = IOHelper.CheckedReadBytes(delta, instructionsLength); byte[] addresses = IOHelper.CheckedReadBytes(delta, addressesLength); int addRunDataIndex = 0; MemoryStream instructionStream = new MemoryStream(instructions, false); cache.Reset(addresses); while (true) { int instructionIndex = instructionStream.ReadByte(); if (instructionIndex==-1) { break; } for (int i=0; i < 2; i++) { Instruction instruction = codeTable[instructionIndex, i]; int size = instruction.Size; if (size==0 && instruction.Type != InstructionType.NoOp) { size = IOHelper.ReadBigEndian7BitEncodedInt(instructionStream); } switch (instruction.Type) { case InstructionType.NoOp: break; case InstructionType.Add: targetDataStream.Write(addRunData, addRunDataIndex, size); addRunDataIndex += size; break; case InstructionType.Copy: int addr = cache.DecodeAddress((int)targetDataStream.Position+sourceLength, instruction.Mode); if (sourceData != null && addr < sourceData.Length) { targetDataStream.Write(sourceData, addr, size); } else // Data is in target data { // Get rid of the offset addr -= sourceLength; // Can we just ignore overlap issues? if (addr + size < targetDataStream.Position) { targetDataStream.Write(targetData, addr, size); } else { for (int j=0; j < size; j++) { targetDataStream.WriteByte(targetData[addr++]); } } } break; case InstructionType.Run: byte data = addRunData[addRunDataIndex++]; for (int j=0; j < size; j++) { targetDataStream.WriteByte(data); } break; default: throw new VcdiffFormatException("Invalid instruction type found."); } } } output.Write(targetData, 0, targetLength); if (hasAdler32Checksum) { int actualChecksum = Adler32.ComputeChecksum(1, targetData); if (actualChecksum != checksumInFile) { throw new VcdiffFormatException("Invalid checksum after decoding window"); } } return true; } #endregion } }
//----------------------------------------------------------------------- // <copyright file="ResourceAccessHandler.cs" company="Rare Crowds Inc."> // Copyright 2012-2013 Rare Crowds, 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. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text.RegularExpressions; using DataAccessLayer; namespace ResourceAccess { /// <summary>Class to handle resource access checking.</summary> public class ResourceAccessHandler : IResourceAccessHandler { /// <summary>Initializes a new instance of the <see cref="ResourceAccessHandler"/> class.</summary> /// <param name="userAccessRepository">The user access repository.</param> /// <param name="entityRepository">The entiry repository.</param> public ResourceAccessHandler(IUserAccessRepository userAccessRepository, IEntityRepository entityRepository) { this.UserAccessRepository = userAccessRepository; this.EntityRepository = entityRepository; } /// <summary>Gets UserAccessRepository.</summary> internal IUserAccessRepository UserAccessRepository { get; private set; } /// <summary>Gets EntityRepository.</summary> internal IEntityRepository EntityRepository { get; private set; } /// <summary>Check whether a user has access to a resource.</summary> /// <param name="canonicalResource">A canonical resource object.</param> /// <param name="userEntityId">An authenticated user entity id.</param> /// <returns>True if access is granted.</returns> public bool CheckAccess(CanonicalResource canonicalResource, EntityId userEntityId) { // No user, no access if (userEntityId == null) { return false; } // TODO: Remove this once the service namespaces have been removed // Right now if the resource is not canonical we grant access as long // as there is an authenticated user. if (!canonicalResource.IsCanonical) { return true; } // Get the access list from the repository var accessList = this.UserAccessRepository.GetUserAccessList(userEntityId).ToList(); // Check for a match and if it is, validate the resource chain is parent/child hierarchy if (this.MatchAccess(canonicalResource, accessList, false) && this.ValidateResourceChain(canonicalResource)) { return true; } return false; } /// <summary>Check if a resource has global access rights.</summary> /// <param name="canonicalResource">A canonical resource object.</param> /// <returns>True if global access is granted.</returns> public bool CheckGlobalAccess(CanonicalResource canonicalResource) { // TODO: load this from config var accessList = new List<string> { "ROOT:#:GET", "*.html:#:GET:*", // allows user access to any .html page "LogOff.aspx:#:GET:*", "userverification.html:#:GET:*", "home.html:#:GET:*", "ping.html:#:GET:*", "favicon.ico:#:GET:*", "css:*:#:GET:*", "dhtml:*:#:GET:*", "images:*:#:GET:*", "jquery:*:#:GET:*", "scripts:*:#:GET:*", "federationmetadata:*:#:GET:*", "api/data:*:#:GET:*", }; return this.MatchAccess(canonicalResource, accessList, true); } /// <summary>Return an array of EnityId'sbased on the user's access list</summary> /// <param name="userEntityId">User's Entity Id</param> /// <returns>Array of Company Ids.</returns> public EntityId[] GetUserCompanyByAccessList(EntityId userEntityId) { var accessList = this.UserAccessRepository.GetUserAccessList(userEntityId).ToList(); // get the companies from the list var accessListCompanies = accessList.Where(c => c.Contains("COMPANY") && !c.Contains("COMPANY:*")); if (accessListCompanies.Any()) { var resourceChain = CanonicalResource.ExtractResourceList(accessListCompanies.FirstOrDefault()); return new EntityId[] { resourceChain[1] }; } else { return new EntityId[0]; } } /// <summary>Check if a resource has access rights.</summary> /// <param name="canonicalResource">A canonical resource object.</param> /// <param name="accessList">The access list.</param> /// <param name="checkGlobalAccess">True if we are only checking for global access.</param> /// <returns>True if access is granted.</returns> internal bool MatchAccess(CanonicalResource canonicalResource, List<string> accessList, bool checkGlobalAccess) { // Check for simple exact match first if (CheckExactMatch(canonicalResource, accessList)) { return true; } if (this.CheckInheritedMatch(canonicalResource, accessList, checkGlobalAccess)) { return true; } return false; } /// <summary>Determine whether a resource matches a given access descriptor.</summary> /// <param name="canonicalResource">The canonical resource to check.</param> /// <param name="accessList">The access list.</param> /// <returns>True if this is a match.</returns> private static bool CheckExactMatch(CanonicalResource canonicalResource, IEnumerable<string> accessList) { var canonicalDescriptor = canonicalResource.CanonicalDescriptor; return accessList.Any(a => IsStringMatch(a, canonicalDescriptor)); } /// <summary> /// Given an access descriptor string and a list of resourceDescriptor tokens build a /// list of accessDescriptor tokens that is expanded to have a 1:1 correspondance /// with the resourceDescriptor tokens for safer comparison. /// </summary> /// <param name="accessDescriptorTokensIn">The access descriptor tokens.</param> /// <param name="resourceDescriptorTokens">The resource descriptor tokens.</param> /// <returns>A list of accessDescriptor tokens.</returns> private static List<string> ExpandAccessDescriptorTokens(IList<string> accessDescriptorTokensIn, IList<string> resourceDescriptorTokens) { var accessDescriptorTokens = new string[resourceDescriptorTokens.Count()]; var wildCardEncountered = false; for (var i = 0; i < resourceDescriptorTokens.Count(); i++) { // By default, an unspecified access descriptor token will be empty string. If this is // a resource chain and we have encountered a wildcard fill to end with the wildcard. accessDescriptorTokens[i] = wildCardEncountered ? CanonicalResource.WildCard : string.Empty; if (accessDescriptorTokensIn.Count <= i) { continue; } accessDescriptorTokens[i] = accessDescriptorTokensIn[i]; // Toggle as a sticky flag if (IsWildcard(accessDescriptorTokensIn[i])) { wildCardEncountered = true; } } return accessDescriptorTokens.ToList(); } /// <summary> /// Determine if a list of tokens from a canonical resource descriptor is a match for /// a list of tokens from an access descriptor. /// </summary> /// <param name="accessDescriptorTokens"> /// The access descriptor tokens. Must be the same length as resourceDescriptor list. /// </param> /// <param name="resourceDescriptorTokens">The resource descriptor tokens.</param> /// <returns>True if they are a match.</returns> private static bool CompareTokenLists(IList<string> accessDescriptorTokens, IList<string> resourceDescriptorTokens) { var accessMatch = true; for (var i = 0; i < resourceDescriptorTokens.Count(); i++) { var accessToken = accessDescriptorTokens[i]; if (IsWildcard(accessToken)) { // If this is a resource chain we don't need to go any futhur, but that is not the case // for the Action and Message which are independent - so we keep going. continue; } var resourceToken = resourceDescriptorTokens[i]; if (CompareTokens(resourceToken, accessToken)) { // Exact match to this point, keep going. continue; } if (MatchWithWildcard(resourceToken, accessToken)) { continue; } // Match failed accessMatch = false; break; } return accessMatch; } /// <summary> /// Determine if a list of tokens from a canonical resource descriptor entity id contains a match from /// a list of tokens from an access descriptor. /// </summary> /// <param name="accessDescriptorTokens"> /// The access descriptor tokens. Must be the same length as resourceDescriptor list. /// </param> /// <param name="resourceDescriptorTokens">The resource descriptor tokens.</param> /// <returns>True if there is an entity id match.</returns> private static bool ComparePartialTokenListsForEntityId(IList<string> accessDescriptorTokens, IList<string> resourceDescriptorTokens) { for (var i = 0; i < resourceDescriptorTokens.Count(); i++) { var accessToken = accessDescriptorTokens[i]; var resourceToken = resourceDescriptorTokens[i]; var parsedGuid = new Guid(); if (Guid.TryParse(resourceToken, out parsedGuid) && CompareTokens(resourceToken, accessToken)) { // Exact match return true; } } return false; } /// <summary> /// Determine if a list of resource tokens from a canonical resource descriptor is a match for /// a list of tokens from an access descriptor. /// </summary> /// <param name="accessResourceTokens">The access descriptor tokens.</param> /// <param name="resourceTokens">The resource descriptor tokens.</param> /// <returns>True if they are a match.</returns> private static bool CompareResourceTokenLists(IList<string> accessResourceTokens, IList<string> resourceTokens) { // Expand the access resource tokens to align 1:1 with the resource tokens for easier direct comparison var expandedAccessResourceTokens = ExpandAccessDescriptorTokens(accessResourceTokens, resourceTokens); // Determine if resource chain matches return CompareTokenLists(expandedAccessResourceTokens, resourceTokens); } /// <summary> /// Determine if a list of resource tokens from a canonical resource descriptor contains a match for /// a list of tokens from an access descriptor. /// </summary> /// <param name="accessResourceTokens">The access descriptor tokens.</param> /// <param name="resourceTokens">The resource descriptor tokens.</param> /// <returns>True if there is a match.</returns> private static bool IsAccessResourceInDerived(IList<string> accessResourceTokens, IList<string> resourceTokens) { // Expand the access resource tokens to align 1:1 with the resource tokens for easier direct comparison var expandedAccessResourceTokens = ExpandAccessDescriptorTokens(accessResourceTokens, resourceTokens); // Determine if an entity id in the resource chain matches return ComparePartialTokenListsForEntityId(expandedAccessResourceTokens, resourceTokens); } /// <summary>Try to get an entity id from a resource id string.</summary> /// <param name="resourceId">The resource id.</param> /// <returns>An entity id or null if it is not a valid id.</returns> [SuppressMessage("Microsoft.Design", "CA1031", Justification = "TryGet pattern.")] private static EntityId TryBuildEntityId(string resourceId) { try { return new EntityId(resourceId); } catch { } return null; } /// <summary>Compare two descriptor tokens</summary> /// <param name="resourceToken">The resource token.</param> /// <param name="accessToken">The access token.</param> /// <returns>True if the tokens match.</returns> private static bool CompareTokens(string resourceToken, string accessToken) { return IsStringMatch(accessToken, resourceToken); } /// <summary>Check if a token is a wildcard.</summary> /// <param name="token">The token.</param> /// <returns>True if the token is a wildcard.</returns> private static bool IsWildcard(string token) { return IsStringMatch(token, CanonicalResource.WildCard); } /// <summary>Check if a token matches a value with a wildcard.</summary> /// <param name="resourceToken">The resource token.</param> /// <param name="accessToken">The access token.</param> /// <returns>True if the token matches wildcard.</returns> private static bool MatchWithWildcard(string resourceToken, string accessToken) { var regex = new Regex(WildcardToRegex(accessToken), RegexOptions.IgnoreCase); return regex.IsMatch(resourceToken); } /// <summary> /// WildcardToRegex returns a regular expression when for the passed in string that has a wildcard star (*) /// </summary> /// <param name="pattern">pattern to search</param> /// <returns>regualr expression to be used for a wildcard match</returns> private static string WildcardToRegex(string pattern) { return "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$"; } /// <summary>Compare two strings.</summary> /// <param name="a">The a.</param> /// <param name="b">The b.</param> /// <returns>True if the strings are equal.</returns> private static bool IsStringMatch(string a, string b) { return string.Compare(a, b, StringComparison.OrdinalIgnoreCase) == 0; } /// <summary>Determine if an entity id refers to a child of a given entity.</summary> /// <param name="candidateChildId">The candidate child id.</param> /// <param name="parentEntity">The parent entity.</param> /// <returns>True if the entity is a child.</returns> private static bool IsChildEntity(EntityId candidateChildId, IEntity parentEntity) { if (parentEntity.Associations.Any( a => a.TargetEntityId == candidateChildId && a.AssociationType == AssociationType.Child)) { return true; } // TODO: Remove when we start saving as child associations. For now we give it a pass if (parentEntity.Associations.Any( a => a.TargetEntityId == candidateChildId && a.AssociationType == AssociationType.Relationship)) { return true; } return false; } /// <summary>Check if a resource is granted inherited access</summary> /// <param name="canonicalResource">The canonical resource to check.</param> /// <param name="accessList">The access list.</param> /// <param name="checkGlobalAccess">True if we are only checking for global access.</param> /// <returns>True if access granted.</returns> private bool CheckInheritedMatch(CanonicalResource canonicalResource, IList<string> accessList, bool checkGlobalAccess) { // Extract the canonical resource components var resourceTokens = CanonicalResource.ExtractResourceList(canonicalResource.CanonicalDescriptor); var resourceActions = new List<string> { canonicalResource.Action }; var resourceMessages = new List<string> { canonicalResource.Message }; // Reduce the accessList by filtering Actions that do not match var reducedAccessList = accessList.Where( a => CompareTokenLists(new List<string> { CanonicalResource.ExtractAction(a) }, resourceActions)).ToList(); // Reduce the accessList by filtering Messages that do not match reducedAccessList = reducedAccessList.Where( a => CompareTokenLists(new List<string> { CanonicalResource.ExtractMessage(a) }, resourceMessages)).ToList(); // Convert the access desciptors into a list of lists of access resource tokens var accessResourceTokenLists = reducedAccessList.Select(a => CanonicalResource.ExtractResourceList(a)).ToList(); // Look for a direct match between the access descriptors and the resource chain. foreach (var accessResourceTokens in accessResourceTokenLists) { if (CompareResourceTokenLists(accessResourceTokens, resourceTokens)) { return true; } } // For global resource checks we don't go further than this. if (checkGlobalAccess) { return false; } // Look for an indirect match among access descriptors that refer to parents of the resource chain. // This is expensive so it is done after all other checks have failed. foreach (var accessResourceTokens in accessResourceTokenLists) { // Construct a resource chain that includes the parent from the access tokens if possible var derivedResourceTokens = this.BuildDerivedResourceList(accessResourceTokens, resourceTokens); if (derivedResourceTokens == null) { continue; } if (CompareResourceTokenLists(accessResourceTokens, derivedResourceTokens)) { return true; } if (IsAccessResourceInDerived(accessResourceTokens, derivedResourceTokens)) { return true; } } return false; } /// <summary> /// Given a list of access resource tokens and resource tokens, determine if we can derive /// a resource chain leading back to a parent in the access resource tokens. /// </summary> /// <param name="accessResourceTokens">The access descriptor tokens.</param> /// <param name="resourceTokens">The resource descriptor tokens.</param> /// <returns>The derived access resource list if found.</returns> private List<string> BuildDerivedResourceList(IList<string> accessResourceTokens, IList<string> resourceTokens) { // For now, only check head entity of the access resource list var headAccessResourceEntityId = accessResourceTokens.Select(TryBuildEntityId).FirstOrDefault(e => e != null); // Get the first valid entity id in the requested resource chain var headResourceEntityId = resourceTokens.Select(TryBuildEntityId).FirstOrDefault(e => e != null); if (headAccessResourceEntityId == null || headResourceEntityId == null) { return null; } var context = new RequestContext { ExternalCompanyId = headAccessResourceEntityId }; var headEntity = this.EntityRepository.TryGetEntity(context, headAccessResourceEntityId); if (headEntity == null) { return null; } // Assume the head entity is a company for purposes of matching with the access descriptor if (IsChildEntity(headResourceEntityId, headEntity)) { // Create a new list of derived resource tokens (leaving the old one intact). var derivedResourceTokens = resourceTokens.Select(token => token).ToList(); derivedResourceTokens.Insert(0, headAccessResourceEntityId); derivedResourceTokens.Insert(0, "COMPANY"); return derivedResourceTokens; } return null; } /// <summary>Determine that the resource chain has legitimate parent/child associations.</summary> /// <param name="canonicalResource">A canonical resource.</param> /// <returns>True if the resouce chain is valid.</returns> private bool ValidateResourceChain(CanonicalResource canonicalResource) { var resourceChain = CanonicalResource.ExtractResourceList(canonicalResource.CanonicalDescriptor); // TODO: consider making this method part of a mockable class // TODO: generalize for longer resource chains // Currently this only applies for resource chains of two entities if (resourceChain.Count != 4) { return true; } // If either resource has a wildcard parent/child is not meaningful if (IsWildcard(resourceChain[1]) || IsWildcard(resourceChain[3])) { return true; } var companyEntityId = TryBuildEntityId(resourceChain[1]); var childEntityId = TryBuildEntityId(resourceChain[3]); if (companyEntityId == null || childEntityId == null) { // Should have been an entity id return false; } var context = new RequestContext { ExternalCompanyId = companyEntityId }; var companyEntity = this.EntityRepository.TryGetEntity(context, companyEntityId); if (companyEntity == null) { return false; } return IsChildEntity(childEntityId, companyEntity); } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.IEqualityComparer.Equals(T,T) /// </summary> public class IEqualityComparerEquals { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main(string[] args) { IEqualityComparerEquals testObj = new IEqualityComparerEquals(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.EqualityComparer.Equals(T,T)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using EqualityComparer<T> which implemented the Equals method in IEqualityComparer<T> and Type is int..."; const string c_TEST_ID = "P001"; EqualityComparer<int> equalityComparer = EqualityComparer<int>.Default; int x = TestLibrary.Generator.GetInt32(-55); int y = x; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!((IEqualityComparer<int>)equalityComparer).Equals(x, y)) { string errorDesc = "result should be true when two int both are " + x; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using EqualityComparer<T> which implemented the Equals method in IEqualityComparer<T> and Type is String..."; const string c_TEST_ID = "P002"; String x = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String y = x; EqualityComparer<String> equalityComparer = EqualityComparer<String>.Default; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!((IEqualityComparer<String>)equalityComparer).Equals(x, y)) { string errorDesc = "result should be true when two String object is the same reference"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using EqualityComparer<T> which implemented the Equals method in IEqualityComparer<T> and Type is user-defined class..."; const string c_TEST_ID = "P003"; MyClass x = new MyClass(); MyClass y = x; EqualityComparer<MyClass> equalityComparer = EqualityComparer<MyClass>.Default; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!((IEqualityComparer<MyClass>)equalityComparer).Equals(x, y)) { string errorDesc = "result should be true when two MyClass object is the same reference"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using user-defined class which implemented the Equals method in IEqualityComparer<T>..."; const string c_TEST_ID = "P004"; MyEqualityComparer<String> myEC = new MyEqualityComparer<String>(); String str1 = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String str2 = str1 + TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (((IEqualityComparer<String>)myEC).Equals(str1, str2)) { string errorDesc = "result should be true when two string are difference"; errorDesc += "\n str1 is " + str1; errorDesc += "\n str2 is " + str2; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_DESC = "PosTest5: Using user-defined class which implemented the Equals method in IEqualityComparer<T> and two parament are null..."; const string c_TEST_ID = "P005"; MyEqualityComparer<Object> myEC = new MyEqualityComparer<Object>(); Object x = null; Object y = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { if (!((IEqualityComparer<Object>)myEC).Equals(x, y)) { string errorDesc = "result should be true when two object are null"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyEqualityComparer<T> : IEqualityComparer<T> { #region IEqualityComparer<T> Members bool IEqualityComparer<T>.Equals(T x, T y) { if (x != null) { if (y != null) return x.Equals(y); return false; } if (y != null) return false; return true; } int IEqualityComparer<T>.GetHashCode(T obj) { throw new Exception("The method or operation is not implemented."); } #endregion } public class MyClass { } #endregion }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Connectors.Hypergrid; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGEntityTransferModule")] public class HGEntityTransferModule : EntityTransferModule, INonSharedRegionModule, IEntityTransferModule, IUserAgentVerificationModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private int m_levelHGTeleport = 0; private GatekeeperServiceConnector m_GatekeeperConnector; private IUserAgentService m_UAS; protected bool m_RestrictAppearanceAbroad; protected string m_AccountName; protected List<AvatarAppearance> m_ExportedAppearances; protected List<AvatarAttachment> m_Attachs; protected List<AvatarAppearance> ExportedAppearance { get { if (m_ExportedAppearances != null) return m_ExportedAppearances; m_ExportedAppearances = new List<AvatarAppearance>(); m_Attachs = new List<AvatarAttachment>(); string[] names = m_AccountName.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string name in names) { string[] parts = name.Trim().Split(); if (parts.Length != 2) { m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Wrong user account name format {0}. Specify 'First Last'", name); return null; } UserAccount account = Scene.UserAccountService.GetUserAccount(UUID.Zero, parts[0], parts[1]); if (account == null) { m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unknown account {0}", m_AccountName); return null; } AvatarAppearance a = Scene.AvatarService.GetAppearance(account.PrincipalID); if (a != null) m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Successfully retrieved appearance for {0}", name); foreach (AvatarAttachment att in a.GetAttachments()) { InventoryItemBase item = new InventoryItemBase(att.ItemID, account.PrincipalID); item = Scene.InventoryService.GetItem(item); if (item != null) a.SetAttachment(att.AttachPoint, att.ItemID, item.AssetID); else m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to retrieve item {0} from inventory {1}", att.ItemID, name); } m_ExportedAppearances.Add(a); m_Attachs.AddRange(a.GetAttachments()); } return m_ExportedAppearances; } } #region ISharedRegionModule public override string Name { get { return "HGEntityTransferModule"; } } public override void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("EntityTransferModule", ""); if (name == Name) { IConfig transferConfig = source.Configs["EntityTransfer"]; if (transferConfig != null) { m_levelHGTeleport = transferConfig.GetInt("LevelHGTeleport", 0); m_RestrictAppearanceAbroad = transferConfig.GetBoolean("RestrictAppearanceAbroad", false); if (m_RestrictAppearanceAbroad) { m_AccountName = transferConfig.GetString("AccountForAppearance", string.Empty); if (m_AccountName == string.Empty) m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is on, but no account has been given for avatar appearance!"); } } InitialiseCommon(source); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: {0} enabled.", Name); } } } public override void AddRegion(Scene scene) { base.AddRegion(scene); if (m_Enabled) { scene.RegisterModuleInterface<IUserAgentVerificationModule>(this); scene.EventManager.OnIncomingSceneObject += OnIncomingSceneObject; } } void OnIncomingSceneObject(SceneObjectGroup so) { if (!so.IsAttachment) return; if (so.AttachedAvatar == UUID.Zero || Scene.UserManagementModule.IsLocalGridUser(so.AttachedAvatar)) return; // foreign user AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(so.AttachedAvatar); if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0) { if (aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("AssetServerURI")) { string url = aCircuit.ServiceURLs["AssetServerURI"].ToString(); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Incoming attachment {0} for HG user {1} with asset server {2}", so.Name, so.AttachedAvatar, url); Dictionary<UUID, sbyte> ids = new Dictionary<UUID, sbyte>(); HGUuidGatherer uuidGatherer = new HGUuidGatherer(Scene.AssetService, url); uuidGatherer.GatherAssetUuids(so, ids); foreach (KeyValuePair<UUID, sbyte> kvp in ids) uuidGatherer.FetchAsset(kvp.Key); } } } protected override void OnNewClient(IClientAPI client) { client.OnTeleportHomeRequest += TriggerTeleportHome; client.OnTeleportLandmarkRequest += RequestTeleportLandmark; client.OnConnectionClosed += new Action<IClientAPI>(OnConnectionClosed); } public override void RegionLoaded(Scene scene) { base.RegionLoaded(scene); if (m_Enabled) { m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService); m_UAS = scene.RequestModuleInterface<IUserAgentService>(); if (m_UAS == null) m_UAS = new UserAgentServiceConnector(m_ThisHomeURI); } } public override void RemoveRegion(Scene scene) { base.RemoveRegion(scene); if (m_Enabled) scene.UnregisterModuleInterface<IUserAgentVerificationModule>(this); } #endregion #region HG overrides of IEntiryTransferModule protected override GridRegion GetFinalDestination(GridRegion region, UUID agentID, string agentHomeURI, out string message) { int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, region.RegionID); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionName, flags); message = null; if ((flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region is hyperlink"); GridRegion real_destination = m_GatekeeperConnector.GetHyperlinkRegion(region, region.RegionID, agentID, agentHomeURI, out message); if (real_destination != null) m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: GetFinalDestination: ServerURI={0}", real_destination.ServerURI); else m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: GetHyperlinkRegion of region {0} from Gatekeeper {1} failed: {2}", region.RegionID, region.ServerURI, message); return real_destination; } return region; } protected override bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg) { if (base.NeedsClosing(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) return true; int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID); if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0) return true; return false; } protected override void AgentHasMovedAway(ScenePresence sp, bool logout) { base.AgentHasMovedAway(sp, logout); if (logout) { // Log them out of this grid Scene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId); string userId; /* Unknown users cannot be logged out so we guard for that */ if (Scene.UserManagementModule.GetUserUUI(sp.UUID, out userId)) { Scene.GridUserService.LoggedOut(userId, UUID.Zero, Scene.RegionInfo.RegionID, sp.AbsolutePosition, sp.Lookat); } } } protected override bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI); reason = string.Empty; logout = false; int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID); if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0) { // this user is going to another grid // for local users, check if HyperGrid teleport is allowed, based on user level if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID) && sp.UserLevel < m_levelHGTeleport) { m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: Unable to HG teleport agent due to insufficient UserLevel."); reason = "Hypergrid teleport not allowed"; return false; } if (agentCircuit.ServiceURLs.ContainsKey("HomeURI")) { string userAgentDriver = agentCircuit.ServiceURLs["HomeURI"].ToString(); IUserAgentService connector; if (userAgentDriver.Equals(m_ThisHomeURI) && m_UAS != null) connector = m_UAS; else connector = new UserAgentServiceConnector(userAgentDriver); GridRegion source = new GridRegion(Scene.RegionInfo); source.RawServerURI = m_GatekeeperURI; bool success = connector.LoginAgentToGrid(source, agentCircuit, reg, finalDestination, false, out reason); logout = success; // flag for later logout from this grid; this is an HG TP if (success) sp.Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout); return success; } else { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent does not have a HomeURI address"); return false; } } return base.CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout); } protected override bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason) { reason = "Please wear your grid's allowed appearance before teleporting to another grid"; if (!m_RestrictAppearanceAbroad) return true; // The rest is only needed for controlling appearance int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID); if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Framework.RegionFlags.Hyperlink) != 0) { // this user is going to another grid if (Scene.UserManagementModule.IsLocalGridUser(sp.UUID)) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Checking generic appearance"); // Check wearables for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { for (int j = 0; j < sp.Appearance.Wearables[i].Count; j++) { if (sp.Appearance.Wearables[i] == null) continue; bool found = false; foreach (AvatarAppearance a in ExportedAppearance) if (a.Wearables[i] != null) { found = true; break; } if (!found) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i); return false; } found = false; foreach (AvatarAppearance a in ExportedAppearance) if (sp.Appearance.Wearables[i][j].AssetID == a.Wearables[i][j].AssetID) { found = true; break; } if (!found) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Wearable not allowed to go outside {0}", i); return false; } } } // Check attachments foreach (AvatarAttachment att in sp.Appearance.GetAttachments()) { bool found = false; foreach (AvatarAttachment att2 in m_Attachs) { if (att2.AssetID == att.AssetID) { found = true; break; } } if (!found) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Attachment not allowed to go outside {0}", att.AttachPoint); return false; } } } } reason = string.Empty; return true; } //protected override bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agentData, ScenePresence sp) //{ // int flags = Scene.GridService.GetRegionFlags(Scene.RegionInfo.ScopeID, reg.RegionID); // if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0) // { // // this user is going to another grid // if (m_RestrictAppearanceAbroad && Scene.UserManagementModule.IsLocalGridUser(agentData.AgentID)) // { // // We need to strip the agent off its appearance // m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: RestrictAppearanceAbroad is ON. Sending generic appearance"); // // Delete existing npc attachments // Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, false); // // XXX: We can't just use IAvatarFactoryModule.SetAppearance() yet since it doesn't transfer attachments // AvatarAppearance newAppearance = new AvatarAppearance(ExportedAppearance, true); // sp.Appearance = newAppearance; // // Rez needed npc attachments // Scene.AttachmentsModule.RezAttachments(sp); // IAvatarFactoryModule module = Scene.RequestModuleInterface<IAvatarFactoryModule>(); // //module.SendAppearance(sp.UUID); // module.RequestRebake(sp, false); // Scene.AttachmentsModule.CopyAttachments(sp, agentData); // agentData.Appearance = sp.Appearance; // } // } // foreach (AvatarAttachment a in agentData.Appearance.GetAttachments()) // m_log.DebugFormat("[XXX]: {0}-{1}", a.ItemID, a.AssetID); // return base.UpdateAgent(reg, finalDestination, agentData, sp); //} public override void TriggerTeleportHome(UUID id, IClientAPI client) { TeleportHome(id, client); } public override bool TeleportHome(UUID id, IClientAPI client) { m_log.DebugFormat( "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId); // Let's find out if this is a foreign user or a local user IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>(); if (uMan != null && uMan.IsLocalGridUser(id)) { // local grid user m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: User is local"); return base.TeleportHome(id, client); } // Foreign user wants to go home // AgentCircuitData aCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode); if (aCircuit == null || (aCircuit != null && !aCircuit.ServiceURLs.ContainsKey("HomeURI"))) { client.SendTeleportFailed("Your information has been lost"); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Unable to locate agent's gateway information"); return false; } IUserAgentService userAgentService = new UserAgentServiceConnector(aCircuit.ServiceURLs["HomeURI"].ToString()); Vector3 position = Vector3.UnitY, lookAt = Vector3.UnitY; GridRegion finalDestination = null; try { finalDestination = userAgentService.GetHomeRegion(aCircuit.AgentID, out position, out lookAt); } catch (Exception e) { m_log.Debug("[HG ENTITY TRANSFER MODULE]: GetHomeRegion call failed ", e); } if (finalDestination == null) { client.SendTeleportFailed("Your home region could not be found"); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent's home region not found"); return false; } ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(client.AgentId); if (sp == null) { client.SendTeleportFailed("Internal error"); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent not found in the scene where it is supposed to be"); return false; } GridRegion homeGatekeeper = MakeRegion(aCircuit); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: teleporting user {0} {1} home to {2} via {3}:{4}", aCircuit.firstname, aCircuit.lastname, finalDestination.RegionName, homeGatekeeper.ServerURI, homeGatekeeper.RegionName); DoTeleport( sp, homeGatekeeper, finalDestination, position, lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome)); return true; } /// <summary> /// Tries to teleport agent to landmark. /// </summary> /// <param name="remoteClient"></param> /// <param name="regionHandle"></param> /// <param name="position"></param> public override void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}", (lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position); if (lm.Gatekeeper == string.Empty) { base.RequestTeleportLandmark(remoteClient, lm); return; } GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID); // Local region? if (info != null) { ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position, Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark)); } else { // Foreign region Scene scene = (Scene)(remoteClient.Scene); GatekeeperServiceConnector gConn = new GatekeeperServiceConnector(); GridRegion gatekeeper = new GridRegion(); gatekeeper.ServerURI = lm.Gatekeeper; string homeURI = Scene.GetAgentHomeURI(remoteClient.AgentId); string message; GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID), remoteClient.AgentId, homeURI, out message); if (finalDestination != null) { ScenePresence sp = scene.GetScenePresence(remoteClient.AgentId); IEntityTransferModule transferMod = scene.RequestModuleInterface<IEntityTransferModule>(); if (transferMod != null && sp != null) { if (message != null) sp.ControllingClient.SendAgentAlertMessage(message, true); transferMod.DoTeleport( sp, gatekeeper, finalDestination, lm.Position, Vector3.UnitX, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark)); } } else { remoteClient.SendTeleportFailed(message); } } } #endregion #region IUserAgentVerificationModule public bool VerifyClient(AgentCircuitData aCircuit, string token) { if (aCircuit.ServiceURLs.ContainsKey("HomeURI")) { string url = aCircuit.ServiceURLs["HomeURI"].ToString(); IUserAgentService security = new UserAgentServiceConnector(url); return security.VerifyClient(aCircuit.SessionID, token); } else { m_log.DebugFormat( "[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!", aCircuit.firstname, aCircuit.lastname); } return false; } void OnConnectionClosed(IClientAPI obj) { if (obj.SceneAgent.IsChildAgent) return; // Let's find out if this is a foreign user or a local user IUserManagement uMan = Scene.RequestModuleInterface<IUserManagement>(); // UserAccount account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, obj.AgentId); if (uMan != null && uMan.IsLocalGridUser(obj.AgentId)) { // local grid user m_UAS.LogoutAgent(obj.AgentId, obj.SessionId); return; } AgentCircuitData aCircuit = ((Scene)(obj.Scene)).AuthenticateHandler.GetAgentCircuitData(obj.CircuitCode); if (aCircuit != null && aCircuit.ServiceURLs != null && aCircuit.ServiceURLs.ContainsKey("HomeURI")) { string url = aCircuit.ServiceURLs["HomeURI"].ToString(); IUserAgentService security = new UserAgentServiceConnector(url); security.LogoutAgent(obj.AgentId, obj.SessionId); //m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Sent logout call to UserAgentService @ {0}", url); } else { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: HomeURI not found for agent {0} logout", obj.AgentId); } } #endregion private GridRegion MakeRegion(AgentCircuitData aCircuit) { GridRegion region = new GridRegion(); Uri uri = null; if (!aCircuit.ServiceURLs.ContainsKey("HomeURI") || (aCircuit.ServiceURLs.ContainsKey("HomeURI") && !Uri.TryCreate(aCircuit.ServiceURLs["HomeURI"].ToString(), UriKind.Absolute, out uri))) return null; region.ExternalHostName = uri.Host; region.HttpPort = (uint)uri.Port; region.ServerURI = aCircuit.ServiceURLs["HomeURI"].ToString(); region.RegionName = string.Empty; region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0); return region; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class Event_Generic : PortsTest { // Maximum time to wait for all of the expected events to be firered private static readonly int MAX_TIME_WAIT = 5000; // Time to wait in-between triggering events private static readonly int TRIGERING_EVENTS_WAIT_TIME = 500; #region Test Cases [ConditionalFact(nameof(HasNullModem))] public void EventHandlers_CalledSerially() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0; int iterationWaitTime = 100; /*************************************************************** Scenario Description: All of the event handlers should be called sequentially never at the same time on multiple thread. Basically we will block each event handler caller thread and verify that no other thread is in another event handler ***************************************************************/ Debug.WriteLine("Verifying that event handlers are called serially"); com1.WriteTimeout = 5000; com2.WriteTimeout = 5000; com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.PinChanged += pinChangedEventHandler.HandleEvent; com1.DataReceived += receivedEventHandler.HandleEvent; com1.ErrorReceived += errorEventHandler.HandleEvent; //This should cause ErrorEvent to be fired with a parity error since the //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), //and com2 is writing 0 for this bit com1.DataBits = 7; com1.Parity = Parity.Mark; com2.BaseStream.Write(new byte[1], 0, 1); Debug.Print("ERROREvent Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged //since we are setting DtrEnable to true com2.DtrEnable = true; Debug.WriteLine("PinChange Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause ReceivedEvent to be fired with ReceivedChars //since we are writing some bytes com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 40 }, 0, 1); Debug.WriteLine("RxEvent Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause a frame error since the 8th bit is not set, //and com1 is set to 7 data bits so the 8th bit will +12v where //com1 expects the stop bit at the 8th bit to be -12v com1.DataBits = 7; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1); Debug.WriteLine("FrameError Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged //since we are setting RtsEnable to true com2.RtsEnable = true; Debug.WriteLine("PinChange Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause ReceivedEvent to be fired with EofReceived //since we are writing the EOF char com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 26 }, 0, 1); Debug.WriteLine("RxEOF Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.Break //since we are setting BreakState to true com2.BreakState = true; Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); bool threadFound = true; Stopwatch sw = Stopwatch.StartNew(); while (threadFound && sw.ElapsedMilliseconds < MAX_TIME_WAIT) { threadFound = false; for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i) { Debug.WriteLine("Event counts: PinChange {0}, Rx {1}, error {2}", numPinChangedEvents, numReceivedEvents, numErrorEvents); Debug.WriteLine("Waiting for pinchange event {0}ms", iterationWaitTime); if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1)) { // A thread is in PinChangedEvent: verify that it is not in any other handler at the same time if (receivedEventHandler.NumEventsHandled != numReceivedEvents) { Fail("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent"); } if (errorEventHandler.NumEventsHandled != numErrorEvents) { Fail("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent"); } ++numPinChangedEvents; pinChangedEventHandler.ResumeHandleEvent(); threadFound = true; break; } Debug.WriteLine("Waiting for rx event {0}ms", iterationWaitTime); if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1)) { // A thread is in ReceivedEvent: verify that it is not in any other handler at the same time if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) { Fail("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent"); } if (errorEventHandler.NumEventsHandled != numErrorEvents) { Fail("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent"); } ++numReceivedEvents; receivedEventHandler.ResumeHandleEvent(); threadFound = true; break; } Debug.WriteLine("Waiting for error event {0}ms", iterationWaitTime); if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1)) { // A thread is in ErrorEvent: verify that it is not in any other handler at the same time if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) { Fail("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent"); } if (receivedEventHandler.NumEventsHandled != numReceivedEvents) { Fail("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent"); } ++numErrorEvents; errorEventHandler.ResumeHandleEvent(); threadFound = true; break; } } } Assert.True(pinChangedEventHandler.SuccessfulWait, "pinChangedEventHandler did not receive resume handle event"); Assert.True(receivedEventHandler.SuccessfulWait, "receivedEventHandler did not receive resume handle event"); Assert.True(errorEventHandler.SuccessfulWait, "errorEventHandler did not receive resume handle event"); if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) { Fail("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occurred", pinChangedEventHandler.NumEventsHandled); } if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) { Fail("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occurred", receivedEventHandler.NumEventsHandled); } if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) { Fail("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occurred", errorEventHandler.NumEventsHandled); } //[] Verify all PinChangedEvents should have occurred pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0); pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0); pinChangedEventHandler.Validate(SerialPinChange.Break, 0); //[] Verify all ReceivedEvent should have occurred receivedEventHandler.Validate(SerialData.Chars, 0); receivedEventHandler.Validate(SerialData.Eof, 0); //[] Verify all ErrorEvents should have occurred errorEventHandler.Validate(SerialError.RXParity, 0); errorEventHandler.Validate(SerialError.Frame, 0); // It's important that we close com1 BEFORE com2 (the using() block would do this the other way around normally) // This is because we have our special blocking event handlers hooked onto com1, and closing com2 is likely to // cause a pin-change event which then hangs and prevents com1 from closing. // An alternative approach would be to unhook all the event-handlers before leaving the using() block. com1.Close(); } } [ConditionalFact(nameof(HasNullModem))] public void Thread_In_PinChangedEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); Debug.WriteLine( "Verifying that if a thread is blocked in a PinChangedEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.PinChanged += pinChangedEventHandler.HandleEvent; //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged //since we are setting DtrEnable to true com2.DtrEnable = true; if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_32688ajoid Expected 1 PinChangedEvents to be fired and only {0} occurred", pinChangedEventHandler.NumEventsHandled); } Task task = Task.Run(() => com1.Close()); Thread.Sleep(5000); pinChangedEventHandler.ResumeHandleEvent(); TCSupport.WaitForTaskCompletion(task); Assert.True(pinChangedEventHandler.SuccessfulWait, "pinChangedEventHandler did not receive resume handle event"); } } [ConditionalFact(nameof(HasNullModem))] public void Thread_In_ReceivedEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); Debug.WriteLine( "Verifying that if a thread is blocked in a RecevedEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.DataReceived += receivedEventHandler.HandleEvent; //This should cause ReceivedEvent to be fired with ReceivedChars //since we are writing some bytes com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 40 }, 0, 1); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_122808aoeid Expected 1 ReceivedEvents to be fired and only {0} occurred", receivedEventHandler.NumEventsHandled); } Task task = Task.Run(() => com1.Close()); Thread.Sleep(5000); receivedEventHandler.ResumeHandleEvent(); TCSupport.WaitForTaskCompletion(task); Assert.True(receivedEventHandler.SuccessfulWait, "receivedEventHandler did not receive resume handle event"); } } [ConditionalFact(nameof(HasNullModem))] public void Thread_In_ErrorEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); Debug.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.ErrorReceived += errorEventHandler.HandleEvent; //This should cause ErrorEvent to be fired with a parity error since the //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), //and com2 is writing 0 for this bit com1.DataBits = 7; com1.Parity = Parity.Mark; com2.BaseStream.Write(new byte[1], 0, 1); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occurred", errorEventHandler.NumEventsHandled); } Task task = Task.Run(() => com1.Close()); Thread.Sleep(5000); errorEventHandler.ResumeHandleEvent(); TCSupport.WaitForTaskCompletion(task); Assert.True(errorEventHandler.SuccessfulWait, "errorEventHandler did not receive resume handle event"); } } #endregion #region Verification for Test Cases private class PinChangedEventHandler : TestEventHandler<SerialPinChange> { public PinChangedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait) { } public void HandleEvent(object source, SerialPinChangedEventArgs e) { HandleEvent(source, e.EventType); } } private class ErrorEventHandler : TestEventHandler<SerialError> { public ErrorEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait) { } public void HandleEvent(object source, SerialErrorReceivedEventArgs e) { HandleEvent(source, e.EventType); } } private class ReceivedEventHandler : TestEventHandler<SerialData> { public ReceivedEventHandler(SerialPort com, bool shouldThrow, bool shouldWait) : base(com, shouldThrow, shouldWait) { } public void HandleEvent(object source, SerialDataReceivedEventArgs e) { HandleEvent(source, e.EventType); } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using System.Text; using NPOI.OpenXmlFormats.Wordprocessing; using System.Collections.Generic; /** * <p>Sketch of XWPFTable class. Only table's text is being hold.</p> * <p>Specifies the contents of a table present in the document. A table is a set * of paragraphs (and other block-level content) arranged in rows and columns.</p> */ public class XWPFTable : IBodyElement, ISDTContents { protected StringBuilder text = new StringBuilder(); private CT_Tbl ctTbl; protected List<XWPFTableRow> tableRows; protected List<String> styleIDs; // Create a map from this XWPF-level enum to the STBorder.Enum values public enum XWPFBorderType { NIL, NONE, SINGLE, THICK, DOUBLE, DOTTED, DASHED, DOT_DASH }; internal static Dictionary<XWPFBorderType, ST_Border> xwpfBorderTypeMap; // Create a map from the STBorder.Enum values to the XWPF-level enums internal static Dictionary<ST_Border, XWPFBorderType> stBorderTypeMap; protected IBody part; static XWPFTable() { // populate enum maps xwpfBorderTypeMap = new Dictionary<XWPFBorderType, ST_Border>(); xwpfBorderTypeMap.Add(XWPFBorderType.NIL, ST_Border.nil); xwpfBorderTypeMap.Add(XWPFBorderType.NONE, ST_Border.none); xwpfBorderTypeMap.Add(XWPFBorderType.SINGLE, ST_Border.single); xwpfBorderTypeMap.Add(XWPFBorderType.THICK, ST_Border.thick); xwpfBorderTypeMap.Add(XWPFBorderType.DOUBLE, ST_Border.@double); xwpfBorderTypeMap.Add(XWPFBorderType.DOTTED, ST_Border.dotted); xwpfBorderTypeMap.Add(XWPFBorderType.DASHED, ST_Border.dashed); xwpfBorderTypeMap.Add(XWPFBorderType.DOT_DASH, ST_Border.dotDash); stBorderTypeMap = new Dictionary<ST_Border, XWPFBorderType>(); stBorderTypeMap.Add(ST_Border.nil, XWPFBorderType.NIL); stBorderTypeMap.Add(ST_Border.none, XWPFBorderType.NONE); stBorderTypeMap.Add(ST_Border.single, XWPFBorderType.SINGLE); stBorderTypeMap.Add(ST_Border.thick, XWPFBorderType.THICK); stBorderTypeMap.Add(ST_Border.@double, XWPFBorderType.DOUBLE); stBorderTypeMap.Add(ST_Border.dotted, XWPFBorderType.DOTTED); stBorderTypeMap.Add(ST_Border.dashed, XWPFBorderType.DASHED); stBorderTypeMap.Add(ST_Border.dotDash, XWPFBorderType.DOT_DASH); } public XWPFTable(CT_Tbl table, IBody part, int row, int col) : this(table, part) { CT_TblGrid ctTblGrid = table.AddNewTblGrid(); for (int j = 0; j < col; j++) { CT_TblGridCol ctGridCol= ctTblGrid.AddNewGridCol(); ctGridCol.w = 300; } for (int i = 0; i < row; i++) { XWPFTableRow tabRow = (GetRow(i) == null) ? CreateRow() : GetRow(i); for (int k = 0; k < col; k++) { if (tabRow.GetCell(k) == null) { tabRow.CreateCell(); } } } } public void SetColumnWidth(int columnIndex, ulong width) { if (this.ctTbl.tblGrid == null) return; if (columnIndex > this.ctTbl.tblGrid.gridCol.Count) { throw new ArgumentOutOfRangeException(string.Format("Column index {0} doesn't exist.", columnIndex)); } this.ctTbl.tblGrid.gridCol[columnIndex].w = width; } public XWPFTable(CT_Tbl table, IBody part) { this.part = part; this.ctTbl = table; tableRows = new List<XWPFTableRow>(); // is an empty table: I add one row and one column as default if (table.SizeOfTrArray() == 0) CreateEmptyTable(table); foreach (CT_Row row in table.GetTrList()) { StringBuilder rowText = new StringBuilder(); row.Table = table; XWPFTableRow tabRow = new XWPFTableRow(row, this); tableRows.Add(tabRow); foreach (CT_Tc cell in row.GetTcList()) { foreach (CT_P ctp in cell.GetPList()) { XWPFParagraph p = new XWPFParagraph(ctp, part); if (rowText.Length > 0) { rowText.Append('\t'); } rowText.Append(p.Text); } } if (rowText.Length > 0) { this.text.Append(rowText); this.text.Append('\n'); } } } private void CreateEmptyTable(CT_Tbl table) { // MINIMUM ELEMENTS FOR A TABLE table.AddNewTr().AddNewTc().AddNewP(); CT_TblPr tblpro = table.AddNewTblPr(); if (!tblpro.IsSetTblW()) tblpro.AddNewTblW().w = "0"; tblpro.tblW.type=(ST_TblWidth.auto); // layout tblpro.AddNewTblLayout().type = ST_TblLayoutType.autofit; // borders CT_TblBorders borders = tblpro.AddNewTblBorders(); borders.AddNewBottom().val=ST_Border.single; borders.AddNewInsideH().val = ST_Border.single; borders.AddNewInsideV().val = ST_Border.single; borders.AddNewLeft().val = ST_Border.single; borders.AddNewRight().val = ST_Border.single; borders.AddNewTop().val = ST_Border.single; //CT_TblGrid tblgrid=table.AddNewTblGrid(); //tblgrid.AddNewGridCol().w= (ulong)2000; } /** * @return ctTbl object */ internal CT_Tbl GetCTTbl() { return ctTbl; } /** * Convenience method to extract text in cells. This * does not extract text recursively in cells, and it does not * currently include text in SDT (form) components. * <p> * To get all text within a table, see XWPFWordExtractor's appendTableText * as an example. * * @return text */ public String Text { get { return text.ToString(); } } public void AddNewRowBetween(int start, int end) { throw new NotImplementedException(); } /** * add a new column for each row in this table */ public void AddNewCol() { if (ctTbl.SizeOfTrArray() == 0) { CreateRow(); } for (int i = 0; i < ctTbl.SizeOfTrArray(); i++) { XWPFTableRow tabRow = new XWPFTableRow(ctTbl.GetTrArray(i), this); tabRow.CreateCell(); } } /** * create a new XWPFTableRow object with as many cells as the number of columns defined in that moment * * @return tableRow */ public XWPFTableRow CreateRow() { int sizeCol = ctTbl.SizeOfTrArray() > 0 ? ctTbl.GetTrArray(0) .SizeOfTcArray() : 0; XWPFTableRow tabRow = new XWPFTableRow(ctTbl.AddNewTr(), this); AddColumn(tabRow, sizeCol); tableRows.Add(tabRow); return tabRow; } /** * @param pos - index of the row * @return the row at the position specified or null if no rows is defined or if the position is greather than the max size of rows array */ public XWPFTableRow GetRow(int pos) { if (pos >= 0 && pos < ctTbl.SizeOfTrArray()) { //return new XWPFTableRow(ctTbl.GetTrArray(pos)); return Rows[(pos)]; } return null; } /** * @return width value */ public int Width { get { CT_TblPr tblPr = GetTrPr(); return tblPr.IsSetTblW() ? int.Parse(tblPr.tblW.w) : -1; } set { CT_TblPr tblPr = GetTrPr(); CT_TblWidth tblWidth = tblPr.IsSetTblW() ? tblPr.tblW : tblPr .AddNewTblW(); tblWidth.w = value.ToString(); tblWidth.type = ST_TblWidth.pct; } } /** * @return number of rows in table */ public int NumberOfRows { get { return ctTbl.SizeOfTrArray(); } } private CT_TblPr GetTrPr() { return (ctTbl.tblPr != null) ? ctTbl.tblPr : ctTbl .AddNewTblPr(); } private void AddColumn(XWPFTableRow tabRow, int sizeCol) { if (sizeCol > 0) { for (int i = 0; i < sizeCol; i++) { tabRow.CreateCell(); } } } /** * Get the StyleID of the table * @return style-ID of the table */ public String StyleID { get { String styleId = null; CT_TblPr tblPr = ctTbl.tblPr; if (tblPr != null) { CT_String styleStr = tblPr.tblStyle; if (styleStr != null) { styleId = styleStr.val; } } return styleId; } set { CT_TblPr tblPr = GetTrPr(); CT_String styleStr = tblPr.tblStyle; if (styleStr == null) { styleStr = tblPr.AddNewTblStyle(); } styleStr.val = value; } } public XWPFBorderType InsideHBorderType { get { XWPFBorderType bt = XWPFBorderType.NONE; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; bt = stBorderTypeMap[border.val]; } } return bt; } } public int InsideHBorderSize { get { int size = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; size = (int)border.sz; } } return size; } } public int InsideHBorderSpace { get { int space = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; space = (int)border.space; } } return space; } } public String InsideHBorderColor { get { String color = null; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideH()) { CT_Border border = ctb.insideH; color = border.color; } } return color; } } public XWPFBorderType InsideVBorderType { get { XWPFBorderType bt = XWPFBorderType.NONE; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; bt = stBorderTypeMap[border.val]; } } return bt; } } public int InsideVBorderSize { get { int size = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; size = (int)border.sz; } } return size; } } public int InsideVBorderSpace { get { int space = -1; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; space = (int)border.space; } } return space; } } public String InsideVBorderColor { get { String color = null; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblBorders()) { CT_TblBorders ctb = tblPr.tblBorders; if (ctb.IsSetInsideV()) { CT_Border border = ctb.insideV; color = border.color; } } return color; } } public int RowBandSize { get { int size = 0; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblStyleRowBandSize()) { CT_DecimalNumber rowSize = tblPr.tblStyleRowBandSize; int.TryParse(rowSize.val, out size); } return size; } set { CT_TblPr tblPr = GetTrPr(); CT_DecimalNumber rowSize = tblPr.IsSetTblStyleRowBandSize() ? tblPr.tblStyleRowBandSize : tblPr.AddNewTblStyleRowBandSize(); rowSize.val = value.ToString(); } } public int ColBandSize { get { int size = 0; CT_TblPr tblPr = GetTrPr(); if (tblPr.IsSetTblStyleColBandSize()) { CT_DecimalNumber colSize = tblPr.tblStyleColBandSize; int.TryParse(colSize.val, out size); } return size; } set { CT_TblPr tblPr = GetTrPr(); CT_DecimalNumber colSize = tblPr.IsSetTblStyleColBandSize() ? tblPr.tblStyleColBandSize : tblPr.AddNewTblStyleColBandSize(); colSize.val = value.ToString(); } } public void SetTopBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.top!=null ? ctb.top : ctb.AddNewTop(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetBottomBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.bottom != null ? ctb.bottom : ctb.AddNewBottom(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetLeftBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.left != null ? ctb.left : ctb.AddNewLeft(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetRightBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.right != null ? ctb.right : ctb.AddNewRight(); b.val = xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetInsideHBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.IsSetInsideH() ? ctb.insideH : ctb.AddNewInsideH(); b.val = (xwpfBorderTypeMap[(type)]); b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetInsideVBorder(XWPFBorderType type, int size, int space, String rgbColor) { CT_TblPr tblPr = GetTrPr(); CT_TblBorders ctb = tblPr.IsSetTblBorders() ? tblPr.tblBorders : tblPr.AddNewTblBorders(); CT_Border b = ctb.IsSetInsideV() ? ctb.insideV : ctb.AddNewInsideV(); b.val = (xwpfBorderTypeMap[type]); b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public int CellMarginTop { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.top; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public int CellMarginLeft { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.left; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public int CellMarginBottom { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.bottom; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public int CellMarginRight { get { int margin = 0; CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.tblCellMar; if (tcm != null) { CT_TblWidth tw = tcm.right; if (tw != null) { int.TryParse(tw.w, out margin); } } return margin; } } public void SetCellMargins(int top, int left, int bottom, int right) { CT_TblPr tblPr = GetTrPr(); CT_TblCellMar tcm = tblPr.IsSetTblCellMar() ? tblPr.tblCellMar : tblPr.AddNewTblCellMar(); CT_TblWidth tw = tcm.IsSetLeft() ? tcm.left : tcm.AddNewLeft(); tw.type = (ST_TblWidth.dxa); tw.w = left.ToString(); tw = tcm.IsSetTop() ? tcm.top : tcm.AddNewTop(); tw.type = (ST_TblWidth.dxa); tw.w = top.ToString(); tw = tcm.IsSetBottom() ? tcm.bottom : tcm.AddNewBottom(); tw.type = (ST_TblWidth.dxa); tw.w = bottom.ToString(); tw = tcm.IsSetRight() ? tcm.right : tcm.AddNewRight(); tw.type = (ST_TblWidth.dxa); tw.w = right.ToString(); } /** * add a new Row to the table * * @param row the row which should be Added */ public void AddRow(XWPFTableRow row) { ctTbl.AddNewTr(); ctTbl.SetTrArray(this.NumberOfRows-1, row.GetCTRow()); tableRows.Add(row); } /** * add a new Row to the table * at position pos * @param row the row which should be Added */ public bool AddRow(XWPFTableRow row, int pos) { if (pos >= 0 && pos <= tableRows.Count) { ctTbl.InsertNewTr(pos); ctTbl.SetTrArray(pos, row.GetCTRow()); tableRows.Insert(pos, row); return true; } return false; } /** * inserts a new tablerow * @param pos * @return the inserted row */ public XWPFTableRow InsertNewTableRow(int pos) { if(pos >= 0 && pos <= tableRows.Count){ CT_Row row = ctTbl.InsertNewTr(pos); XWPFTableRow tableRow = new XWPFTableRow(row, this); tableRows.Insert(pos, tableRow); return tableRow; } return null; } /** * Remove a row at position pos from the table * @param pos position the Row in the Table */ public bool RemoveRow(int pos) { if (pos >= 0 && pos < tableRows.Count) { if (ctTbl.SizeOfTrArray() > 0) { ctTbl.RemoveTr(pos); } tableRows.RemoveAt(pos); return true; } return false; } public List<XWPFTableRow> Rows { get { return tableRows; } } /** * returns the type of the BodyElement Table * @see NPOI.XWPF.UserModel.IBodyElement#getElementType() */ public BodyElementType ElementType { get { return BodyElementType.TABLE; } } public IBody Body { get { return part; } } /** * returns the part of the bodyElement * @see NPOI.XWPF.UserModel.IBody#getPart() */ public POIXMLDocumentPart Part { get { if (part != null) { return part.Part; } return null; } } /** * returns the partType of the bodyPart which owns the bodyElement * @see NPOI.XWPF.UserModel.IBody#getPartType() */ public BodyType PartType { get { return part.PartType; } } /** * returns the XWPFRow which belongs to the CTRow row * if this row is not existing in the table null will be returned */ public XWPFTableRow GetRow(CT_Row row) { for(int i=0; i<Rows.Count; i++){ if(Rows[(i)].GetCTRow() == row) return GetRow(i); } return null; } }// end class }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole, Terje Sandstrom // // 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 NUnit.Framework; namespace NUnit.Tests { namespace Assemblies { /// <summary> /// Constant definitions for the mock-assembly dll. /// </summary> public class MockAssembly { public const int Classes = 9; public const int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly public const int Tests = MockTestFixture.Tests + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + IgnoredFixture.Tests + ExplicitFixture.Tests + BadFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests; public const int Suites = MockTestFixture.Suites + Singletons.OneTestCase.Suites + TestAssembly.MockTestFixture.Suites + IgnoredFixture.Suites + ExplicitFixture.Suites + BadFixture.Suites + FixtureWithTestCases.Suites + ParameterizedFixture.Suites + GenericFixtureConstants.Suites + NamespaceSuites; public const int Nodes = Tests + Suites; public const int ExplicitFixtures = 1; public const int SuitesRun = Suites - ExplicitFixtures; public const int Ignored = MockTestFixture.Ignored + IgnoredFixture.Tests; public const int Explicit = MockTestFixture.Explicit + ExplicitFixture.Tests; public const int NotRun = Ignored + Explicit + NotRunnable; public const int TestsRun = Tests - NotRun; public const int ResultCount = Tests - Explicit; public const int Errors = MockTestFixture.Errors; public const int Failures = MockTestFixture.Failures; public const int NotRunnable = MockTestFixture.NotRunnable + BadFixture.Tests; public const int ErrorsAndFailures = Errors + Failures + NotRunnable; public const int Inconclusive = MockTestFixture.Inconclusive; public const int Success = TestsRun - Errors - Failures - Inconclusive; public const int Categories = MockTestFixture.Categories; } [TestFixture(Description="Fake Test Fixture")] [Category("FixtureCategory")] public class MockTestFixture { public const int Tests = 11; public const int Suites = 1; public const int Ignored = 1; public const int Explicit = 1; public const int NotRun = Ignored + Explicit; public const int TestsRun = Tests - NotRun; public const int ResultCount = Tests - Explicit; public const int Failures = 1; public const int Errors = 1; public const int NotRunnable = 2; public const int ErrorsAndFailures = Errors + Failures + NotRunnable; public const int Inconclusive = 1; public const int Categories = 5; public const int MockCategoryTests = 2; [Test(Description="Mock Test #1")] public void MockTest1() {} [Test] [Category("MockCategory")] [Property("Severity","Critical")] [Description("This is a really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long description")] public void MockTest2() {} [Test] [Category("MockCategory")] [Category("AnotherCategory")] public void MockTest3() { Assert.Pass("Succeeded!"); } [Test] protected static void MockTest5() {} [Test] public void FailingTest() { Assert.Fail("Intentional failure"); } [Test, Property("TargetMethod", "SomeClassName"), Property("Size", 5), /*Property("TargetType", typeof( System.Threading.Thread ))*/] public void TestWithManyProperties() {} [Test] [Ignore("ignoring this test method for now")] [Category("Foo")] public void MockTest4() {} [Test, Explicit] [Category( "Special" )] public void ExplicitlyRunTest() {} [Test] public void NotRunnableTest( int a, int b) { } [Test] public void InconclusiveTest() { Assert.Inconclusive("No valid data"); } [Test] public void TestWithException() { MethodThrowsException(); } private void MethodThrowsException() { throw new Exception("Intentional Exception"); } } } namespace Singletons { [TestFixture] public class OneTestCase { public const int Tests = 1; public const int Suites = 1; [Test] public virtual void TestCase() {} } } namespace TestAssembly { [TestFixture] public class MockTestFixture { public const int Tests = 1; public const int Suites = 1; [Test] public void MyTest() { } } } [TestFixture, Ignore("BECAUSE")] public class IgnoredFixture { public const int Tests = 3; public const int Suites = 1; [Test] public void Test1() { } [Test] public void Test2() { } [Test] public void Test3() { } } [TestFixture,Explicit] public class ExplicitFixture { public const int Tests = 2; public const int Suites = 1; public const int Nodes = Tests + Suites; [Test] public void Test1() { } [Test] public void Test2() { } } [TestFixture] public class BadFixture { public const int Tests = 1; public const int Suites = 1; public BadFixture(int val) { } [Test] public void SomeTest() { } } [TestFixture] public class FixtureWithTestCases { public const int Tests = 4; public const int Suites = 3; [TestCase(2, 2, ExpectedResult=4)] [TestCase(9, 11, ExpectedResult=20)] public int MethodWithParameters(int x, int y) { return x+y; } [TestCase(2, 4)] [TestCase(9.2, 11.7)] public void GenericMethod<T>(T x, T y) { } } [TestFixture(5)] [TestFixture(42)] public class ParameterizedFixture { public const int Tests = 4; public const int Suites = 3; public ParameterizedFixture(int num) { } [Test] public void Test1() { } [Test] public void Test2() { } } public class GenericFixtureConstants { public const int Tests = 4; public const int Suites = 3; } [TestFixture(5)] [TestFixture(11.5)] public class GenericFixture<T> { public GenericFixture(T num){ } [Test] public void Test1() { } [Test] public void Test2() { } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal abstract class PlaceholderLocalSymbol : EELocalSymbolBase { private readonly MethodSymbol _method; private readonly string _name; private readonly TypeSymbol _type; internal readonly string DisplayName; internal PlaceholderLocalSymbol(MethodSymbol method, string name, string displayName, TypeSymbol type) { _method = method; _name = name; _type = type; this.DisplayName = displayName; } internal static LocalSymbol Create( TypeNameDecoder<PEModuleSymbol, TypeSymbol> typeNameDecoder, MethodSymbol containingMethod, AssemblySymbol sourceAssembly, Alias alias) { var typeName = alias.Type; Debug.Assert(typeName.Length > 0); var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName); Debug.Assert((object)type != null); var dynamicFlagsInfo = alias.CustomTypeInfo.ToDynamicFlagsCustomTypeInfo(); if (dynamicFlagsInfo.Any()) { var flagsBuilder = ArrayBuilder<bool>.GetInstance(); dynamicFlagsInfo.CopyTo(flagsBuilder); var dynamicType = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags( type, sourceAssembly, RefKind.None, flagsBuilder.ToImmutableAndFree(), checkLength: false); Debug.Assert(dynamicType != null); Debug.Assert(dynamicType != type); type = dynamicType; } var name = alias.FullName; var displayName = alias.Name; switch (alias.Kind) { case DkmClrAliasKind.Exception: return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetExceptionMethodName); case DkmClrAliasKind.StowedException: return new ExceptionLocalSymbol(containingMethod, name, displayName, type, ExpressionCompilerConstants.GetStowedExceptionMethodName); case DkmClrAliasKind.ReturnValue: { int index; PseudoVariableUtilities.TryParseReturnValueIndex(name, out index); Debug.Assert(index >= 0); return new ReturnValueLocalSymbol(containingMethod, name, displayName, type, index); } case DkmClrAliasKind.ObjectId: return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: false); case DkmClrAliasKind.Variable: return new ObjectIdLocalSymbol(containingMethod, type, name, displayName, isWritable: true); default: throw ExceptionUtilities.UnexpectedValue(alias.Kind); } } internal override LocalDeclarationKind DeclarationKind { get { return LocalDeclarationKind.RegularVariable; } } internal override SyntaxToken IdentifierToken { get { throw ExceptionUtilities.Unreachable; } } public override TypeSymbol Type { get { return _type; } } internal override bool IsPinned { get { return false; } } internal override bool IsCompilerGenerated { get { return true; } } internal override RefKind RefKind { get { return RefKind.None; } } public override Symbol ContainingSymbol { get { return _method; } } public override ImmutableArray<Location> Locations { get { return NoLocations; } } public override string Name { get { return _name; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } internal abstract override bool IsWritable { get; } internal override EELocalSymbolBase ToOtherMethod(MethodSymbol method, TypeMap typeMap) { // Placeholders should be rewritten (as method calls) // rather than copied as locals to the target method. throw ExceptionUtilities.Unreachable; } /// <summary> /// Rewrite the local reference as a call to a synthesized method. /// </summary> internal abstract BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics); internal static BoundExpression ConvertToLocalType(CSharpCompilation compilation, BoundExpression expr, TypeSymbol type, DiagnosticBag diagnostics) { if (type.IsPointerType()) { var syntax = expr.Syntax; var intPtrType = compilation.GetSpecialType(SpecialType.System_IntPtr); Binder.ReportUseSiteDiagnostics(intPtrType, diagnostics, syntax); MethodSymbol conversionMethod; if (Binder.TryGetSpecialTypeMember(compilation, SpecialMember.System_IntPtr__op_Explicit_ToPointer, syntax, diagnostics, out conversionMethod)) { var temp = ConvertToLocalTypeHelper(compilation, expr, intPtrType, diagnostics); expr = BoundCall.Synthesized( syntax, receiverOpt: null, method: conversionMethod, arg0: temp); } else { return new BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundNode>(expr), type); } } return ConvertToLocalTypeHelper(compilation, expr, type, diagnostics); } private static BoundExpression ConvertToLocalTypeHelper(CSharpCompilation compilation, BoundExpression expr, TypeSymbol type, DiagnosticBag diagnostics) { // NOTE: This conversion can fail if some of the types involved are from not-yet-loaded modules. // For example, if System.Exception hasn't been loaded, then this call will fail for $stowedexception. HashSet<DiagnosticInfo> useSiteDiagnostics = null; var conversion = compilation.Conversions.ClassifyConversionFromExpression(expr, type, ref useSiteDiagnostics); diagnostics.Add(expr.Syntax, useSiteDiagnostics); Debug.Assert(conversion.IsValid || diagnostics.HasAnyErrors()); return BoundConversion.Synthesized( expr.Syntax, expr, conversion, @checked: false, explicitCastInCode: false, constantValueOpt: null, type: type, hasErrors: !conversion.IsValid); } internal static MethodSymbol GetIntrinsicMethod(CSharpCompilation compilation, string methodName) { var type = compilation.GetTypeByMetadataName(ExpressionCompilerConstants.IntrinsicAssemblyTypeMetadataName); var members = type.GetMembers(methodName); Debug.Assert(members.Length == 1); return (MethodSymbol)members[0]; } } }
// 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.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Security.Principal { [Flags] internal enum PolicyRights { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002, POLICY_GET_PRIVATE_INFORMATION = 0x00000004, POLICY_TRUST_ADMIN = 0x00000008, POLICY_CREATE_ACCOUNT = 0x00000010, POLICY_CREATE_SECRET = 0x00000020, POLICY_CREATE_PRIVILEGE = 0x00000040, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100, POLICY_AUDIT_LOG_ADMIN = 0x00000200, POLICY_SERVER_ADMIN = 0x00000400, POLICY_LOOKUP_NAMES = 0x00000800, POLICY_NOTIFICATION = 0x00001000, } internal static class Win32 { internal const int FALSE = 0; // // Wrapper around advapi32.LsaOpenPolicy // internal static SafeLsaPolicyHandle LsaOpenPolicy( string systemName, PolicyRights rights) { SafeLsaPolicyHandle policyHandle; var attributes = new Interop.OBJECT_ATTRIBUTES(); uint error = Interop.Advapi32.LsaOpenPolicy(systemName, ref attributes, (int)rights, out policyHandle); if (error == 0) { return policyHandle; } else if (error == Interop.StatusOptions.STATUS_ACCESS_DENIED) { throw new UnauthorizedAccessException(); } else if (error == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || error == Interop.StatusOptions.STATUS_NO_MEMORY) { throw new OutOfMemoryException(); } else { uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(error); throw new Win32Exception(unchecked((int)win32ErrorCode)); } } internal static byte[] ConvertIntPtrSidToByteArraySid(IntPtr binaryForm) { byte[] ResultSid; // // Verify the revision (just sanity, should never fail to be 1) // byte Revision = Marshal.ReadByte(binaryForm, 0); if (Revision != SecurityIdentifier.Revision) { throw new ArgumentException(SR.IdentityReference_InvalidSidRevision, nameof(binaryForm)); } // // Need the subauthority count in order to figure out how many bytes to read // byte SubAuthorityCount = Marshal.ReadByte(binaryForm, 1); if (SubAuthorityCount < 0 || SubAuthorityCount > SecurityIdentifier.MaxSubAuthorities) { throw new ArgumentException(SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, SecurityIdentifier.MaxSubAuthorities), nameof(binaryForm)); } // // Compute the size of the binary form of this SID and allocate the memory // int BinaryLength = 1 + 1 + 6 + SubAuthorityCount * 4; ResultSid = new byte[BinaryLength]; // // Extract the data from the returned pointer // Marshal.Copy(binaryForm, ResultSid, 0, BinaryLength); return ResultSid; } // // Wrapper around advapi32.ConvertStringSidToSidW // internal static int CreateSidFromString( string stringSid, out byte[] resultSid ) { int ErrorCode; IntPtr ByteArray = IntPtr.Zero; try { if (FALSE == Interop.Advapi32.ConvertStringSidToSid(stringSid, out ByteArray)) { ErrorCode = Marshal.GetLastWin32Error(); goto Error; } resultSid = ConvertIntPtrSidToByteArraySid(ByteArray); } finally { // // Now is a good time to get rid of the returned pointer // Interop.Kernel32.LocalFree(ByteArray); } // // Now invoke the SecurityIdentifier factory method to create the result // return Interop.Errors.ERROR_SUCCESS; Error: resultSid = null; return ErrorCode; } // // Wrapper around advapi32.CreateWellKnownSid // internal static int CreateWellKnownSid( WellKnownSidType sidType, SecurityIdentifier domainSid, out byte[] resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // uint length = (uint)SecurityIdentifier.MaxBinaryLength; resultSid = new byte[length]; if (FALSE != Interop.Advapi32.CreateWellKnownSid((int)sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length)) { return Interop.Errors.ERROR_SUCCESS; } else { resultSid = null; return Marshal.GetLastWin32Error(); } } // // Wrapper around advapi32.EqualDomainSid // internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2) { if (sid1 == null || sid2 == null) { return false; } else { bool result; byte[] BinaryForm1 = new byte[sid1.BinaryLength]; sid1.GetBinaryForm(BinaryForm1, 0); byte[] BinaryForm2 = new byte[sid2.BinaryLength]; sid2.GetBinaryForm(BinaryForm2, 0); return (Interop.Advapi32.IsEqualDomainSid(BinaryForm1, BinaryForm2, out result) == FALSE ? false : result); } } /// <summary> /// Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST /// </summary> internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains) { Debug.Assert(referencedDomains != null, "referencedDomains != null"); // We don't know the real size of the referenced domains yet, so we need to set an initial // size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of // the domains. referencedDomains.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>()); Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0); unsafe { byte* pRdl = null; try { referencedDomains.AcquirePointer(ref pRdl); // If there is a trust information list, then the buffer size is the end of that list minus // the beginning of the domain list. Otherwise, then the buffer is just the size of the // referenced domain list structure, which is what we defaulted to. if (domainList.Domains != IntPtr.Zero) { Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains; pTrustInformation = pTrustInformation + domainList.Entries; long bufferSize = (byte*)pTrustInformation - pRdl; Debug.Assert(bufferSize > 0, "bufferSize > 0"); referencedDomains.Initialize((ulong)bufferSize); } } finally { if (pRdl != null) referencedDomains.ReleasePointer(); } } } // // Wrapper around avdapi32.GetWindowsAccountDomainSid // internal static int GetWindowsAccountDomainSid( SecurityIdentifier sid, out SecurityIdentifier resultSid ) { // // Passing an array as big as it can ever be is a small price to pay for // not having to P/Invoke twice (once to get the buffer, once to get the data) // byte[] BinaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength; byte[] resultSidBinary = new byte[sidLength]; if (FALSE != Interop.Advapi32.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength)) { resultSid = new SecurityIdentifier(resultSidBinary, 0); return Interop.Errors.ERROR_SUCCESS; } else { resultSid = null; return Marshal.GetLastWin32Error(); } } // // Wrapper around advapi32.IsWellKnownSid // internal static bool IsWellKnownSid( SecurityIdentifier sid, WellKnownSidType type ) { byte[] BinaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(BinaryForm, 0); if (FALSE == Interop.Advapi32.IsWellKnownSid(BinaryForm, (int)type)) { return false; } else { return true; } } } }
// Copyright (c) 2021 Alachisoft // // 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 Alachisoft.NCache.Caching; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Common.Util; using System.Collections.Generic; using System.Text; using Alachisoft.NCache.SocketServer.RuntimeLogging; using Alachisoft.NCache.Common.Caching; using Alachisoft.NCache.Common.Locking; using Alachisoft.NCache.Util; using Alachisoft.NCache.Common.DataSource; using Alachisoft.NCache.Runtime.Caching; using Alachisoft.NCache.Caching.Pooling; using Alachisoft.NCache.Common.Pooling; using Alachisoft.NCache.SocketServer.Pooling; using Alachisoft.NCache.SocketServer.Util; namespace Alachisoft.NCache.SocketServer.Command { class GetCommand : CommandBase { private struct CommandInfo { public long RequestId; public string Key; public BitSet FlagMap; public LockAccessType LockAccessType; public object LockId; public TimeSpan LockTimeout; public ulong CacheItemVersion; public string ProviderName; public int ThreadId; } private OperationResult _getResult = OperationResult.Success; CommandInfo cmdInfo; private readonly BitSet _bitSet; private readonly OperationContext _operationContext; private readonly Common.Protobuf.GetResponse _getResponse; internal override OperationResult OperationResult { get { return _getResult; } } public override bool CanHaveLargedata { get { return true; } } public GetCommand() { _bitSet = new BitSet(); _operationContext = new OperationContext(); _getResponse = new Common.Protobuf.GetResponse(); } public override string GetCommandParameters(out string commandName) { StringBuilder details = new StringBuilder(); commandName = "Get"; details.Append("Command Keys: " + cmdInfo.Key); details.Append(" ; "); return details.ToString(); } //PROTOBUF public override void ExecuteCommand(ClientManager clientManager, Alachisoft.NCache.Common.Protobuf.Command command) { int dataLength = 0; int overload; string exception = null; System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); try { overload = command.MethodOverload; cmdInfo = ParseCommand(command, clientManager); } catch (ArgumentOutOfRangeException arEx) { if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error( "GetCommand", "command: " + command + " Error" + arEx); _getResult = OperationResult.Failure; if (!base.immatureId.Equals("-2")) _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(arEx, command.requestID,command.commandID, clientManager.ClientVersion)); return; } catch (Exception exc) { _getResult = OperationResult.Failure; if (!base.immatureId.Equals("-2")) _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion)); return; } Alachisoft.NCache.Common.Protobuf.GetResponse getResponse = null; CompressedValueEntry flagValueEntry = null; OperationContext operationContext = null; NCache nCache = clientManager.CmdExecuter as NCache; try { object lockId = cmdInfo.LockId; ulong version = cmdInfo.CacheItemVersion; DateTime lockDate = new DateTime(); operationContext = _operationContext; operationContext.Add(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); CommandsUtil.PopulateClientIdInContext(ref operationContext, clientManager.ClientAddress); if (cmdInfo.LockAccessType == LockAccessType.ACQUIRE) { operationContext.Add(OperationContextFieldName.ClientThreadId, clientManager.ClientID); operationContext.Add(OperationContextFieldName.ClientThreadId, cmdInfo.ThreadId); operationContext.Add(OperationContextFieldName.IsRetryOperation, command.isRetryCommand); } flagValueEntry = nCache.Cache.GetGroup(cmdInfo.Key, cmdInfo.FlagMap, null,null, ref version, ref lockId, ref lockDate, cmdInfo.LockTimeout, cmdInfo.LockAccessType, operationContext); stopWatch.Stop(); UserBinaryObject ubObj = null; getResponse = _getResponse; if (flagValueEntry != null) { if (flagValueEntry.Value is UserBinaryObject) ubObj = (UserBinaryObject)flagValueEntry.Value; else { var flag = flagValueEntry.Flag; ubObj = (UserBinaryObject)nCache.Cache.SocketServerDataService.GetClientData(flagValueEntry.Value, ref flag, LanguageContext.DOTNET); } if(flagValueEntry.Value!=null) { getResponse.itemType = MiscUtil.EntryTypeToProtoItemType(flagValueEntry.Type);// (Alachisoft.NCache.Common.Protobuf.CacheItemType.ItemType)flagValueEntry.Type; } } if (ubObj != null) dataLength = ubObj.Length; if (clientManager.ClientVersion >= 5000) { if (lockId != null) { getResponse.lockId = lockId.ToString(); } getResponse.requestId = cmdInfo.RequestId; getResponse.commandID = command.commandID; getResponse.lockTime = lockDate.Ticks; getResponse.version = version; if (ubObj == null) { // response.get = getResponse; _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(getResponse, Common.Protobuf.Response.Type.GET)); } else { //_dataPackageArray = ubObj.Data; getResponse.flag = flagValueEntry.Flag.Data; getResponse.data.AddRange(ubObj.DataList); // response.get = getResponse; _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(getResponse, Common.Protobuf.Response.Type.GET)); } } else { Alachisoft.NCache.Common.Protobuf.Response response = Stash.ProtobufResponse; response.requestId = Convert.ToInt64(cmdInfo.RequestId); response.commandID = command.commandID; response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.GET; if (lockId != null) { getResponse.lockId = lockId.ToString(); } getResponse.lockTime = lockDate.Ticks; getResponse.version = version; if (ubObj == null) { response.get = getResponse; _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response)); } else { getResponse.flag = flagValueEntry.Flag.Data; getResponse.data.AddRange(ubObj.DataList); response.get = getResponse; _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response)); } } } catch (Exception exc) { exception = exc.ToString(); _getResult = OperationResult.Failure; _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion)); } finally { operationContext?.MarkFree(NCModulesConstants.SocketServer); TimeSpan executionTime = stopWatch.Elapsed; try { if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging) { int resutlt = 0; if (getResponse != null) { resutlt = dataLength; } string methodName = null; if (cmdInfo.LockAccessType == LockAccessType.ACQUIRE) methodName = MethodsName.GET.ToLower(); else methodName = MethodsName.GET.ToLower(); APILogItemBuilder log = new APILogItemBuilder(methodName); log.GenerateGetCommandAPILogItem(cmdInfo.Key, null,null, (long)cmdInfo.CacheItemVersion, cmdInfo.LockAccessType, cmdInfo.LockTimeout, cmdInfo.LockId, cmdInfo.ProviderName, overload, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString(), resutlt); } } catch { } if(flagValueEntry != null) { MiscUtil.ReturnCompressedEntryToPool(flagValueEntry, clientManager.CacheTransactionalPool); MiscUtil.ReturnEntryToPool(flagValueEntry.Entry, clientManager.CacheTransactionalPool); } } //} //if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("GetCmd.Exec", "cmd executed on cache"); } //PROTOBUF private CommandInfo ParseCommand(Alachisoft.NCache.Common.Protobuf.Command command, ClientManager clientManager) { CommandInfo cmdInfo = new CommandInfo(); Alachisoft.NCache.Common.Protobuf.GetCommand getCommand = command.getCommand; cmdInfo.CacheItemVersion = getCommand.version; BitSet bitset = _bitSet; bitset.Data =((byte)getCommand.flag); cmdInfo.FlagMap = bitset; cmdInfo.Key = clientManager.CacheTransactionalPool.StringPool.GetString(getCommand.key); cmdInfo.LockAccessType = (LockAccessType)getCommand.lockInfo.lockAccessType; cmdInfo.LockId = getCommand.lockInfo.lockId; cmdInfo.LockTimeout = new TimeSpan(getCommand.lockInfo.lockTimeout); cmdInfo.ProviderName = getCommand.providerName.Length == 0 ? null : getCommand.providerName; cmdInfo.RequestId = getCommand.requestId; cmdInfo.ThreadId = getCommand.threadId; return cmdInfo; } public sealed override void ResetLeasable() { base.ResetLeasable(); _bitSet.ResetLeasable(); _getResponse.ResetLeasable(); _operationContext.ResetLeasable(); } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using ESRI.ArcLogistics.App.GridHelpers; using ESRI.ArcLogistics.BreaksHelpers; using ESRI.ArcLogistics.DomainObjects; using Xceed.Wpf.DataGrid; using AppData = ESRI.ArcLogistics.Data; using ESRI.ArcLogistics.App.Validators; using ESRI.ArcLogistics.Data; namespace ESRI.ArcLogistics.App.Pages.Wizards { /// <summary> /// Interaction logic for FleetSetupWizardRoutesPage.xaml /// </summary> internal partial class FleetSetupWizardRoutesPage : WizardPageBase, ISupportBack, ISupportNext, ISupportCancel { #region Constructors /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public FleetSetupWizardRoutesPage() { InitializeComponent(); // init handlers this.Loaded += new RoutedEventHandler(fleetSetupWizardRoutesPage_Loaded); this.Unloaded += new RoutedEventHandler(fleetSetupWizardRoutesPage_Unloaded); } #endregion // Constructors #region ISupportBack members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Occurs when "Back" button clicked. /// </summary> public event EventHandler BackRequired; #endregion // ISupportBack members #region ISupportNext members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Occurs when "Next" button clicked. /// </summary> public event EventHandler NextRequired; #endregion // ISupportNext members #region ISupportCancel members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Occurs when "Cancel" button clicked. /// </summary> public event EventHandler CancelRequired; #endregion // ISupportCancel members #region Private properties /// <summary> /// Specialized context. /// </summary> private FleetSetupWizardDataContext DataKeeper { get { return DataContext as FleetSetupWizardDataContext; } } #endregion #region Event handlers /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Page loaded handler. /// </summary> private void fleetSetupWizardRoutesPage_Loaded(object sender, RoutedEventArgs e) { Debug.Assert(0 < DataKeeper.Locations.Count); // locations must present // If there are no default breaks - add default break to project configuration. if (DataKeeper.Project.BreaksSettings.BreaksType == null) { DataKeeper.Project.BreaksSettings.BreaksType = BreakType.TimeWindow; var timeWindowBreak = new TimeWindowBreak(); DataKeeper.Project.BreaksSettings.DefaultBreaks.Add(timeWindowBreak); } // init controls if (!_isInited) _InitControls(); _InitDataGridCollection(); // validate controls _UpdatePageState(); vehicleNumberTextBox.Focus(); vehicleNumberTextBox.SelectAll(); } /// <summary> /// Page unloaded handler. /// </summary> private void fleetSetupWizardRoutesPage_Unloaded(object sender, RoutedEventArgs e) { _StoreChanges(); } /// <summary> /// Vehicle number text changed handler. /// </summary> private void vehicleNumberTextBox_TextChanged(object sender, TextChangedEventArgs e) { if (_isInited) { _UpdatePageState(); _UpdateRoutes(); } } /// <summary> /// Text box changed handler. /// </summary> private void maxTextBox_TextChanged(object sender, TextChangedEventArgs e) { if (_isInited) { _UpdateRoutesValues(); _UpdatePageState(); } } /// <summary> /// Time text box changed handler. /// </summary> private void textBoxTime_TimeChanged(object sender, RoutedEventArgs e) { if (_isInited) _UpdateRoutesValues(); } /// <summary> /// "Back" button click handler. /// </summary> private void buttonBack_Click(object sender, RoutedEventArgs e) { if (null != BackRequired) BackRequired(this, EventArgs.Empty); } /// <summary> /// "Next" button click handler. /// </summary> private void buttonNext_Click(object sender, RoutedEventArgs e) { if (CanBeLeftValidator<Route>.IsValid(DataKeeper.Routes)) { if (null != NextRequired) NextRequired(this, EventArgs.Empty); } else CanBeLeftValidator<Route>.ShowErrorMessagesInMessageWindow(DataKeeper.Routes); } /// <summary> /// "Cancel" button click handler. /// </summary> private void buttonCancel_Click(object sender, RoutedEventArgs e) { if (null != CancelRequired) CancelRequired(this, EventArgs.Empty); } /// <summary> /// vehicleNumberTextBox previewkeydown handler. /// </summary> private void vehicleNumberTextBox_PreviewKeyDown(object sender, KeyEventArgs e) { Key pressedKey = e.Key; if (pressedKey == Key.Up) _IncrementVehicleNumber(); else if (pressedKey == Key.Down) _DecrementVehicleNumber(); // else do nothing } /// <summary> /// vehicleNumberTextBox mousewheel handler. /// </summary> private void vehicleNumberTextBox_MouseWheel(object sender, MouseWheelEventArgs e) { int delta = e.Delta; if (delta > 0) _IncrementVehicleNumber(); else if (delta < 0) _DecrementVehicleNumber(); // else do nothing } /// <summary> /// incrementButton click handler. /// </summary> private void incrementButton_Click(object sender, RoutedEventArgs e) { _IncrementVehicleNumber(); } /// <summary> /// decrementButton click handler. /// </summary> private void decrementButton_Click(object sender, RoutedEventArgs e) { _DecrementVehicleNumber(); } /// <summary> /// Items collection changed handler. /// </summary> private void _items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { _UpdateLayout(); } /// <summary> /// xceedGrid item source changed handler. /// </summary> private void xceedGrid_OnItemSourceChanged(object sender, EventArgs e) { if (null != _items) _items.CollectionChanged -= _items_CollectionChanged; _items = xceedGrid.Items; _items.CollectionChanged += new NotifyCollectionChangedEventHandler(_items_CollectionChanged); _UpdateLayout(); } /// <summary> /// If edited item has driver/vehicle, which names are the same as others /// routes names - raises property changed event for such routes. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">DataGridItemCancelEventArgs.</param> private void _DataGridCollectionViewSourceCommittingEdit(object sender, DataGridItemCancelEventArgs e) { Route editedRoute = e.Item as Route; foreach (Route route in DataKeeper.Routes) { // If drivers name are the same - raise driver property changed. if (route.Driver.Name == editedRoute.Driver.Name) (route as IForceNotifyPropertyChanged).RaisePropertyChangedEvent(Route.PropertyNameDriver); // If vehicle name are the same - raise vehicle property changed. if (route.Vehicle.Name == editedRoute.Vehicle.Name) (route as IForceNotifyPropertyChanged).RaisePropertyChangedEvent(Route.PropertyNameVehicle); } } #endregion // Event handlers #region Private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Loads grid layout. /// </summary> private void _InitDataGridLayout() { xceedGrid.OnItemSourceChanged += new EventHandler(xceedGrid_OnItemSourceChanged); DataGridCollectionViewSource collectionSource = (DataGridCollectionViewSource)layoutRoot.FindResource(COLLECTION_SOURCE_KEY); GridStructureInitializer structureInitializer = new GridStructureInitializer(GridSettingsProvider.FleetRoutesGridStructure); structureInitializer.BuildGridStructure(collectionSource, xceedGrid); } /// <summary> /// Gets row definitions from page root. /// </summary> /// <returns>Page's root row definitions.</returns> private RowDefinitionCollection _GetRowDefinitions() { var layoutBorder = (Border)layoutRoot.Children[0]; var rootGrid = (Grid)layoutBorder.Child; return rootGrid.RowDefinitions; } /// <summary> /// Gets row definition for routes table. /// </summary> /// <param name="rowDefinitions">Page's root row definitions.</param> /// <returns>Row definition for routes table.</returns> private RowDefinition _GetRowDefinitionForRoutesTable(RowDefinitionCollection rowDefinitions) { Debug.Assert(null != rowDefinitions); return rowDefinitions[DATA_GRID_ROW_DEFINITION_INDEX]; } /// <summary> /// Gets row definition for routes table. /// </summary> /// <returns>Row definition for routes table.</returns> private RowDefinition _GetRowDefinitionForRoutesTable() { var definitions = _GetRowDefinitions(); return _GetRowDefinitionForRoutesTable(definitions); } /// <summary> /// Updates page layout. /// </summary> private void _UpdateLayout() { // make rotes table space grow as possible var rowDefinitions = _GetRowDefinitions(); var routesTableRowDefinition = _GetRowDefinitionForRoutesTable(rowDefinitions); if (0 == DataKeeper.Routes.Count) routesTableRowDefinition.Height = new GridLength(0); else { // it's not maximum - do work var rowsToShowCount = Math.Max(MINIMUM_ROW_COUNT, xceedGrid.Items.Count); var newHeight = (rowsToShowCount + HEADER_ROWS_COUNT) * DEFAULT_ROW_HEIGHT; if (newHeight < (layoutRoot.ActualHeight - LABELS_SPACE)) { // if all items accommodate in grid with half size of frame, set size on items routesTableRowDefinition.Height = new GridLength(newHeight); } else { // otherwise set grid size to all free space of frame rowDefinitions[rowDefinitions.Count - 1].Height = new GridLength(0); // NOTE: last column have free all space - chenge this settings routesTableRowDefinition.Height = new GridLength(1, System.Windows.GridUnitType.Star); } } } /// <summary> /// Inits page controls. /// </summary> private void _InitControls() { Debug.Assert(!_isInited); // only once // init page controls var defaults = Defaults.Instance; // init Max Order from Defaults if (null == maxOrderTextBox.Value) maxOrderTextBox.Value = (UInt32)defaults.RoutesDefaults.MaxOrder; // init Max Work Time from Defaults if (null == maxWorkTimeTextBox.Value) maxWorkTimeTextBox.Value = (UInt32)UnitConvertor.Convert(defaults.RoutesDefaults.MaxTotalDuration, Unit.Minute, Unit.Hour); // init Start Time Window from Defaults var startTimeWindow = defaults.RoutesDefaults.StartTimeWindow; textBoxStart.Time = startTimeWindow.From; textBoxEnd.Time = startTimeWindow.To; textBoxStart.IsEnabled = textBoxEnd.IsEnabled = !startTimeWindow.IsWideopen; // init table _InitDataGridLayout(); // init vehicle number from project int routesCount = DataKeeper.Routes.Count; if (0 == (UInt32)vehicleNumberTextBox.Value) { vehicleNumberTextBox.Value = (UInt32)((0 == routesCount) ? DEFAULT_ROUTE_COUNT : routesCount); if (0 == routesCount) // defaults records is shown immediately in table _DoGrowList(DEFAULT_ROUTE_COUNT); } _isInited = true; } /// <summary> /// Inits collection of route. /// </summary> private void _InitDataGridCollection() { var routes = DataKeeper.Routes; // init source collection var sortedRoutesCollection = new AppData.SortedDataObjectCollection<Route>(routes, new RoutesComparer()); DataGridCollectionViewSource collectionSource = (DataGridCollectionViewSource)layoutRoot.FindResource(COLLECTION_SOURCE_KEY); collectionSource.Source = sortedRoutesCollection; } /// <summary> /// Updates page controls state. /// </summary> private void _UpdatePageState() { var routesCount = DataKeeper.Routes.Count; var isRoutePresent = (0 < routesCount); var isVehicleNumberSet = (0 < (UInt32)vehicleNumberTextBox.Value); var isFullState = (isVehicleNumberSet && isRoutePresent); // init state of controls var controlVisibility = isFullState ? Visibility.Visible : Visibility.Collapsed; border.Visibility = textBoxEditTooltip.Visibility = gridBorder.Visibility = xceedGrid.Visibility = textBoxEndTooltip.Visibility = controlVisibility; buttonNext.IsEnabled = isFullState && isRoutePresent; } /// <summary> /// Ends edit table. /// </summary> private void _EndEditTable() { try { xceedGrid.EndEdit(); } catch { xceedGrid.CancelEdit(); } } /// <summary> /// Gets Max Order value from GUI. /// </summary> /// <returns>Max Order value.</returns> private int _GetInputedMaxOrder() { return (null == maxOrderTextBox.Value) ? 0 : (int)((UInt32)maxOrderTextBox.Value); } /// <summary> /// Gets Max Work Time value from GUI. /// </summary> /// <returns>Max Work Time value.</returns> private int _GetInputedMaxWorkTime() { double inputedValue = 0; if (null != maxWorkTimeTextBox.Value) inputedValue = (double)((UInt32)maxWorkTimeTextBox.Value); return (int)UnitConvertor.Convert(inputedValue, Unit.Hour, Unit.Minute); } /// <summary> /// Gets Max Travel Duration form Defaults with valid correction. /// </summary> /// <param name="maxWorkTime">Max Work Time to correction Max Travel Duration.</param> /// <returns>Valid value for Max Travel Duration.</returns> private int _GetCorrectedMaxTravelDuration(int maxWorkTime) { return Math.Min(maxWorkTime, Defaults.Instance.RoutesDefaults.MaxTravelDuration); } /// <summary> /// Updates values of all created routes from GUI. /// </summary> private void _UpdateRoutesValues() { // update routes from GUI values int maxOrders = _GetInputedMaxOrder(); int maxWorkTime = _GetInputedMaxWorkTime(); int maxTravelDuration = _GetCorrectedMaxTravelDuration(maxWorkTime); var routes = DataKeeper.Routes; for (int index = 0; index < routes.Count; ++index) { var route = routes[index]; TimeWindow startTimeWindow = route.StartTimeWindow; startTimeWindow.From = textBoxStart.Time; startTimeWindow.To = textBoxEnd.Time; route.MaxOrders = maxOrders; route.MaxTravelDuration = maxTravelDuration; route.MaxTotalDuration = maxWorkTime; } } /// <summary> /// Updates routes list. /// </summary> private void _UpdateRoutes() { // get user choice var newNumber = (int)(UInt32)vehicleNumberTextBox.Value; // get presented objects var presentedNumber = DataKeeper.Routes.Count; if (presentedNumber != newNumber) { // count changed if (newNumber < presentedNumber) // need remove needles _DoShrinkList(newNumber); else if (presentedNumber < newNumber) // need add new vehicle _DoGrowList(newNumber); // else do nothing _UpdatePageState(); } } /// <summary> /// Incrementes vehicle number. /// </summary> private void _IncrementVehicleNumber() { var value = (UInt32)vehicleNumberTextBox.Value; var maxValue = (UInt32)vehicleNumberTextBox.MaxValue; if (value < maxValue) vehicleNumberTextBox.Value = value + 1; } /// <summary> /// Decrementes vehicle number. /// </summary> private void _DecrementVehicleNumber() { if (vehicleNumberTextBox.HasValidationError) return; var value = (UInt32)vehicleNumberTextBox.Value; var minValue = (UInt32)vehicleNumberTextBox.MinValue; if (minValue < value) vehicleNumberTextBox.Value = value - 1; } /// <summary> /// Stores changes in project. /// </summary> private void _StoreChanges() { DataKeeper.Project.Save(); } /// <summary> /// Gets from full collection all object not presented in filtred objects. /// </summary> /// <param name="ignoredObjects">Ignored object collection.</param> /// <param name="allObjects">Full object collection.</param> /// <returns>Object colletion from full collection not presented in filtred objects.</returns> private IList<T> _GetNotUsedObjects<T>(ICollection<T> ignoredObjects, AppData.IDataObjectCollection<T> allObjects) where T : AppData.DataObject { var filtredObject = new List<T>(); for (int index = 0; index < allObjects.Count; ++index) { T obj = allObjects[index]; if (null == _GetObjectByName(obj.ToString(), ignoredObjects)) filtredObject.Add(obj); } return filtredObject; } /// <summary> /// Get object by name. /// </summary> /// <param name="name">Object name.</param> /// <param name="collection">Objects collections.</param> /// <returns>Object or null if not founded.</returns> private T _GetObjectByName<T>(string name, ICollection<T> collection) where T : AppData.DataObject { var objects = from obj in collection where obj.ToString() == name select obj; return objects.FirstOrDefault(); } /// <summary> /// Checks is object present in object collection. /// </summary> /// <param name="obj">Object to check.</param> /// <param name="collection">Object's collection.</param> /// <returns>TRUE if cheked object present in collection.</returns> private bool _IsObjectPresentInCollection<T>(T obj, IList<T> collection) where T : AppData.DataObject { var objName = obj.ToString(); return (null != _GetObjectByName(objName, collection)); } /// <summary> /// Gets object unique name. /// </summary> /// <param name="baseName">Base object name.</param> /// <param name="collection">Objects collections.</param> /// <returns>Dublicate unique name.</returns> private string _GetNewName<T>(string baseName, ICollection<T> collection) where T : AppData.DataObject { var index = 1; var newName = string.Format(NEW_NAME_FORMAT, baseName, index); while (null != _GetObjectByName(newName, collection)) newName = string.Format(NEW_NAME_FORMAT, baseName, ++index); return newName; } /// <summary> /// Gets driver to init route. /// </summary> /// <param name="list">Drivers for first selection.</param> /// <param name="index">Driver index.</param> /// <returns>Driver object.</returns> private Driver _GetNextDriver(IList<Driver> list, int index) { Driver obj = null; if (index < list.Count) obj = list[index]; // get presented else { // create new object AppData.IDataObjectCollection<Driver> drivers = DataKeeper.Project.Drivers; obj = new Driver(); obj.Name = _GetNewName(App.Current.FindString("Driver"), drivers); drivers.Add(obj); } return obj; } /// <summary> /// Gets vehicle to init route. /// </summary> /// <param name="list">Vehicles for first selection.</param> /// <param name="index">Vehicle index.</param> /// <returns>Vehicle object.</returns> private Vehicle _GetNextVehicle(IList<Vehicle> list, int index) { Vehicle obj = null; if (index < list.Count) obj = list[index]; // get presented else { // create new object AppData.IDataObjectCollection<Vehicle> vehicles = DataKeeper.Project.Vehicles; obj = new Vehicle(DataKeeper.Project.CapacitiesInfo); obj.Name = _GetNewName(App.Current.FindString("Vehicle"), vehicles); // init fuel type - use first presented AppData.IDataObjectCollection<FuelType> fuelTypes = DataKeeper.Project.FuelTypes; if (0 < fuelTypes.Count) obj.FuelType = fuelTypes[0]; vehicles.Add(obj); } return obj; } /// <summary> /// Does grow list of routes. /// </summary> /// <param name="vehicleNumber">New vehicle number.</param> private void _DoGrowList(int vehicleNumber) { _EndEditTable(); // select objects in use List<Driver> driversInUse = new List<Driver>(); List<Vehicle> vehiclesInUse = new List<Vehicle>(); AppData.IDataObjectCollection<Route> routes = DataKeeper.Routes; for (int index = 0; index < routes.Count; ++index) { Route route = routes[index]; if (!_IsObjectPresentInCollection(route.Driver, driversInUse)) driversInUse.Add(route.Driver); if (!_IsObjectPresentInCollection(route.Vehicle, vehiclesInUse)) vehiclesInUse.Add(route.Vehicle); } Project project = DataKeeper.Project; // filter project objects - select not used objects IList<Driver> drivers = _GetNotUsedObjects(driversInUse, project.Drivers); IList<Vehicle> vehicles = _GetNotUsedObjects(vehiclesInUse, project.Vehicles); // use older as default location var sortCollection = from loc in project.Locations orderby loc.CreationTime select loc; Location defaultLocation = sortCollection.First(); // create, init and add new routes int maxOrders = _GetInputedMaxOrder(); int maxWorkTime = _GetInputedMaxWorkTime(); int maxTravelDuration = _GetCorrectedMaxTravelDuration(maxWorkTime); int presentedVehicleNumber = DataKeeper.Routes.Count; int needAddCount = vehicleNumber - presentedVehicleNumber; for (int index = 0; index < needAddCount; ++index) { // create route Route route = project.CreateRoute(); // init route route.Name = _GetNewName(App.Current.FindString("Route"), routes); route.Color = RouteColorManager.Instance.NextRouteColor(routes); route.StartLocation = defaultLocation; route.EndLocation = defaultLocation; route.Driver = _GetNextDriver(drivers, index); route.Vehicle = _GetNextVehicle(vehicles, index); TimeWindow startTimeWindow = route.StartTimeWindow; startTimeWindow.From = textBoxStart.Time; startTimeWindow.To = textBoxEnd.Time; route.MaxOrders = maxOrders; route.MaxTravelDuration = maxTravelDuration; route.MaxTotalDuration = maxWorkTime; routes.Add(route); } _StoreChanges(); } /// <summary> /// Deletes objects from project collection. /// </summary> /// <param name="deleteingObjects">List of deleting objects.</param> /// <param name="objectCollection">Project object collection.</param> private void _DeleteObjects<T>(IList<T> deleteingObjects, AppData.IDataObjectCollection<T> objectCollection) where T : AppData.DataObject { for (int index = 0; index < deleteingObjects.Count; ++index) objectCollection.Remove(deleteingObjects[index]); } /// <summary> /// Deletes routes from project collection. /// </summary> /// <param name="deletingRoutes">List of deleting routes.</param> private void _DeleteRoutes(IList<Route> deletingRoutes) { AppData.IDataObjectCollection<Route> routes = DataKeeper.Routes; // store route relative objects List<Driver> deletingDrivers = new List<Driver>(); List<Vehicle> deletingVehicles = new List<Vehicle>(); // remove routes for (int index = 0; index < deletingRoutes.Count; ++index) { Route route = deletingRoutes[index]; Driver driver = route.Driver; if (!_IsObjectPresentInCollection(driver, deletingDrivers)) deletingDrivers.Add(driver); Vehicle vehicle = route.Vehicle; if (!_IsObjectPresentInCollection(vehicle, deletingVehicles)) deletingVehicles.Add(vehicle); routes.Remove(route); } // remove drivers _DeleteObjects(deletingDrivers, DataKeeper.Project.Drivers); // remove vehicles _DeleteObjects(deletingVehicles, DataKeeper.Project.Vehicles); } /// <summary> /// Does shrinks list of routes. /// </summary> /// <param name="vehicleNumber">New vehicle number.</param> private void _DoShrinkList(int vehicleNumber) { _EndEditTable(); var routes = DataKeeper.Routes; // do temporary copy var routesTmp = new List<Route>(routes); // sort by creation time var sortCollection = from rt in routesTmp orderby rt.CreationTime select rt; // prepare deleting route list var sortedRoutes = sortCollection.ToList(); var deletingRoutes = new List<Route>(sortedRoutes.Count - vehicleNumber); for (int index = vehicleNumber; index < sortedRoutes.Count; ++index) deletingRoutes.Add(sortedRoutes[index]); // do delete _DeleteRoutes(deletingRoutes); _StoreChanges(); } #endregion // Private methods #region Private consts /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private const string COLLECTION_SOURCE_KEY = "routesCollection"; private const string NAME_PROPERTY_STRING = "Name"; private const string NEW_NAME_FORMAT = "{0} {1}"; private const int DEFAULT_ROUTE_COUNT = 1; private const double LABELS_SPACE = 255; private const int HEADER_ROWS_COUNT = 2; private const int MINIMUM_ROW_COUNT = 3; private const int DATA_GRID_ROW_DEFINITION_INDEX = 5; private readonly double DEFAULT_ROW_HEIGHT = (double)App.Current.FindResource("XceedRowDefaultHeight"); #endregion // Private consts #region Private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Is inited flag. /// </summary> private bool _isInited; /// <summary> /// Items for routes table. /// </summary> private INotifyCollectionChanged _items; #endregion // Private fields } }
using System; using System.Collections.Generic; using System.Linq; using CSharpTest.Net.Interfaces; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Moq; using NPoco; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.IO; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Scoping { [TestFixture] public class ScopeUnitTests { /// <summary> /// Creates a ScopeProvider with mocked internals. /// </summary> /// <param name="syntaxProviderMock">The mock of the ISqlSyntaxProvider2, used to count method calls.</param> /// <returns></returns> private ScopeProvider GetScopeProvider(out Mock<ISqlSyntaxProvider> syntaxProviderMock) { var loggerFactory = NullLoggerFactory.Instance; var fileSystems = new FileSystems(loggerFactory, Mock.Of<IIOHelper>(), Mock.Of<IOptions<GlobalSettings>>(), Mock.Of<IHostingEnvironment>()); var mediaFileManager = new MediaFileManager( Mock.Of<IFileSystem>(), Mock.Of<IMediaPathScheme>(), loggerFactory.CreateLogger<MediaFileManager>(), Mock.Of<IShortStringHelper>(), Mock.Of<IServiceProvider>(), Options.Create(new ContentSettings())); var databaseFactory = new Mock<IUmbracoDatabaseFactory>(); var database = new Mock<IUmbracoDatabase>(); var sqlContext = new Mock<ISqlContext>(); syntaxProviderMock = new Mock<ISqlSyntaxProvider>(); // Setup mock of database factory to return mock of database. databaseFactory.Setup(x => x.CreateDatabase()).Returns(database.Object); databaseFactory.Setup(x => x.SqlContext).Returns(sqlContext.Object); // Setup mock of database to return mock of sql SqlContext database.Setup(x => x.SqlContext).Returns(sqlContext.Object); // Setup mock of ISqlContext to return syntaxProviderMock sqlContext.Setup(x => x.SqlSyntax).Returns(syntaxProviderMock.Object); return new ScopeProvider( databaseFactory.Object, fileSystems, Options.Create(new CoreDebugSettings()), mediaFileManager, loggerFactory.CreateLogger<ScopeProvider>(), loggerFactory, Mock.Of<IRequestCache>(), Mock.Of<IEventAggregator>()); } [Test] public void Unused_Lazy_Locks_Cleared_At_Child_Scope() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); var outerScope = scopeProvider.CreateScope(); outerScope.ReadLock(Constants.Locks.Domains); outerScope.ReadLock(Constants.Locks.Languages); using (var innerScope1 = (Scope)scopeProvider.CreateScope()) { innerScope1.ReadLock(Constants.Locks.Domains); innerScope1.ReadLock(Constants.Locks.Languages); innerScope1.Complete(); } using (var innerScope2 = (Scope)scopeProvider.CreateScope()) { innerScope2.ReadLock(Constants.Locks.Domains); innerScope2.ReadLock(Constants.Locks.Languages); // force resolving the locks var locks = innerScope2.GetReadLocks(); innerScope2.Complete(); } outerScope.Complete(); Assert.DoesNotThrow(() => outerScope.Dispose()); } [Test] public void WriteLock_Acquired_Only_Once_Per_Key() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); using (var outerScope = (Scope)scopeProvider.CreateScope()) { outerScope.EagerWriteLock(Constants.Locks.Domains); outerScope.EagerWriteLock(Constants.Locks.Languages); using (var innerScope1 = (Scope)scopeProvider.CreateScope()) { innerScope1.EagerWriteLock(Constants.Locks.Domains); innerScope1.EagerWriteLock(Constants.Locks.Languages); using (var innerScope2 = (Scope)scopeProvider.CreateScope()) { innerScope2.EagerWriteLock(Constants.Locks.Domains); innerScope2.EagerWriteLock(Constants.Locks.Languages); innerScope2.Complete(); } innerScope1.Complete(); } outerScope.Complete(); } syntaxProviderMock.Verify(x => x.WriteLock(It.IsAny<IDatabase>(), Constants.Locks.Domains), Times.Once); syntaxProviderMock.Verify(x => x.WriteLock(It.IsAny<IDatabase>(), Constants.Locks.Languages), Times.Once); } [Test] public void WriteLock_Acquired_Only_Once_When_InnerScope_Disposed() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); using (var outerScope = (Scope)scopeProvider.CreateScope()) { outerScope.EagerWriteLock(Constants.Locks.Languages); using (var innerScope = (Scope)scopeProvider.CreateScope()) { innerScope.EagerWriteLock(Constants.Locks.Languages); innerScope.EagerWriteLock(Constants.Locks.ContentTree); innerScope.Complete(); } outerScope.EagerWriteLock(Constants.Locks.ContentTree); outerScope.Complete(); } syntaxProviderMock.Verify(x => x.WriteLock(It.IsAny<IDatabase>(), Constants.Locks.Languages), Times.Once); syntaxProviderMock.Verify(x => x.WriteLock(It.IsAny<IDatabase>(), Constants.Locks.ContentTree), Times.Once); } [Test] public void WriteLock_With_Timeout_Acquired_Only_Once_Per_Key() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); var timeout = TimeSpan.FromMilliseconds(10000); using (var outerScope = (Scope)scopeProvider.CreateScope()) { outerScope.EagerWriteLock(timeout, Constants.Locks.Domains); outerScope.EagerWriteLock(timeout, Constants.Locks.Languages); using (var innerScope1 = (Scope)scopeProvider.CreateScope()) { innerScope1.EagerWriteLock(timeout, Constants.Locks.Domains); innerScope1.EagerWriteLock(timeout, Constants.Locks.Languages); using (var innerScope2 = (Scope)scopeProvider.CreateScope()) { innerScope2.EagerWriteLock(timeout, Constants.Locks.Domains); innerScope2.EagerWriteLock(timeout, Constants.Locks.Languages); innerScope2.Complete(); } innerScope1.Complete(); } outerScope.Complete(); } syntaxProviderMock.Verify(x => x.WriteLock(It.IsAny<IDatabase>(), timeout, Constants.Locks.Domains), Times.Once); syntaxProviderMock.Verify(x => x.WriteLock(It.IsAny<IDatabase>(), timeout, Constants.Locks.Languages), Times.Once); } [Test] public void ReadLock_Acquired_Only_Once_Per_Key() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); using (var outerScope = (Scope)scopeProvider.CreateScope()) { outerScope.EagerReadLock(Constants.Locks.Domains); outerScope.EagerReadLock(Constants.Locks.Languages); using (var innerScope1 = (Scope)scopeProvider.CreateScope()) { innerScope1.EagerReadLock(Constants.Locks.Domains); innerScope1.EagerReadLock(Constants.Locks.Languages); using (var innerScope2 = (Scope)scopeProvider.CreateScope()) { innerScope2.EagerReadLock(Constants.Locks.Domains); innerScope2.EagerReadLock(Constants.Locks.Languages); innerScope2.Complete(); } innerScope1.Complete(); } outerScope.Complete(); } syntaxProviderMock.Verify(x => x.ReadLock(It.IsAny<IDatabase>(), Constants.Locks.Domains), Times.Once); syntaxProviderMock.Verify(x => x.ReadLock(It.IsAny<IDatabase>(), Constants.Locks.Languages), Times.Once); } [Test] public void ReadLock_With_Timeout_Acquired_Only_Once_Per_Key() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); var timeOut = TimeSpan.FromMilliseconds(10000); using (var outerScope = (Scope)scopeProvider.CreateScope()) { outerScope.EagerReadLock(timeOut, Constants.Locks.Domains); outerScope.EagerReadLock(timeOut, Constants.Locks.Languages); using (var innerScope1 = (Scope)scopeProvider.CreateScope()) { innerScope1.EagerReadLock(timeOut, Constants.Locks.Domains); innerScope1.EagerReadLock(timeOut, Constants.Locks.Languages); using (var innerScope2 = (Scope)scopeProvider.CreateScope()) { innerScope2.EagerReadLock(timeOut, Constants.Locks.Domains); innerScope2.EagerReadLock(timeOut, Constants.Locks.Languages); innerScope2.Complete(); } innerScope1.Complete(); } outerScope.Complete(); } syntaxProviderMock.Verify(x => x.ReadLock(It.IsAny<IDatabase>(), timeOut, Constants.Locks.Domains), Times.Once); syntaxProviderMock.Verify(x => x.ReadLock(It.IsAny<IDatabase>(), timeOut, Constants.Locks.Languages), Times.Once); } [Test] public void ReadLock_Acquired_Only_Once_When_InnerScope_Disposed() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); using (var outerScope = scopeProvider.CreateScope()) { outerScope.ReadLock(Constants.Locks.Languages); using (var innerScope = (Scope)scopeProvider.CreateScope()) { innerScope.EagerReadLock(Constants.Locks.Languages); innerScope.EagerReadLock(Constants.Locks.ContentTree); innerScope.Complete(); } outerScope.ReadLock(Constants.Locks.ContentTree); outerScope.Complete(); } syntaxProviderMock.Verify(x => x.ReadLock(It.IsAny<IDatabase>(), Constants.Locks.Languages), Times.Once); syntaxProviderMock.Verify(x => x.ReadLock(It.IsAny<IDatabase>(), Constants.Locks.ContentTree), Times.Once); } [Test] public void WriteLocks_Count_correctly_If_Lock_Requested_Twice_In_Scope() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); Guid innerscopeId; using (var outerscope = (Scope)scopeProvider.CreateScope()) { outerscope.EagerWriteLock(Constants.Locks.ContentTree); outerscope.EagerWriteLock(Constants.Locks.ContentTree); Assert.AreEqual(2, outerscope.GetWriteLocks()[outerscope.InstanceId][Constants.Locks.ContentTree]); using (var innerScope = (Scope)scopeProvider.CreateScope()) { innerscopeId = innerScope.InstanceId; innerScope.EagerWriteLock(Constants.Locks.ContentTree); innerScope.EagerWriteLock(Constants.Locks.ContentTree); Assert.AreEqual(2, outerscope.GetWriteLocks()[outerscope.InstanceId][Constants.Locks.ContentTree]); Assert.AreEqual(2, outerscope.GetWriteLocks()[innerscopeId][Constants.Locks.ContentTree]); innerScope.EagerWriteLock(Constants.Locks.Languages); innerScope.EagerWriteLock(Constants.Locks.Languages); Assert.AreEqual(2, outerscope.GetWriteLocks()[innerScope.InstanceId][Constants.Locks.Languages]); innerScope.Complete(); } Assert.AreEqual(2, outerscope.GetWriteLocks()[outerscope.InstanceId][Constants.Locks.ContentTree]); Assert.IsFalse(outerscope.GetWriteLocks().ContainsKey(innerscopeId)); outerscope.Complete(); } } [Test] public void ReadLocks_Count_correctly_If_Lock_Requested_Twice_In_Scope() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); Guid innerscopeId; using (var outerscope = (Scope)scopeProvider.CreateScope()) { outerscope.EagerReadLock(Constants.Locks.ContentTree); outerscope.EagerReadLock(Constants.Locks.ContentTree); Assert.AreEqual(2, outerscope.GetReadLocks()[outerscope.InstanceId][Constants.Locks.ContentTree]); using (var innerScope = (Scope)scopeProvider.CreateScope()) { innerscopeId = innerScope.InstanceId; innerScope.EagerReadLock(Constants.Locks.ContentTree); innerScope.EagerReadLock(Constants.Locks.ContentTree); Assert.AreEqual(2, outerscope.GetReadLocks()[outerscope.InstanceId][Constants.Locks.ContentTree]); Assert.AreEqual(2, outerscope.GetReadLocks()[innerScope.InstanceId][Constants.Locks.ContentTree]); innerScope.EagerReadLock(Constants.Locks.Languages); innerScope.EagerReadLock(Constants.Locks.Languages); Assert.AreEqual(2, outerscope.GetReadLocks()[innerScope.InstanceId][Constants.Locks.Languages]); innerScope.Complete(); } Assert.AreEqual(2, outerscope.GetReadLocks()[outerscope.InstanceId][Constants.Locks.ContentTree]); Assert.IsFalse(outerscope.GetReadLocks().ContainsKey(innerscopeId)); outerscope.Complete(); } } [Test] public void Nested_Scopes_WriteLocks_Count_Correctly() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); Guid innerScope1Id, innerScope2Id; using (var parentScope = scopeProvider.CreateScope()) { var realParentScope = (Scope)parentScope; parentScope.WriteLock(Constants.Locks.ContentTree); parentScope.WriteLock(Constants.Locks.ContentTypes); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"parentScope after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"parentScope after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); using (var innerScope1 = scopeProvider.CreateScope()) { innerScope1Id = innerScope1.InstanceId; innerScope1.WriteLock(Constants.Locks.ContentTree); innerScope1.WriteLock(Constants.Locks.ContentTypes); innerScope1.WriteLock(Constants.Locks.Languages); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"innerScope1, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.ContentTree], $"innerScope1, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.Languages], $"innerScope1, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.Languages)}"); using (var innerScope2 = scopeProvider.CreateScope()) { innerScope2Id = innerScope2.InstanceId; innerScope2.WriteLock(Constants.Locks.ContentTree); innerScope2.WriteLock(Constants.Locks.MediaTypes); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"innerScope2, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"innerScope2, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.ContentTree], $"innerScope2, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.ContentTypes], $"innerScope2, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.Languages], $"innerScope2, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.Languages)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope2.InstanceId][Constants.Locks.ContentTree], $"innerScope2, innerScope2 instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope2.InstanceId][Constants.Locks.MediaTypes], $"innerScope2, innerScope2 instance, after locks acquired: {nameof(Constants.Locks.MediaTypes)}"); innerScope2.Complete(); } Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"innerScope1, parent instance, after innserScope2 disposed: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, parent instance, after innserScope2 disposed: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.ContentTree], $"innerScope1, innerScope1 instance, after innserScope2 disposed: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, innerScope1 instance, after innserScope2 disposed: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[innerScope1.InstanceId][Constants.Locks.Languages], $"innerScope1, innerScope1 instance, after innserScope2 disposed: {nameof(Constants.Locks.Languages)}"); Assert.IsFalse(realParentScope.GetWriteLocks().ContainsKey(innerScope2Id)); innerScope1.Complete(); } Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"parentScope after inner scopes disposed: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetWriteLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"parentScope after inner scopes disposed: {nameof(Constants.Locks.ContentTypes)}"); Assert.IsFalse(realParentScope.GetWriteLocks().ContainsKey(innerScope2Id)); Assert.IsFalse(realParentScope.GetWriteLocks().ContainsKey(innerScope1Id)); parentScope.Complete(); } } [Test] public void Nested_Scopes_ReadLocks_Count_Correctly() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); Guid innerScope1Id, innerScope2Id; using (var parentScope = scopeProvider.CreateScope()) { var realParentScope = (Scope)parentScope; parentScope.ReadLock(Constants.Locks.ContentTree); parentScope.ReadLock(Constants.Locks.ContentTypes); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"parentScope after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"parentScope after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); using (var innserScope1 = scopeProvider.CreateScope()) { innerScope1Id = innserScope1.InstanceId; innserScope1.ReadLock(Constants.Locks.ContentTree); innserScope1.ReadLock(Constants.Locks.ContentTypes); innserScope1.ReadLock(Constants.Locks.Languages); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"innerScope1, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.ContentTree], $"innerScope1, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.Languages], $"innerScope1, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.Languages)}"); using (var innerScope2 = scopeProvider.CreateScope()) { innerScope2Id = innerScope2.InstanceId; innerScope2.ReadLock(Constants.Locks.ContentTree); innerScope2.ReadLock(Constants.Locks.MediaTypes); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"innerScope2, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"innerScope2, parent instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.ContentTree], $"innerScope2, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.ContentTypes], $"innerScope2, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.Languages], $"innerScope2, innerScope1 instance, after locks acquired: {nameof(Constants.Locks.Languages)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innerScope2.InstanceId][Constants.Locks.ContentTree], $"innerScope2, innerScope2 instance, after locks acquired: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innerScope2.InstanceId][Constants.Locks.MediaTypes], $"innerScope2, innerScope2 instance, after locks acquired: {nameof(Constants.Locks.MediaTypes)}"); innerScope2.Complete(); } Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"innerScope1, parent instance, after innerScope2 disposed: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, parent instance, after innerScope2 disposed: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.ContentTree], $"innerScope1, innerScope1 instance, after innerScope2 disposed: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.ContentTypes], $"innerScope1, innerScope1 instance, after innerScope2 disposed: {nameof(Constants.Locks.ContentTypes)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[innserScope1.InstanceId][Constants.Locks.Languages], $"innerScope1, innerScope1 instance, after innerScope2 disposed: {nameof(Constants.Locks.Languages)}"); Assert.IsFalse(realParentScope.GetReadLocks().ContainsKey(innerScope2Id)); innserScope1.Complete(); } Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTree], $"parentScope after innerScope1 disposed: {nameof(Constants.Locks.ContentTree)}"); Assert.AreEqual(1, realParentScope.GetReadLocks()[realParentScope.InstanceId][Constants.Locks.ContentTypes], $"parentScope after innerScope1 disposed: {nameof(Constants.Locks.ContentTypes)}"); Assert.IsFalse(realParentScope.GetReadLocks().ContainsKey(innerScope2Id)); Assert.IsFalse(realParentScope.GetReadLocks().ContainsKey(innerScope1Id)); parentScope.Complete(); } } [Test] public void WriteLock_Doesnt_Increment_On_Error() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); syntaxProviderMock.Setup(x => x.WriteLock(It.IsAny<IDatabase>(), It.IsAny<int[]>())).Throws(new Exception("Boom")); using (var scope = (Scope)scopeProvider.CreateScope()) { Assert.Throws<Exception>(() => scope.EagerWriteLock(Constants.Locks.Languages)); Assert.IsFalse(scope.GetWriteLocks()[scope.InstanceId].ContainsKey(Constants.Locks.Languages)); scope.Complete(); } } [Test] public void ReadLock_Doesnt_Increment_On_Error() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); syntaxProviderMock.Setup(x => x.ReadLock(It.IsAny<IDatabase>(), It.IsAny<int[]>())).Throws(new Exception("Boom")); using (var scope = (Scope)scopeProvider.CreateScope()) { Assert.Throws<Exception>(() => scope.EagerReadLock(Constants.Locks.Languages)); Assert.IsFalse(scope.GetReadLocks()[scope.InstanceId].ContainsKey(Constants.Locks.Languages)); scope.Complete(); } } [Test] public void Scope_Throws_If_ReadLocks_Not_Cleared() { var scopeprovider = GetScopeProvider(out var syntaxProviderMock); var scope = (Scope)scopeprovider.CreateScope(); try { // Request a lock to create the ReadLocks dict. scope.ReadLock(Constants.Locks.Domains); var readDict = new Dictionary<int, int>(); readDict[Constants.Locks.Languages] = 1; scope.GetReadLocks()[Guid.NewGuid()] = readDict; Assert.Throws<InvalidOperationException>(() => scope.Dispose()); } finally { // We have to clear so we can properly dispose the scope, otherwise it'll mess with other tests. scope.GetReadLocks()?.Clear(); scope.Dispose(); } } [Test] public void Scope_Throws_If_WriteLocks_Not_Cleared() { var scopeprovider = GetScopeProvider(out var syntaxProviderMock); var scope = (Scope)scopeprovider.CreateScope(); try { // Request a lock to create the WriteLocks dict. scope.WriteLock(Constants.Locks.Domains); var writeDict = new Dictionary<int, int>(); writeDict[Constants.Locks.Languages] = 1; scope.GetWriteLocks()[Guid.NewGuid()] = writeDict; Assert.Throws<InvalidOperationException>(() => scope.Dispose()); } finally { // We have to clear so we can properly dispose the scope, otherwise it'll mess with other tests. scope.GetWriteLocks()?.Clear(); scope.Dispose(); } } [Test] public void WriteLocks_Not_Created_Until_First_Lock() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); using (var scope = scopeProvider.CreateScope()) { var realScope = (Scope)scope; Assert.IsNull(realScope.GetWriteLocks()); } } [Test] public void ReadLocks_Not_Created_Until_First_Lock() { var scopeProvider = GetScopeProvider(out var syntaxProviderMock); using (var scope = scopeProvider.CreateScope()) { var realScope = (Scope)scope; Assert.IsNull(realScope.GetReadLocks()); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using UnityEngine; namespace UnityTest { [Serializable] public class PropertyResolver { public string[] ExcludedFieldNames { get; set; } public Type[] ExcludedTypes { get; set; } public Type[] AllowedTypes { get; set; } public PropertyResolver () { ExcludedFieldNames = new string[] {}; ExcludedTypes = new Type[] {}; AllowedTypes = new Type[] {}; } public IList<string> GetFieldsAndPropertiesUnderPath(GameObject go, string propertPath) { propertPath = propertPath.Trim (); if (!PropertyPathIsValid (propertPath)) { throw new ArgumentException("Incorrent property path: " + propertPath); } var idx = propertPath.LastIndexOf('.'); if (idx < 0) { var components = GetFieldsAndPropertiesFromGameObject(go, 2, null); return components; } var propertyToSearch = propertPath; Type type = null; try { type = GetPropertyTypeFromString(go, propertyToSearch); idx = propertPath.Length-1; } catch(ArgumentException) { try { propertyToSearch = propertPath.Substring(0, idx); type = GetPropertyTypeFromString(go, propertyToSearch); } catch (NullReferenceException) { var components = GetFieldsAndPropertiesFromGameObject(go, 2, null); return components.Where(s => s.StartsWith(propertPath.Substring(idx + 1))).ToArray(); } } var resultList = new List<string>(); var path = ""; if(propertyToSearch.EndsWith(".")) propertyToSearch = propertyToSearch.Substring(0, propertyToSearch.Length-1); foreach(var c in propertyToSearch) { if(c == '.') resultList.Add(path); path += c; } resultList.Add(path); foreach (var prop in type.GetProperties()) { if (prop.Name.StartsWith(propertPath.Substring(idx + 1))) resultList.Add(propertyToSearch + "." + prop.Name); } foreach (var prop in type.GetFields()) { if (prop.Name.StartsWith(propertPath.Substring(idx + 1))) resultList.Add(propertyToSearch + "." + prop.Name); } return resultList.ToArray(); } private bool PropertyPathIsValid ( string propertPath ) { if (propertPath.StartsWith (".")) return false; if (propertPath.IndexOf ("..") >= 0) return false; if (Regex.IsMatch (propertPath, @"\s")) return false; return true; } public IList<string> GetFieldsAndPropertiesFromGameObject ( GameObject gameObject, int depthOfSearch, string extendPath ) { if(depthOfSearch<1) throw new ArgumentOutOfRangeException("depthOfSearch need to be greater than 0"); var goVals = GetPropertiesAndFieldsFromType(typeof(GameObject), depthOfSearch - 1).Select(s => "gameObject." + s); var result = new List<string>(); if (AllowedTypes == null || !AllowedTypes.Any() || AllowedTypes.Contains(typeof(GameObject))) result.Add("gameObject"); result.AddRange (goVals); foreach (var componentType in GetAllComponents(gameObject)) { if (AllowedTypes == null || !AllowedTypes.Any() || AllowedTypes.Contains(componentType)) result.Add(componentType.Name); if (depthOfSearch > 1) { var vals = GetPropertiesAndFieldsFromType (componentType, depthOfSearch - 1 ); var valsFullName = vals.Select (s => componentType.Name + "." + s); result.AddRange (valsFullName); } } if (!string.IsNullOrEmpty (extendPath)) { var pathType = GetPropertyTypeFromString (gameObject, extendPath); var vals = GetPropertiesAndFieldsFromType (pathType, depthOfSearch - 1); var valsFullName = vals.Select (s => extendPath + "." + s); result.AddRange (valsFullName); } return result; } private string[] GetPropertiesAndFieldsFromType ( Type type, int level ) { level--; var result = new List<string>(); var fields = new List<MemberInfo>(); fields.AddRange(type.GetFields()); fields.AddRange(type.GetProperties()); foreach (var member in fields) { var memberType = GetMemberFieldType(member); var memberTypeName = memberType.Name; if (AllowedTypes == null ||!AllowedTypes.Any() || (AllowedTypes.Contains(memberType) && !ExcludedFieldNames.Contains(memberTypeName)) ) { result.Add(member.Name); } if (level > 0 && IsTypeOrNameNotExcluded(memberType, memberTypeName)) { var vals = GetPropertiesAndFieldsFromType(memberType, level); var valsFullName = vals.Select(s => member.Name + "." + s); result.AddRange(valsFullName); } } return result.ToArray(); } private Type GetMemberFieldType ( MemberInfo info ) { if (info.MemberType == MemberTypes.Property) return (info as PropertyInfo).PropertyType; if (info.MemberType == MemberTypes.Field) return (info as FieldInfo).FieldType; throw new Exception("Only properties and fields are allowed"); } private Type[] GetAllComponents ( GameObject gameObject ) { var result = new List<Type>(); var components = gameObject.GetComponents(typeof(Component)); foreach (var component in components) { var componentType = component.GetType(); if (IsTypeOrNameNotExcluded(componentType, null)) { result.Add(componentType); } } return result.ToArray(); } private bool IsTypeOrNameNotExcluded(Type memberType, string memberTypeName) { return !ExcludedTypes.Contains(memberType) && !ExcludedFieldNames.Contains(memberTypeName); } #region Static helpers public static object GetPropertyValueFromString(GameObject gameObj, string propertyPath) { if (propertyPath == "") return gameObj; var propsQueue = new Queue<string>(propertyPath.Split('.').Where(s => !string.IsNullOrEmpty(s))); if (propsQueue == null) throw new ArgumentException("Incorrent property path"); object result; if (char.IsLower(propsQueue.Peek()[0])) { result = gameObj; } else { result = gameObj.GetComponent(propsQueue.Dequeue()); } Type type = result.GetType(); while (propsQueue.Count != 0) { var nameToFind = propsQueue.Dequeue(); var property = type.GetProperty(nameToFind); if (property != null) { result = property.GetGetMethod().Invoke(result, null); } else { var field = type.GetField(nameToFind); result = field.GetValue(result); } type = result.GetType(); } return result; } private static Type GetPropertyTypeFromString(GameObject gameObj, string propertyPath) { if (propertyPath == "") return gameObj.GetType(); var propsQueue = new Queue<string>(propertyPath.Split('.').Where(s => !string.IsNullOrEmpty(s))); if (propsQueue == null) throw new ArgumentException("Incorrent property path"); Type result; if (char.IsLower(propsQueue.Peek()[0])) { result = gameObj.GetType(); } else { var component = gameObj.GetComponent(propsQueue.Dequeue()); if (component == null) throw new ArgumentException("Incorrent property path"); result = component.GetType(); } while (propsQueue.Count != 0) { var nameToFind = propsQueue.Dequeue(); var property = result.GetProperty(nameToFind); if (property != null) { result = property.PropertyType; } else { var field = result.GetField(nameToFind); if (field == null) throw new ArgumentException("Incorrent property path"); result = field.FieldType; } } return result; } #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.DirectoryServices.Interop { #pragma warning disable BCL0015 // CoreFxPort using System.Runtime.InteropServices; using System; using System.Security; using System.Security.Permissions; using System.Collections; using System.IO; using System.Text; [StructLayout(LayoutKind.Explicit)] internal struct Variant { [FieldOffset(0)] public ushort varType; [FieldOffset(2)] public ushort reserved1; [FieldOffset(4)] public ushort reserved2; [FieldOffset(6)] public ushort reserved3; [FieldOffset(8)] public short boolvalue; [FieldOffset(8)] public IntPtr ptr1; [FieldOffset(12)] public IntPtr ptr2; } [ SuppressUnmanagedCodeSecurityAttribute() ] internal class 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.DSAdsiNotInstalled); } } public interface IAds { string Name { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; } string Class { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; } string GUID { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; } string ADsPath { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; } string Parent { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; } string Schema { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; } [SuppressUnmanagedCodeSecurityAttribute()] void GetInfo(); [SuppressUnmanagedCodeSecurityAttribute()] void SetInfo(); Object Get( [In, MarshalAs(UnmanagedType.BStr)] string bstrName); [SuppressUnmanagedCodeSecurityAttribute()] void Put( [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] Object vProp); [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int GetEx( [In, MarshalAs(UnmanagedType.BStr)] String bstrName, [Out] out object value); [SuppressUnmanagedCodeSecurityAttribute()] void PutEx( [In, MarshalAs(UnmanagedType.U4)] int lnControlCode, [In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] Object vProp); [SuppressUnmanagedCodeSecurityAttribute()] void GetInfoEx( [In] Object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved); } public interface IAdsContainer { int Count { [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurityAttribute()] get; } object _NewEnum { [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurityAttribute()] get; } object Filter { get; set; } object Hints { get; set; } [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurityAttribute()] object GetObject( [In, MarshalAs(UnmanagedType.BStr)] string className, [In, MarshalAs(UnmanagedType.BStr)] string relativeName); [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurityAttribute()] object Create( [In, MarshalAs(UnmanagedType.BStr)] string className, [In, MarshalAs(UnmanagedType.BStr)] string relativeName); [SuppressUnmanagedCodeSecurityAttribute()] void Delete( [In, MarshalAs(UnmanagedType.BStr)] string className, [In, MarshalAs(UnmanagedType.BStr)] string relativeName); [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurityAttribute()] object CopyHere( [In, MarshalAs(UnmanagedType.BStr)] string sourceName, [In, MarshalAs(UnmanagedType.BStr)] string newName); [return: MarshalAs(UnmanagedType.Interface)] [SuppressUnmanagedCodeSecurityAttribute()] object MoveHere( [In, MarshalAs(UnmanagedType.BStr)] string sourceName, [In, MarshalAs(UnmanagedType.BStr)] string newName); } public interface IAdsDeleteOps { [SuppressUnmanagedCodeSecurityAttribute()] void DeleteObject(int flags); } // // PropertyValue as a co-class that implements the IAdsPropertyValue interface // [ComImport, Guid("7b9e38b0-a97c-11d0-8534-00c04fd8d503")] public class PropertyValue { } public interface IADsLargeInteger { int HighPart { get; set; } int LowPart { get; set; } } public interface IAdsPropertyValue { [SuppressUnmanagedCodeSecurityAttribute()] void Clear(); int ADsType { [SuppressUnmanagedCodeSecurityAttribute()] get; [SuppressUnmanagedCodeSecurityAttribute()] set; } string DNString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string CaseExactString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string CaseIgnoreString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string PrintableString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; [param: MarshalAs(UnmanagedType.BStr)] set; } string NumericString { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; [param: MarshalAs(UnmanagedType.BStr)] set; } bool Boolean { get; set; } int Integer { get; set; } object OctetString { [SuppressUnmanagedCodeSecurityAttribute()] get; [SuppressUnmanagedCodeSecurityAttribute()] set; } object SecurityDescriptor { [SuppressUnmanagedCodeSecurityAttribute()] get; set; } object LargeInteger { [SuppressUnmanagedCodeSecurityAttribute()] get; set; } object UTCTime { [SuppressUnmanagedCodeSecurityAttribute()] get; set; } } // // PropertyEntry as a co-class that implements the IAdsPropertyEntry interface // public class PropertyEntry { } public interface IAdsPropertyEntry { [SuppressUnmanagedCodeSecurityAttribute()] void Clear(); string Name { [return: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] get; [param: MarshalAs(UnmanagedType.BStr)] [SuppressUnmanagedCodeSecurityAttribute()] set; } int ADsType { [SuppressUnmanagedCodeSecurityAttribute()] get; [SuppressUnmanagedCodeSecurityAttribute()] set; } int ControlCode { [SuppressUnmanagedCodeSecurityAttribute()] get; [SuppressUnmanagedCodeSecurityAttribute()] set; } object Values { get; set; } } public interface IAdsPropertyList { int PropertyCount { [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurityAttribute()] get; } [return: MarshalAs(UnmanagedType.I4)] [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int Next([Out] out object nextProp); void Skip([In] int cElements); [SuppressUnmanagedCodeSecurityAttribute()] void Reset(); object Item([In] object varIndex); object GetPropertyItem([In, MarshalAs(UnmanagedType.BStr)] string bstrName, int ADsType); [SuppressUnmanagedCodeSecurityAttribute()] void PutPropertyItem([In] object varData); void ResetPropertyItem([In] object varEntry); void PurgePropertyList(); } [ComImport, Guid("109BA8EC-92F0-11D0-A790-00C04FD8D5A8"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)] public interface IDirectorySearch { [SuppressUnmanagedCodeSecurityAttribute()] void SetSearchPreference( [In] IntPtr /*ads_searchpref_info * */pSearchPrefs, //ads_searchpref_info[] pSearchPrefs, int dwNumPrefs); [SuppressUnmanagedCodeSecurityAttribute()] void ExecuteSearch( [In, MarshalAs(UnmanagedType.LPWStr)] string pszSearchFilter, [In, MarshalAs(UnmanagedType.LPArray)] string[] pAttributeNames, [In] int dwNumberAttributes, [Out] out IntPtr hSearchResult); [SuppressUnmanagedCodeSecurityAttribute()] void AbandonSearch([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int GetFirstRow([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int GetNextRow([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int GetPreviousRow([In] IntPtr hSearchResult); [return: MarshalAs(UnmanagedType.U4)] [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int GetNextColumnName( [In] IntPtr hSearchResult, [Out] IntPtr ppszColumnName); [SuppressUnmanagedCodeSecurityAttribute()] void GetColumn( [In] IntPtr hSearchResult, [In] //, MarshalAs(UnmanagedType.LPWStr)] IntPtr /* char * */ szColumnName, [In] IntPtr pSearchColumn); [SuppressUnmanagedCodeSecurityAttribute()] void FreeColumn( [In] IntPtr pSearchColumn); [SuppressUnmanagedCodeSecurityAttribute()] void CloseSearchHandle([In] IntPtr hSearchResult); } public interface IAdsObjectOptions { object GetOption(int flag); [SuppressUnmanagedCodeSecurityAttribute()] void SetOption(int flag, [In] object varValue); } // for boolean type, the default marshaller does not work, so need to have specific marshaller. For other types, use the // default marshaller which is more efficient public interface IAdsObjectOptions2 { [SuppressUnmanagedCodeSecurityAttribute()] [PreserveSig] int GetOption(int flag, [Out] out object value); [SuppressUnmanagedCodeSecurityAttribute()] void SetOption(int option, Variant value); } // IDirecorySearch return codes internal const int S_ADS_NOMORE_ROWS = 0x00005012; internal const int INVALID_FILTER = unchecked((int)0x8007203E); internal const int SIZE_LIMIT_EXCEEDED = unchecked((int)0x80072023); } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Security.Cryptography { public abstract partial class Aes : System.Security.Cryptography.SymmetricAlgorithm { protected Aes() { } public static new System.Security.Cryptography.Aes Create() { throw null; } public static new System.Security.Cryptography.Aes Create(string algorithmName) { throw null; } } public sealed class AesGcm : IDisposable { public AesGcm(ReadOnlySpan<byte> key) { } public AesGcm(byte[] key) { } public static KeySizes TagByteSizes { get => throw null; } public static KeySizes NonceByteSizes { get => throw null; } public void Encrypt(ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> plaintext, Span<byte> ciphertext, Span<byte> tag, ReadOnlySpan<byte> associatedData = default) => throw null; public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null) => throw null; public void Decrypt(ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> tag, Span<byte> plaintext, ReadOnlySpan<byte> associatedData = default) => throw null; public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = default) => throw null; public void Dispose() { } } public sealed class AesCcm : IDisposable { public AesCcm(ReadOnlySpan<byte> key) { } public AesCcm(byte[] key) { } public static KeySizes TagByteSizes { get => throw null; } public static KeySizes NonceByteSizes { get => throw null; } public void Encrypt(ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> plaintext, Span<byte> ciphertext, Span<byte> tag, ReadOnlySpan<byte> associatedData = default) => throw null; public void Encrypt(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag, byte[] associatedData = null) => throw null; public void Decrypt(ReadOnlySpan<byte> nonce, ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> tag, Span<byte> plaintext, ReadOnlySpan<byte> associatedData = default) => throw null; public void Decrypt(byte[] nonce, byte[] ciphertext, byte[] tag, byte[] plaintext, byte[] associatedData = default) => throw null; public void Dispose() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class AesManaged : System.Security.Cryptography.Aes { public AesManaged() { } public override int BlockSize { get { throw null; } set { } } public override int FeedbackSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalBlockSizes { get { throw null; } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public abstract partial class AsymmetricKeyExchangeDeformatter { protected AsymmetricKeyExchangeDeformatter() { } public abstract string Parameters { get; set; } public abstract byte[] DecryptKeyExchange(byte[] rgb); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public abstract partial class AsymmetricKeyExchangeFormatter { protected AsymmetricKeyExchangeFormatter() { } public abstract string Parameters { get; } public abstract byte[] CreateKeyExchange(byte[] data); public abstract byte[] CreateKeyExchange(byte[] data, System.Type symAlgType); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public abstract partial class AsymmetricSignatureDeformatter { protected AsymmetricSignatureDeformatter() { } public abstract void SetHashAlgorithm(string strName); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature); public virtual bool VerifySignature(System.Security.Cryptography.HashAlgorithm hash, byte[] rgbSignature) { throw null; } } public abstract partial class AsymmetricSignatureFormatter { protected AsymmetricSignatureFormatter() { } public abstract byte[] CreateSignature(byte[] rgbHash); public virtual byte[] CreateSignature(System.Security.Cryptography.HashAlgorithm hash) { throw null; } public abstract void SetHashAlgorithm(string strName); public abstract void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key); } public partial class CryptoConfig { public CryptoConfig() { } public static bool AllowOnlyFipsAlgorithms { get { throw null; } } public static void AddAlgorithm(System.Type algorithm, params string[] names) { } public static void AddOID(string oid, params string[] names) { } public static object CreateFromName(string name) { throw null; } public static object CreateFromName(string name, params object[] args) { throw null; } public static byte[] EncodeOID(string str) { throw null; } public static string MapNameToOID(string name) { throw null; } } public abstract partial class DeriveBytes : System.IDisposable { protected DeriveBytes() { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract byte[] GetBytes(int cb); public abstract void Reset(); } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public abstract partial class DES : System.Security.Cryptography.SymmetricAlgorithm { protected DES() { } public override byte[] Key { get { throw null; } set { } } public static new System.Security.Cryptography.DES Create() { throw null; } public static new System.Security.Cryptography.DES Create(string algName) { throw null; } public static bool IsSemiWeakKey(byte[] rgbKey) { throw null; } public static bool IsWeakKey(byte[] rgbKey) { throw null; } } public abstract partial class DSA : System.Security.Cryptography.AsymmetricAlgorithm { protected DSA() { } public static new System.Security.Cryptography.DSA Create() { throw null; } public static System.Security.Cryptography.DSA Create(int keySizeInBits) { throw null; } public static new System.Security.Cryptography.DSA Create(string algName) { throw null; } public static System.Security.Cryptography.DSA Create(System.Security.Cryptography.DSAParameters parameters) { throw null; } public abstract byte[] CreateSignature(byte[] rgbHash); public abstract System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters); public override void FromXmlString(string xmlString) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract void ImportParameters(System.Security.Cryptography.DSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public override string ToXmlString(bool includePrivateParameters) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract bool VerifySignature(byte[] rgbHash, byte[] rgbSignature); } public partial struct DSAParameters { public int Counter; public byte[] G; public byte[] J; public byte[] P; public byte[] Q; public byte[] Seed; public byte[] X; public byte[] Y; } public partial class DSASignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter { public DSASignatureDeformatter() { } public DSASignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial class DSASignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter { public DSASignatureFormatter() { } public DSASignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial struct ECCurve { private object _dummy; public byte[] A; public byte[] B; public byte[] Cofactor; public System.Security.Cryptography.ECCurve.ECCurveType CurveType; public System.Security.Cryptography.ECPoint G; public System.Nullable<System.Security.Cryptography.HashAlgorithmName> Hash; public byte[] Order; public byte[] Polynomial; public byte[] Prime; public byte[] Seed; public bool IsCharacteristic2 { get { throw null; } } public bool IsExplicit { get { throw null; } } public bool IsNamed { get { throw null; } } public bool IsPrime { get { throw null; } } public System.Security.Cryptography.Oid Oid { get { throw null; } } public static System.Security.Cryptography.ECCurve CreateFromFriendlyName(string oidFriendlyName) { throw null; } public static System.Security.Cryptography.ECCurve CreateFromOid(System.Security.Cryptography.Oid curveOid) { throw null; } public static System.Security.Cryptography.ECCurve CreateFromValue(string oidValue) { throw null; } public void Validate() { } public enum ECCurveType { Characteristic2 = 4, Implicit = 0, Named = 5, PrimeMontgomery = 3, PrimeShortWeierstrass = 1, PrimeTwistedEdwards = 2, } public static partial class NamedCurves { public static System.Security.Cryptography.ECCurve brainpoolP160r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP160t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP192r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP192t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP224r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP224t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP256r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP256t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP320r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP320t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP384r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP384t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP512r1 { get { throw null; } } public static System.Security.Cryptography.ECCurve brainpoolP512t1 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP256 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP384 { get { throw null; } } public static System.Security.Cryptography.ECCurve nistP521 { get { throw null; } } } } public abstract partial class ECDiffieHellman : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDiffieHellman() { } public override string KeyExchangeAlgorithm { get { throw null; } } public abstract System.Security.Cryptography.ECDiffieHellmanPublicKey PublicKey { get; } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.ECDiffieHellman Create() { throw null; } public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECCurve curve) { throw null; } public static System.Security.Cryptography.ECDiffieHellman Create(System.Security.Cryptography.ECParameters parameters) { throw null; } public static new System.Security.Cryptography.ECDiffieHellman Create(string algorithm) { throw null; } public byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw null; } public byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey) { throw null; } public virtual byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { throw null; } public virtual byte[] DeriveKeyMaterial(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; } public virtual byte[] DeriveKeyTls(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; } public override void FromXmlString(string xmlString) { } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public override string ToXmlString(bool includePrivateParameters) { throw null; } } public abstract partial class ECDiffieHellmanPublicKey : System.IDisposable { protected ECDiffieHellmanPublicKey() { } protected ECDiffieHellmanPublicKey(byte[] keyBlob) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual byte[] ToByteArray() { throw null; } public virtual string ToXmlString() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters() { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters() { throw null; } } public abstract partial class ECDsa : System.Security.Cryptography.AsymmetricAlgorithm { protected ECDsa() { } public override string KeyExchangeAlgorithm { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.ECDsa Create() { throw null; } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECCurve curve) { throw null; } public static System.Security.Cryptography.ECDsa Create(System.Security.Cryptography.ECParameters parameters) { throw null; } public static new System.Security.Cryptography.ECDsa Create(string algorithm) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; } public virtual System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; } public override void FromXmlString(string xmlString) { } public virtual void GenerateKey(System.Security.Cryptography.ECCurve curve) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual void ImportParameters(System.Security.Cryptography.ECParameters parameters) { } public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract byte[] SignHash(byte[] hash); public override string ToXmlString(bool includePrivateParameters) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract bool VerifyHash(byte[] hash, byte[] signature); } public partial struct ECParameters { public System.Security.Cryptography.ECCurve Curve; public byte[] D; public System.Security.Cryptography.ECPoint Q; public void Validate() { } } public partial struct ECPoint { public byte[] X; public byte[] Y; } public partial class HMACMD5 : System.Security.Cryptography.HMAC { public HMACMD5() { } public HMACMD5(byte[] key) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA1 : System.Security.Cryptography.HMAC { public HMACSHA1() { } public HMACSHA1(byte[] key) { } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public HMACSHA1(byte[] key, bool useManagedSha1) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA256 : System.Security.Cryptography.HMAC { public HMACSHA256() { } public HMACSHA256(byte[] key) { } public override byte[] Key { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA384 : System.Security.Cryptography.HMAC { public HMACSHA384() { } public HMACSHA384(byte[] key) { } public override byte[] Key { get { throw null; } set { } } public bool ProduceLegacyHmacValues { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class HMACSHA512 : System.Security.Cryptography.HMAC { public HMACSHA512() { } public HMACSHA512(byte[] key) { } public override byte[] Key { get { throw null; } set { } } public bool ProduceLegacyHmacValues { get { throw null; } set { } } protected override void Dispose(bool disposing) { } protected override void HashCore(byte[] rgb, int ib, int cb) { } protected override void HashCore(System.ReadOnlySpan<byte> source) { } protected override byte[] HashFinal() { throw null; } public override void Initialize() { } protected override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public sealed partial class IncrementalHash : System.IDisposable { internal IncrementalHash() { } public System.Security.Cryptography.HashAlgorithmName AlgorithmName { get { throw null; } } public void AppendData(byte[] data) { } public void AppendData(byte[] data, int offset, int count) { } public static System.Security.Cryptography.IncrementalHash CreateHash(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public static System.Security.Cryptography.IncrementalHash CreateHMAC(System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] key) { throw null; } public void Dispose() { } public byte[] GetHashAndReset() { throw null; } } public abstract partial class MaskGenerationMethod { public abstract byte[] GenerateMask(byte[] rgbSeed, int cbReturn); } public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm { protected MD5() { } public static new System.Security.Cryptography.MD5 Create() { throw null; } public static new System.Security.Cryptography.MD5 Create(string algName) { throw null; } } public partial class PKCS1MaskGenerationMethod : System.Security.Cryptography.MaskGenerationMethod { public PKCS1MaskGenerationMethod() { } public string HashName { get { throw null; } set { } } public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) { throw null; } } public abstract partial class RandomNumberGenerator : System.IDisposable { protected RandomNumberGenerator() { } public static System.Security.Cryptography.RandomNumberGenerator Create() { throw null; } public static System.Security.Cryptography.RandomNumberGenerator Create(string rngName) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public abstract void GetBytes(byte[] data); public virtual void GetBytes(byte[] data, int offset, int count) { } public virtual void GetNonZeroBytes(byte[] data) { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public abstract partial class RC2 : System.Security.Cryptography.SymmetricAlgorithm { protected int EffectiveKeySizeValue; protected RC2() { } public virtual int EffectiveKeySize { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public static new System.Security.Cryptography.RC2 Create() { throw null; } public static new System.Security.Cryptography.RC2 Create(string AlgName) { throw null; } } public partial class Rfc2898DeriveBytes : System.Security.Cryptography.DeriveBytes { public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public Rfc2898DeriveBytes(string password, byte[] salt) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations) { } public Rfc2898DeriveBytes(string password, byte[] salt, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public Rfc2898DeriveBytes(string password, int saltSize) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations) { } public Rfc2898DeriveBytes(string password, int saltSize, int iterations, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { } public System.Security.Cryptography.HashAlgorithmName HashAlgorithm { get { throw null; } } public int IterationCount { get { throw null; } set { } } public byte[] Salt { get { throw null; } set { } } public byte[] CryptDeriveKey(string algname, string alghashname, int keySize, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override byte[] GetBytes(int cb) { throw null; } public override void Reset() { } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public abstract partial class Rijndael : System.Security.Cryptography.SymmetricAlgorithm { protected Rijndael() { } public static new System.Security.Cryptography.Rijndael Create() { throw null; } public static new System.Security.Cryptography.Rijndael Create(string algName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class RijndaelManaged : System.Security.Cryptography.Rijndael { public RijndaelManaged() { } public override int BlockSize { get { throw null; } set { } } public override byte[] IV { get { throw null; } set { } } public override byte[] Key { get { throw null; } set { } } public override int KeySize { get { throw null; } set { } } public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } } public override System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } } public override System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; } public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; } protected override void Dispose(bool disposing) { } public override void GenerateIV() { } public override void GenerateKey() { } } public abstract partial class RSA : System.Security.Cryptography.AsymmetricAlgorithm { protected RSA() { } public override string KeyExchangeAlgorithm { get { throw null; } } public override string SignatureAlgorithm { get { throw null; } } public static new System.Security.Cryptography.RSA Create() { throw null; } public static System.Security.Cryptography.RSA Create(int keySizeInBits) { throw null; } public static System.Security.Cryptography.RSA Create(System.Security.Cryptography.RSAParameters parameters) { throw null; } public static new System.Security.Cryptography.RSA Create(string algName) { throw null; } public virtual byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public virtual byte[] DecryptValue(byte[] rgb) { throw null; } public virtual byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; } public virtual byte[] EncryptValue(byte[] rgb) { throw null; } public abstract System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters); public override void FromXmlString(string xmlString) { } protected virtual byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } protected virtual byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public abstract void ImportParameters(System.Security.Cryptography.RSAParameters parameters); public virtual byte[] SignData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public byte[] SignData(byte[] data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual byte[] SignData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public override string ToXmlString(bool includePrivateParameters) { throw null; } public bool VerifyData(byte[] data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public bool VerifyData(System.IO.Stream data, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } public virtual bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; } } public sealed partial class RSAEncryptionPadding : System.IEquatable<System.Security.Cryptography.RSAEncryptionPadding> { internal RSAEncryptionPadding() { } public System.Security.Cryptography.RSAEncryptionPaddingMode Mode { get { throw null; } } public System.Security.Cryptography.HashAlgorithmName OaepHashAlgorithm { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA1 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA256 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA384 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding OaepSHA512 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding Pkcs1 { get { throw null; } } public static System.Security.Cryptography.RSAEncryptionPadding CreateOaep(System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; } public override bool Equals(object obj) { throw null; } public bool Equals(System.Security.Cryptography.RSAEncryptionPadding other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; } public static bool operator !=(System.Security.Cryptography.RSAEncryptionPadding left, System.Security.Cryptography.RSAEncryptionPadding right) { throw null; } public override string ToString() { throw null; } } public enum RSAEncryptionPaddingMode { Oaep = 1, Pkcs1 = 0, } public partial class RSAOAEPKeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter { public RSAOAEPKeyExchangeDeformatter() { } public RSAOAEPKeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } set { } } public override byte[] DecryptKeyExchange(byte[] rgbData) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAOAEPKeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter { public RSAOAEPKeyExchangeFormatter() { } public RSAOAEPKeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public byte[] Parameter { get { throw null; } set { } } public override string Parameters { get { throw null; } } public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } } public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; } public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial struct RSAParameters { public byte[] D; public byte[] DP; public byte[] DQ; public byte[] Exponent; public byte[] InverseQ; public byte[] Modulus; public byte[] P; public byte[] Q; } public partial class RSAPKCS1KeyExchangeDeformatter : System.Security.Cryptography.AsymmetricKeyExchangeDeformatter { public RSAPKCS1KeyExchangeDeformatter() { } public RSAPKCS1KeyExchangeDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } set { } } public System.Security.Cryptography.RandomNumberGenerator RNG { get { throw null; } set { } } public override byte[] DecryptKeyExchange(byte[] rgbIn) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAPKCS1KeyExchangeFormatter : System.Security.Cryptography.AsymmetricKeyExchangeFormatter { public RSAPKCS1KeyExchangeFormatter() { } public RSAPKCS1KeyExchangeFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override string Parameters { get { throw null; } } public System.Security.Cryptography.RandomNumberGenerator Rng { get { throw null; } set { } } public override byte[] CreateKeyExchange(byte[] rgbData) { throw null; } public override byte[] CreateKeyExchange(byte[] rgbData, System.Type symAlgType) { throw null; } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public partial class RSAPKCS1SignatureDeformatter : System.Security.Cryptography.AsymmetricSignatureDeformatter { public RSAPKCS1SignatureDeformatter() { } public RSAPKCS1SignatureDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; } } public partial class RSAPKCS1SignatureFormatter : System.Security.Cryptography.AsymmetricSignatureFormatter { public RSAPKCS1SignatureFormatter() { } public RSAPKCS1SignatureFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { } public override byte[] CreateSignature(byte[] rgbHash) { throw null; } public override void SetHashAlgorithm(string strName) { } public override void SetKey(System.Security.Cryptography.AsymmetricAlgorithm key) { } } public sealed partial class RSASignaturePadding : System.IEquatable<System.Security.Cryptography.RSASignaturePadding> { internal RSASignaturePadding() { } public System.Security.Cryptography.RSASignaturePaddingMode Mode { get { throw null; } } public static System.Security.Cryptography.RSASignaturePadding Pkcs1 { get { throw null; } } public static System.Security.Cryptography.RSASignaturePadding Pss { get { throw null; } } public override bool Equals(object obj) { throw null; } public bool Equals(System.Security.Cryptography.RSASignaturePadding other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; } public static bool operator !=(System.Security.Cryptography.RSASignaturePadding left, System.Security.Cryptography.RSASignaturePadding right) { throw null; } public override string ToString() { throw null; } } public enum RSASignaturePaddingMode { Pkcs1 = 0, Pss = 1, } public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm { protected SHA1() { } public static new System.Security.Cryptography.SHA1 Create() { throw null; } public static new System.Security.Cryptography.SHA1 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA1Managed : System.Security.Cryptography.SHA1 { public SHA1Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm { protected SHA256() { } public static new System.Security.Cryptography.SHA256 Create() { throw null; } public static new System.Security.Cryptography.SHA256 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA256Managed : System.Security.Cryptography.SHA256 { public SHA256Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm { protected SHA384() { } public static new System.Security.Cryptography.SHA384 Create() { throw null; } public static new System.Security.Cryptography.SHA384 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA384Managed : System.Security.Cryptography.SHA384 { public SHA384Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm { protected SHA512() { } public static new System.Security.Cryptography.SHA512 Create() { throw null; } public static new System.Security.Cryptography.SHA512 Create(string hashName) { throw null; } } [System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))] public sealed partial class SHA512Managed : System.Security.Cryptography.SHA512 { public SHA512Managed() { } protected sealed override void Dispose(bool disposing) { } protected sealed override void HashCore(byte[] array, int ibStart, int cbSize) { } protected sealed override void HashCore(System.ReadOnlySpan<byte> source) { } protected sealed override byte[] HashFinal() { throw null; } public sealed override void Initialize() { } protected sealed override bool TryHashFinal(System.Span<byte> destination, out int bytesWritten) { throw null; } } public partial class SignatureDescription { public SignatureDescription() { } public SignatureDescription(System.Security.SecurityElement el) { } public string DeformatterAlgorithm { get { throw null; } set { } } public string DigestAlgorithm { get { throw null; } set { } } public string FormatterAlgorithm { get { throw null; } set { } } public string KeyAlgorithm { get { throw null; } set { } } public virtual System.Security.Cryptography.AsymmetricSignatureDeformatter CreateDeformatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } public virtual System.Security.Cryptography.HashAlgorithm CreateDigest() { throw null; } public virtual System.Security.Cryptography.AsymmetricSignatureFormatter CreateFormatter(System.Security.Cryptography.AsymmetricAlgorithm key) { throw null; } } public abstract partial class TripleDES : System.Security.Cryptography.SymmetricAlgorithm { protected TripleDES() { } public override byte[] Key { get { throw null; } set { } } public static new System.Security.Cryptography.TripleDES Create() { throw null; } public static new System.Security.Cryptography.TripleDES Create(string str) { throw null; } public static bool IsWeakKey(byte[] rgbKey) { throw null; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Abstractions; using System.IO.Abstractions.TestingHelpers; using System.Reflection; using System.Runtime.InteropServices; using NSubstitute; using NUnit.Framework; using TSQLLint.Common; using TSQLLint.Core.Interfaces; using TSQLLint.Infrastructure.Parser; using TSQLLint.Infrastructure.Plugins; using TSQLLint.Tests.Helpers; namespace TSQLLint.Tests.UnitTests.PluginHandler { public class PluginHandlerTests { [Test] public void LoadPlugins_ShouldLoadPluginsFromPathAndFile() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_one.dll"); var filePath2 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_two.dll"); var filePath3 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_three.dll"); var filePath4 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\foo.txt"); var filePath5 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\subDirectory\bar.txt"); var filePath6 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\subDirectory\plugin_four.dll"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData(string.Empty) }, { filePath2, new MockFileData(string.Empty) }, { filePath3, new MockFileData(string.Empty) }, { filePath4, new MockFileData("foo") }, { filePath5, new MockFileData("bar") }, { filePath6, new MockFileData(string.Empty) }, }); var assemblyWrapper = new TestAssemblyWrapper(new Dictionary<string, int> { { TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_one.dll"), 0 }, { TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_two.dll"), 1 }, { TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_three.dll"), 2 }, { TestHelper.GetTestFilePath(@"c:\pluginDirectory\subDirectory\plugin_four.dll"), 3 } }); var reporter = Substitute.For<IReporter>(); var versionWrapper = Substitute.For<IFileversionWrapper>(); versionWrapper.GetVersion(Arg.Any<Assembly>()).Returns("1.2.3"); var pluginPaths = new Dictionary<string, string> { { "my-first-plugin", TestHelper.GetTestFilePath(@"c:\pluginDirectory\") }, { "my-second-plugin", filePath6 } }; // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); // assert Assert.AreEqual(4, pluginHandler.Plugins.Count); } [Test] public void LoadPlugins_ShouldLoadPluginsFilesWithRelativePaths() { // arrange var currentDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location); var executingLocationParentFolder = currentDirectory.Parent.FullName; var filePath1 = Path.Combine(executingLocationParentFolder, "plugin_one.dll"); var filePath2 = Path.Combine(executingLocationParentFolder, "plugin_two.dll"); var fileSystem = new MockFileSystem( new Dictionary<string, MockFileData> { { filePath1, new MockFileData(string.Empty) }, { filePath2, new MockFileData(string.Empty) } }, currentDirectory.FullName); var assemblyWrapper = new TestAssemblyWrapper(); var reporter = Substitute.For<IReporter>(); var versionWrapper = Substitute.For<IFileversionWrapper>(); versionWrapper.GetVersion(Arg.Any<Assembly>()).Returns("1.2.3"); var pluginPaths = new Dictionary<string, string> { { "my-second-plugin", @"..\plugin_two.dll" } }; // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); // assert Assert.AreEqual(1, pluginHandler.Plugins.Count); } [Test] public void LoadPlugins_ShouldLoadPluginsDirectoriesWithRelativePaths() { // arrange var pluginName = "plugin_one.dll"; var currentDirectory = Directory.GetParent(Assembly.GetExecutingAssembly().Location); var executingLocationParentFolder = currentDirectory.Parent.FullName; var filePath1 = Path.Combine(executingLocationParentFolder, "subDirectory", pluginName); var fileSystem = new MockFileSystem( new Dictionary<string, MockFileData> { { filePath1, new MockFileData(string.Empty) } }, currentDirectory.FullName); var assemblyWrapper = new TestAssemblyWrapper(); var reporter = Substitute.For<IReporter>(); var versionWrapper = Substitute.For<IFileversionWrapper>(); versionWrapper.GetVersion(Arg.Any<Assembly>()).Returns("1.2.3"); var pluginPaths = new Dictionary<string, string> { { pluginName, @"..\subDirectory" } }; // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); // assert Assert.AreEqual(1, pluginHandler.Plugins.Count); } [Test] public void LoadPlugins_ThrowErrors_When_Same_Type_Is_Loaded_More_Than_Once() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_one.dll"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData(string.Empty) } }); var assemblyWrapper = new TestAssemblyWrapper(defaultPlugin: typeof(TestPluginThrowsException)); var pluginPaths = new Dictionary<string, string> { { "my-plugin", filePath1 }, { "my-plugin-directories", TestHelper.GetTestFilePath(@"c:\pluginDirectory") }, { "my-plugin-invalid-path", TestHelper.GetTestFilePath(@"c:\doesnt-exist") } }; var versionWrapper = Substitute.For<IFileversionWrapper>(); versionWrapper.GetVersion(Arg.Any<Assembly>()).Returns("1.2.3"); var reporter = Substitute.For<IReporter>(); // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); // assert Assert.AreEqual(1, pluginHandler.Plugins.Count); var type = typeof(TestPluginThrowsException); reporter.Received().Report($"Loaded plugin: '{type.FullName}', Version: '1.2.3'"); reporter.Received().Report($"Already loaded plugin with type '{type.FullName}'"); } [Test] public void ActivatePlugins_PluginRuleViolations_ShouldCallReporter() { // arrange var filePath1 = TestHelper.GetTestFilePath(@"c:\pluginDirectory\plugin_one.dll"); var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { filePath1, new MockFileData(string.Empty) } }); var assemblyWrapper = new TestAssemblyWrapper(); var pluginPaths = new Dictionary<string, string> { { "my-plugin", filePath1 } }; var reporter = Substitute.For<IReporter>(); var textReader = ParsingUtility.CreateTextReaderFromString("\tSELECT * FROM FOO"); var scriptPath = TestHelper.GetTestFilePath(@"c:\scripts\foo.sql"); var context = new PluginContext(scriptPath, new List<IRuleException>(), textReader); var versionWrapper = Substitute.For<IFileversionWrapper>(); versionWrapper.GetVersion(Arg.Any<Assembly>()).Returns("1.2.3"); // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, fileSystem, assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); // assert Assert.AreEqual(1, pluginHandler.Plugins.Count); Assert.DoesNotThrow(() => pluginHandler.ActivatePlugins(context)); reporter.Received().ReportViolation(Arg.Is<IRuleViolation>(x => x.FileName == context.FilePath && x.RuleName == "prefer-tabs" && x.Text == "Should use spaces rather than tabs" && x.Line == 1 && x.Column == 0 && x.Severity == RuleViolationSeverity.Warning)); } [Test] public void ActivatePlugins_ThrowErrors_ShouldCatch_ShouldReport() { // arrange var testFilePath = TestHelper.GetTestFilePath(@"UnitTests/PluginHandler/tsqllint-plugin-throws-exception.dll"); var path = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, testFilePath)); var assemblyWrapper = new AssemblyWrapper(); var pluginPaths = new Dictionary<string, string> { { "my-plugin", path } }; var reporter = Substitute.For<IReporter>(); var versionWrapper = Substitute.For<IFileversionWrapper>(); var context = Substitute.For<IPluginContext>(); versionWrapper.GetVersion(Arg.Any<Assembly>()).Returns("1.2.3"); // act var pluginHandler = new Infrastructure.Plugins.PluginHandler(reporter, new FileSystem(), assemblyWrapper, versionWrapper); pluginHandler.ProcessPaths(pluginPaths); pluginHandler.ActivatePlugins(context); // assert Assert.AreEqual(1, pluginHandler.Plugins.Count); reporter.Received().Report(@"There was a problem with plugin: tsqllint_plugin_throws_exception.PluginThatThrows - something bad happened"); } public class TestPlugin2 : TestPlugin { } public class TestPlugin3 : TestPlugin { } public class TestPlugin4 : TestPlugin { } public class TestPluginThrowsException : IPlugin { public void PerformAction(IPluginContext context, IReporter reporter) { throw new NotImplementedException(); } } public class TestAssemblyWrapper : IAssemblyWrapper { private readonly Assembly assembly; private readonly Dictionary<string, int> pathsToPluginNumber; private string assemblyLoaded; private Type defaultPlugin; public TestAssemblyWrapper(Dictionary<string, int> pathsToPluginNumber = null, Type defaultPlugin = null) { assembly = Assembly.GetExecutingAssembly(); this.pathsToPluginNumber = pathsToPluginNumber; this.defaultPlugin = defaultPlugin ?? typeof(TestPlugin); } public Assembly LoadFile(string path) { assemblyLoaded = path; return assembly; } public Type[] GetExportedTypes(Assembly assembly) { if (pathsToPluginNumber == null || !pathsToPluginNumber.ContainsKey(assemblyLoaded)) { return new[] { defaultPlugin }; } return pathsToPluginNumber[assemblyLoaded] switch { 0 => new[] { defaultPlugin }, 1 => new[] { typeof(TestPlugin2) }, 2 => new[] { typeof(TestPlugin3) }, _ => new[] { typeof(TestPlugin4) } }; } } } }
using System; using System.Collections; using System.Collections.Generic; #if FRB_MDX using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Microsoft.DirectX.DirectInput; using Direct3D=Microsoft.DirectX.Direct3D; using Keys = Microsoft.DirectX.DirectInput.Key; #elif FRB_XNA || SILVERLIGHT using Microsoft.Xna.Framework.Input; #endif using FlatRedBall.Input; using FlatRedBall.Graphics; namespace FlatRedBall.Gui { /// <summary> /// A List Box which can hold collapsable items. /// </summary> public class CollapseListBox : ListBoxBase { #region Fields const float horizontalBottom = 166/256f; const float horizontalPixelWidth = 2/256f; const float cornerBottom = 169/256f; const float cornerPixelWidth = 2/256f; const float centerLeft = 18/256f; const float centerRight = 19/256f; const float centerTop = 162/256f; const float centerBottom = 163 / 256f; // The right-click list window that appears ListBox mListBox; #endregion #region Properties public bool ShowExpandCollapseAllOption { get; set; } #endregion #region Event Methods private void PopupListBoxClick(Window callingWindow) { CollapseItem item = mListBox.GetFirstHighlightedItem(); mListBox.Visible = false; if (item == null) { return; } if (item.Text == "Expand All") { ExpandAll(); } else if (item.Text == "Collapse All") { CollapseAll(); } } private void OnRightClick(Window callingWindow) { if (ShowExpandCollapseAllOption) { GuiManager.AddPerishableWindow(mListBox); mListBox.Visible = true; GuiManager.PositionTopLeftToCursor(mListBox); } } #endregion #region Methods #region Constructor public CollapseListBox(Cursor cursor) : base(cursor) { mListBox = new ListBox(mCursor); mListBox.AddItem("Expand All"); mListBox.AddItem("Collapse All"); mListBox.SetScaleToContents(0); mListBox.HighlightOnRollOver = true; mListBox.ScrollBarVisible = false; mListBox.Click += PopupListBoxClick; SecondaryClick += OnRightClick; } #endregion #region Public Methods public CollapseItem AddItemUnique(String stringToAdd, object ReferenceObject) { if(this.ContainsObject(ReferenceObject)) return GetItem(ReferenceObject); else return AddItem(stringToAdd, ReferenceObject); } public CollapseItem AddItemToItem(string stringToAdd, object ReferenceObject, CollapseItem itemToAddTo) { CollapseItem itemToReturn = itemToAddTo.AddItem(stringToAdd, ReferenceObject); AdjustScrollSize(); return itemToReturn; } public CollapseItem AttachItem(CollapseItem itemToAttach) { itemToAttach.mParentBox = this; itemToAttach.parentItem = null; Items.Add(itemToAttach); AdjustScrollSize(); return itemToAttach; } public void Clear() { Items.Clear(); float numShowing = ((float)mScaleY - 1) / (Items.Count); if (numShowing > 1) numShowing = 1; mScrollBar.View = numShowing; mScrollBar.Sensitivity = (1 / (float)(Items.Count - (int)(mScaleY - 1))); mScrollBar.SetScrollPosition(mStartAt); } public override void ClearEvents() { base.ClearEvents(); } public void CollapseAll() { foreach (CollapseItem collapseItem in mItems) { collapseItem.CollapseAll(); } AdjustScrollSize(); } public bool ContainsObject(object objectToSearchFor) { for (int i = 0; i < Items.Count; i++) { if (Items[i].Contains(objectToSearchFor)) return true; } return false; } public void DeselectObject(object objectToDeselect) { CollapseItem ci = GetItem(objectToDeselect); if (ci != null && mHighlightedItems.Contains(ci)) { mHighlightedItems.Remove(ci); } } public void ExpandAll() { foreach (CollapseItem collapseItem in mItems) { collapseItem.ExpandAll(); } AdjustScrollSize(); } public List<CollapseItem> GetHighlightedItems() { return mHighlightedItems; } public Object GetFirstHighlightedParentObject() { if (this.mHighlightedItems.Count == 0) return null; else { if (mHighlightedItems[0].parentItem != null) return mHighlightedItems[0].parentItem.ReferenceObject; else return null; } } public string GetFirstHighlightedString() { if (mHighlightedItems.Count != 0) return mHighlightedItems[0].Text; else return ""; } public object GetLastHighlightedObject() { if (mHighlightedItems.Count != 0) return mHighlightedItems[mHighlightedItems.Count - 1].ReferenceObject; else return null; } public int GetNumContained(object objectToCount) { int count = 0; for (int i = 0; i < Items.Count; i++) { Items[i].GetNumContained(objectToCount, ref count); } return count; } public Object GetObject(string objectToGet) { Object objectToReturn = null; for (int i = 0; i < Items.Count; i++) { objectToReturn = Items[i].GetObject(objectToGet); if (objectToReturn != null) return objectToReturn; } return null; } public int IndexOf(object objectToSearchFor) { for (int i = 0; i < Items.Count; i++) { if (Items[i].ReferenceObject == objectToSearchFor) { return i; } } return -1; } public bool MoveItemUp(CollapseItem itemToMove) { // if the item belongs to another item if (itemToMove.parentItem != null) { int num = itemToMove.parentItem.mItems.IndexOf(itemToMove); if (num == 0) return false; itemToMove.parentItem.mItems.Remove(itemToMove); itemToMove.parentItem.mItems.Insert(num - 1, itemToMove); } else // item belongs to a ListBox { if (itemToMove.parentBox is CollapseListBox) { CollapseListBox parentAsCollapseListBox = itemToMove.parentBox as CollapseListBox; int num = parentAsCollapseListBox.Items.IndexOf(itemToMove); if (num == 0) return false; parentAsCollapseListBox.Items.Remove(itemToMove); parentAsCollapseListBox.Items.Insert(num - 1, itemToMove); } else if (itemToMove.parentBox is ListBox) { ListBox parentAsListBox = itemToMove.parentBox as ListBox; int num = parentAsListBox.mItems.IndexOf(itemToMove); if (num == 0) return false; parentAsListBox.mItems.Remove(itemToMove); parentAsListBox.mItems.Insert(num - 1, itemToMove); } } return true; } public bool MoveItemDown(CollapseItem itemToMove) { // if the item belongs to another item if (itemToMove.parentItem != null) { int num = itemToMove.parentItem.mItems.IndexOf(itemToMove); if (num == itemToMove.parentItem.mItems.Count - 1) return false; itemToMove.parentItem.mItems.Remove(itemToMove); itemToMove.parentItem.mItems.Insert(num + 1, itemToMove); } else // item belongs to a ListBox { if (itemToMove.parentBox is CollapseListBox) { CollapseListBox parentAsCollapseListBox = itemToMove.parentBox as CollapseListBox; int num = parentAsCollapseListBox.Items.IndexOf(itemToMove); if (itemToMove.ParentItem != null && num == itemToMove.parentItem.mItems.Count - 1) return false; parentAsCollapseListBox.Items.Remove(itemToMove); parentAsCollapseListBox.Items.Insert(num + 1, itemToMove); } else if (itemToMove.parentBox is ListBox) { ListBox parentAsListBox = itemToMove.parentBox as ListBox; int num = parentAsListBox.mItems.IndexOf(itemToMove); if (num == itemToMove.parentItem.mItems.Count - 1) return false; parentAsListBox.mItems.Remove(itemToMove); parentAsListBox.mItems.Insert(num + 1, itemToMove); } } return true; } public CollapseItem MoveLeftOne(string itemToRemove) { CollapseItem tempItem = GetItemByName(itemToRemove); if (tempItem != null) tempItem.MoveLeftOne(); return tempItem; } public CollapseItem MoveLeftOne(CollapseItem itemToRemove) { if (itemToRemove != null) itemToRemove.MoveLeftOne(); return itemToRemove; } public CollapseItem MoveLeftOne(object objectReference) { CollapseItem tempItem = GetItem(objectReference); if (tempItem != null) tempItem.MoveLeftOne(); return tempItem; } public void MoveHighlightedUp() { foreach (CollapseItem item in this.mHighlightedItems) { MoveItemUp(item); } } public void MoveHighlightedDown() { foreach (CollapseItem item in this.mHighlightedItems) { MoveItemDown(item); } } #region remove item methods /// <summary> /// Detaches the item from the CollapseListBox. /// </summary> /// <remarks> /// This method will keep all children of the detached item in tact so that the item can simply /// be reattached again. /// </remarks> /// <param name="itemToRemove"></param> /// <returns></returns> public CollapseItem DetachItem(string itemToRemove) { CollapseItem tempItem = GetItemByName(itemToRemove); if (tempItem.parentItem != null) { tempItem.parentItem.mItems.Remove(tempItem); tempItem.parentItem.FixCollapseIcon(); } else this.Items.Remove(tempItem); int numOfCollapsedItems = GetNumCollapsed(); if (mStartAt + mScaleY - 1 > numOfCollapsedItems) mStartAt = numOfCollapsedItems - (int)(mScaleY - 1); if (mStartAt < 0) mStartAt = 0; AdjustScrollSize(); return tempItem; } public CollapseItem RemoveItemAndChildren(CollapseItem itemToRemove) { if (itemToRemove != null) itemToRemove.RemoveSelfAndChildren(); int numOfCollapsedItems = GetNumCollapsed(); if (mStartAt + mScaleY - 1 > numOfCollapsedItems) mStartAt = numOfCollapsedItems - (int)(mScaleY - 1); if (mStartAt < 0) mStartAt = 0; AdjustScrollSize(); return itemToRemove; } public CollapseItem RemoveItemAndChildren(object objectToRemove) { return RemoveItemAndChildren(GetItem(objectToRemove)); } public List<CollapseItem> RemoveHighlightedItems() { List<CollapseItem> arrayToReturn = new List<CollapseItem>(); foreach (CollapseItem ci in mHighlightedItems) arrayToReturn.Add(ci); for (int i = mHighlightedItems.Count - 1; i > -1; i--) { mHighlightedItems[i].RemoveSelf(); } int numOfCollapsedItems = GetNumCollapsed(); if (mStartAt + mScaleY - 1 > numOfCollapsedItems) mStartAt = numOfCollapsedItems - (int)(mScaleY - 1); if (mStartAt < 0) mStartAt = 0; AdjustScrollSize(); this.HighlightItem(null, false); return arrayToReturn; } public List<CollapseItem> RemoveHighlightedItemsAndChildren() { List<CollapseItem> arrayToReturn = new List<CollapseItem>(); foreach (CollapseItem ci in mHighlightedItems) arrayToReturn.Add(ci); for (int i = mHighlightedItems.Count - 1; i > -1; i--) { mHighlightedItems[i].RemoveSelfAndChildren(); } int numOfCollapsedItems = GetNumCollapsed(); if (mStartAt + mScaleY - 1 > numOfCollapsedItems) mStartAt = numOfCollapsedItems - (int)(mScaleY - 1); if (mStartAt < 0) mStartAt = 0; AdjustScrollSize(); return arrayToReturn; } #endregion #endregion #endregion } }
// Calendar.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Xml; using System.IO; using Layout; using System.Collections.Generic; namespace Timeline { /// <summary> /// This class is used to store information about the data used to build the calendar /// /// It will allow /// * A traditional calendar /// * A fantasy calendar /// * A relative calendar (i.e., plot flow) /// </summary> public class Calendar { #region constant public enum calendertype { Gregorian, Plot }; #endregion private int nNumberOfZoomOutPanels; private List<holiday> holidays; public List<holiday> Holidays { get {return holidays;} set {holidays = value;} } /// <summary> /// Also known as "Number of Months" /// </summary> public int NumberOfZoomOutPanels { get {return nNumberOfZoomOutPanels;} set {nNumberOfZoomOutPanels = value;} } private string mMonthLabel; /// <summary> /// Used on the add date pick screen to give a label to custom calendars /// </summary> public string MonthLabel { get {return mMonthLabel;} set {mMonthLabel = value;} } private string mDayLabel; /// <summary> /// Used on the add date pick screen to give a label to custom calendars /// </summary> public string DayLabel { get {return mDayLabel;} set {mDayLabel = value;} } private string mYearLabel; /// <summary> /// Used on the add date pick screen to give a label to custom calendars /// </summary> public string YearLabel { get {return mYearLabel;} set {mYearLabel = value;} } private bool mHasYears; public bool HasYears { get {return mHasYears;} set {mHasYears = value;} } private List<string> mZoomOutDetails; /// <summary> /// "Months" /// </summary> public List<string> ZoomOutDetails { get {return mZoomOutDetails;} set {mZoomOutDetails = value;} } private List<int> mZoomInPanels; /// <summary> /// How many days per month /// </summary> public List<int> ZoomInPanels { get {return mZoomInPanels;} set {mZoomInPanels = value;} } private List<int> mZoomInPanelRules; /// <summary> /// This array stores special codes relating to whether the /// "months" have any special rules (like leap days) /// /// -1 = No Rule /// Greater than or equal to zero is how many days in a Leap year /// </summary> public List<int> ZoomInPanelRules { get {return mZoomInPanelRules;} set {mZoomInPanelRules = value;} } private List<int> mZoomOutWidths; /// <summary> /// NOTE: WIdths don't actually do anything, I couldn't get this to work and it was not a super important idea /// </summary> public List<int> ZoomOutWidths { get {return mZoomOutWidths;} set {mZoomOutWidths = value;} } private calendertype mcalendarType; public calendertype CalendarType { get {return mcalendarType;} set { mcalendarType = value; // xml load happens in the appearancelcass } } /// <summary> /// iterates through ZoomInPanel array and looks at number of days per month /// </summary> /// <param name="nYear"></param> /// <param name="nMonth"></param> /// <returns></returns> public int GetDaysInMonth(int nYear, int nMonth) { int nValue = mZoomInPanels[nMonth-1]; bool bLeap = false; // check for leap year int nMonthCode = mZoomInPanelRules[nMonth-1]; if (nMonthCode != -1) { if (nYear % 400 == 0) bLeap = true; else if (nYear % 100 == 0) bLeap = false; else if (nYear %4 == 0) bLeap = true; else bLeap = false; if (bLeap == true) { nValue = nMonthCode; } } return nValue; } public Calendar() { ZoomInPanels = new List<int>(); ZoomInPanelRules = new List<int>(); ZoomOutWidths = new List<int>(); ZoomOutDetails = new List<string>(); } /// <summary> /// Gets the safe date from day of year. /// /// Takes daycounter (say day 3) and figures out the date from this /// </summary> /// <returns> /// The safe date from day of year. /// </returns> /// <param name='daycounter'> /// Daycounter. /// </param> public DateTime GetSafeDateFromDayOfYear (int daycounter) { int Year = 1999; int Day = 1; int Month = 1; // first find the month int totaldaysfoundsofar = 0; for (int i = 0 ; i < this.ZoomOutDetails.Count;i++) { totaldaysfoundsofar = totaldaysfoundsofar + ZoomInPanels[i]; if (daycounter <= totaldaysfoundsofar) { // we have found our month Month = i; // say 2 months. Month 1 has 3 days. Month 2 has 4 days. We are looking for 6 (which sould Day #3 of Month 2) // can't we just minus the days from MOnth 1 away and that gives us the day here? Day = daycounter; if (Month > 0) { // if we are past the first month, subject the days from all the preceding months for (int j = Month-1; j >=0; j--) { Day = Day - ZoomInPanels[j]; } } // now add +1 to month because all references expect this Month++; break; } } //TODO: add unit test for all this string finalDate = String.Format ("{0}/{1}/{2}",Day,Month,Year); //CoreUtilities.NewMessage.Show ("Date is " + finalDate + " for " + daycounter); return newGenericDate.SafeDateParse(finalDate); } /// <summary> /// reutrns the total number of days in the year /// </summary> /// <returns></returns> public int DaysTotal() { int nCount=0; foreach (int nDays in mZoomInPanels) { nCount += nDays; } return nCount; } /// <summary> /// returns the width of the box for the month /// /// NOTE: WIdths don't actually do anything, I couldn't get this to work and it was not a super important idea /// </summary> /// <param name="nMonth"></param> /// <returns></returns> public int GetWidthForMonth(int nMonth) { if (nMonth < 0) nMonth = mZoomOutWidths.Count-1; if (nMonth >= mZoomOutWidths.Count) nMonth = 0; int nWidth = mZoomOutWidths[nMonth]; return nWidth; } /* /// <summary> /// called from the appearance class if this is a plot type instead /// /// ?: How will dates be stored? /// </summary> public void SetToPlotOutline() { CalendarType = Appearance.calendertype.Plot; /* mZoomOutDetails = new string[]{"Introduction", "Rising Action", "Climax", "Conclusion"}; mZoomInPanels = new int[]{2, 5, 2, 1}; mZoomInPanelRules = new int[]{-1,-1,-1,-1}; mZoomOutWidths = new int[]{3,3,3,3}; nNumberOfZoomOutPanels = 4; MonthLabel = "Segment"; DayLabel = "Moment"; YearLabel = "None"; HasYears = false;*/ //} /// <summary> /// adds days to the timeline /// </summary> /// <param name="date"></param> /// <param name="nDays"></param> /// <returns></returns> public newGenericDate AddDays(newGenericDate date, int nDays) { // logic behind adding days // figure out if end of month // : Day > MaxDaysForMonth bool bIsMonthEnd = false; bool bIsYearEnd = false; // set new day date.Day = date.Day + nDays; if (date.Day < 1) { date.Month--; // going back a year if (date.Month < 1) { if (HasYears == true) { date.Month = ZoomOutDetails.Count; date.Year--; } } // error -handling if (date.Month <= 0) { date.Month =1 ; date.Day = 1; } else date.Day = ZoomInPanels[date.Month - 1]; } if (date.Day > ZoomInPanels[date.Month -1]) { bIsMonthEnd = true; } if (bIsMonthEnd == true) { // if month++ would exceed number of months // increment months if (date.Month + 1 > ZoomOutDetails.Count) { bIsYearEnd = true; } } if (bIsMonthEnd == true) { date.Day = 1; date.Month++; } if (bIsYearEnd == true) { if (HasYears == true) { date.Month = 1; date.Year++; } else { date.Month = date.Month -2; // set month back to current month if this type of calendar does not have years date.Day = ZoomInPanels[date.Month - 1]; } } return date; } /// <summary> /// returns the number of days to this specific dates /// </summary> /// <param name="date"></param> /// <returns></returns> public int DaysToStartingDate(newGenericDate date) { int nCount = 0; for(int i = 0 ; i < date.Month-1; i++) { nCount += mZoomInPanels[i]; } nCount+=date.Day; return nCount-1; } /// <summary> /// saves the file out. /// assumes global path has already been added to this. /// </summary> /// <param name="sFile"></param> public void SaveCalendar(string sFile) { System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(this.GetType()); TextWriter tw = new StreamWriter(sFile); x.Serialize(tw, this); tw.Close(); } public static Calendar BuildGregorianDefault() { Calendar returnCalendar = new Calendar(); returnCalendar.Holidays = new List<holiday>(); returnCalendar.Holidays.Add (new holiday(1, "Remembrance Day", new newGenericDate(1, 11, 11), "Remembrance Day")); returnCalendar.Holidays.Add (new holiday(1, "Christmas Day", new newGenericDate(1, 12, 25), "Christmas Day")); returnCalendar.NumberOfZoomOutPanels = 12; returnCalendar.HasYears = true; returnCalendar.ZoomOutDetails.Add ("Jan"); returnCalendar.ZoomOutDetails.Add ("Feb"); returnCalendar.ZoomOutDetails.Add ("Mar"); returnCalendar.ZoomOutDetails.Add ("Apr"); returnCalendar.ZoomOutDetails.Add ("May"); returnCalendar.ZoomOutDetails.Add ("June"); returnCalendar.ZoomOutDetails.Add ("July"); returnCalendar.ZoomOutDetails.Add ("Aug"); returnCalendar.ZoomOutDetails.Add ("Sep"); returnCalendar.ZoomOutDetails.Add ("Oct"); returnCalendar.ZoomOutDetails.Add ("Nov"); returnCalendar.ZoomOutDetails.Add ("Dec"); returnCalendar.ZoomInPanels.AddRange(new int[12]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}); returnCalendar.ZoomInPanelRules.AddRange(new int[12]{-1, 29, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1}); returnCalendar.ZoomOutWidths.AddRange(new int[12]{3,3,3,3,3,3,3,3,3,3,3,3}); returnCalendar.CalendarType = calendertype.Gregorian; return returnCalendar; } public static Calendar BuildPlotDefault () { Calendar returnCalendar = new Calendar (); returnCalendar.NumberOfZoomOutPanels = 4; returnCalendar.MonthLabel = "Segment"; returnCalendar.DayLabel = "Moment"; returnCalendar.YearLabel = "None"; returnCalendar.HasYears = false; returnCalendar.ZoomOutDetails.AddRange (new string[4] {"Introduction", "Rising Action", "Climax", "Conclusion"}); returnCalendar.ZoomInPanels.AddRange (new int[4]{2,5,2,1}); returnCalendar.ZoomInPanelRules.AddRange (new int[4]{-1,-1,-1,-1}); returnCalendar.ZoomOutWidths.AddRange (new int[4]{3,3,3,3}); returnCalendar.CalendarType = calendertype.Plot; return returnCalendar; } } // class }
// 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; #pragma warning disable 169 namespace ContainsGCPointers { struct NoPointers { int int1; byte byte1; char char1; } struct StillNoPointers { NoPointers noPointers1; bool bool1; } class ClassNoPointers { char char1; } struct HasPointers { string string1; } struct FieldHasPointers { HasPointers hasPointers1; } class ClassHasPointers { ClassHasPointers classHasPointers1; } class BaseClassHasPointers : ClassHasPointers { } public class ClassHasIntArray { int[] intArrayField; } public class ClassHasArrayOfClassType { ClassNoPointers[] classTypeArray; } } namespace Explicit { [StructLayout(LayoutKind.Explicit)] class Class1 { static int Stat; [FieldOffset(4)] bool Bar; [FieldOffset(10)] char Baz; } [StructLayout(LayoutKind.Explicit)] class Class2 : Class1 { [FieldOffset(0)] int Lol; [FieldOffset(20)] byte Omg; } [StructLayout(LayoutKind.Explicit, Size = 40)] class ExplicitSize : Class1 { [FieldOffset(0)] int Lol; [FieldOffset(20)] byte Omg; } [StructLayout(LayoutKind.Explicit)] public class ExplicitEmptyClass { } [StructLayout(LayoutKind.Explicit)] public struct ExplicitEmptyStruct { } } namespace Sequential { [StructLayout(LayoutKind.Sequential)] class Class1 { int MyInt; bool MyBool; char MyChar; string MyString; byte[] MyByteArray; Class1 MyClass1SelfRef; } [StructLayout(LayoutKind.Sequential)] class Class2 : Class1 { int MyInt2; } // [StructLayout(LayoutKind.Sequential)] is applied by default by the C# compiler struct Struct0 { bool b1; bool b2; bool b3; int i1; string s1; } // [StructLayout(LayoutKind.Sequential)] is applied by default by the C# compiler struct Struct1 { Struct0 MyStruct0; bool MyBool; } [StructLayout(LayoutKind.Sequential)] public class ClassDoubleBool { double double1; bool bool1; } [StructLayout(LayoutKind.Sequential)] public class ClassBoolDoubleBool { bool bool1; double double1; bool bool2; } } namespace Auto { [StructLayout(LayoutKind.Auto)] struct StructWithBool { bool MyStructBool; } [StructLayout(LayoutKind.Auto)] struct StructWithIntChar { char MyStructChar; int MyStructInt; } [StructLayout(LayoutKind.Auto)] struct StructWithChar { char MyStructChar; } class ClassContainingStructs { static int MyStaticInt; StructWithBool MyStructWithBool; bool MyBool1; char MyChar1; int MyInt; double MyDouble; long MyLong; byte[] MyByteArray; string MyString1; bool MyBool2; StructWithIntChar MyStructWithIntChar; StructWithChar MyStructWithChar; } class BaseClass7BytesRemaining { bool MyBool1; double MyDouble1; long MyLong1; byte[] MyByteArray1; string MyString1; } class BaseClass4BytesRemaining { long MyLong1; uint MyUint1; } class BaseClass3BytesRemaining { int MyInt1; string MyString1; bool MyBool1; } class OptimizePartial : BaseClass7BytesRemaining { bool OptBool; char OptChar; long NoOptLong; string NoOptString; } class Optimize7Bools : BaseClass7BytesRemaining { bool OptBool1; bool OptBool2; bool OptBool3; bool OptBool4; bool OptBool5; bool OptBool6; bool OptBool7; bool NoOptBool8; string NoOptString; } class OptimizeAlignedFields : BaseClass7BytesRemaining { bool OptBool1; bool OptBool2; bool OptBool3; bool NoOptBool4; char OptChar1; char OptChar2; string NoOptString; } class OptimizeLargestField : BaseClass4BytesRemaining { bool NoOptBool; char NoOptChar; int OptInt; string NoOptString; } class NoOptimizeMisaligned : BaseClass3BytesRemaining { char NoOptChar; int NoOptInt; string NoOptString; } class NoOptimizeCharAtSize2Alignment : BaseClass3BytesRemaining { char NoOptChar; } } namespace IsByRefLike { public ref struct ByRefLikeStruct { ByReference<object> ByRef; } public struct NotByRefLike { int X; } }
using System.ComponentModel.DataAnnotations; using Signum.React.ApiControllers; using Signum.Entities.UserAssets; using Signum.React.Files; using Signum.Engine.UserAssets; using System.IO; using Microsoft.AspNetCore.Mvc; using Signum.React.Filters; using System.Collections.ObjectModel; using Signum.React.Facades; using System.Text.Json; namespace Signum.React.UserAssets; [ValidateModelFilter] public class UserAssetController : ControllerBase { public class ParseFiltersRequest { public string queryKey; public bool canAggregate; public List<QueryFilterItem> filters; public Lite<Entity> entity; } [HttpPost("api/userAssets/parseFilters")] public List<FilterNode> ParseFilters([Required, FromBody]ParseFiltersRequest request) { var queryName = QueryLogic.ToQueryName(request.queryKey); var qd = QueryLogic.Queries.QueryDescription(queryName); var options = SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | (request.canAggregate ? SubTokensOptions.CanAggregate : 0); using (request.entity != null ? CurrentEntityConverter.SetCurrentEntity(request.entity.RetrieveAndRemember()) : null) { var result = ParseFilterInternal(request.filters, qd, options, 0).ToList(); return result; } } static List<FilterNode> ParseFilterInternal(IEnumerable<QueryFilterItem> filters, QueryDescription qd, SubTokensOptions options, int indent) { return filters.GroupWhen(filter => filter.indentation == indent).Select(gr => { if (!gr.Key.isGroup) { if (gr.Count() != 0) throw new InvalidOperationException("Unexpected childrens of condition"); var filter = gr.Key; var token = QueryUtils.Parse(filter.tokenString!, qd, options); var value = FilterValueConverter.Parse(filter.valueString, token.Type, filter.operation!.Value.IsList()); return new FilterNode { token = new QueryTokenTS(token, true), operation = filter.operation.Value, value = value, pinned = filter.pinned, dashboardBehaviour = filter.dashboardBehaviour, }; } else { var group = gr.Key; var token = group.tokenString == null ? null : QueryUtils.Parse(group.tokenString!, qd, options); var value = FilterValueConverter.Parse(group.valueString, typeof(string), false); return new FilterNode { groupOperation = group.groupOperation!.Value, token = token == null ? null : new QueryTokenTS(token, true), pinned = group.pinned, dashboardBehaviour = group.dashboardBehaviour, filters = ParseFilterInternal(gr, qd, options, indent + 1).ToList() }; } }).ToList(); } public class StringifyFiltersRequest { public string queryKey; public bool canAggregate; public List<FilterNode> filters; } [HttpPost("api/userAssets/stringifyFilters")] public List<QueryFilterItem> StringifyFilters([Required, FromBody]StringifyFiltersRequest request) { var queryName = QueryLogic.ToQueryName(request.queryKey); var qd = QueryLogic.Queries.QueryDescription(queryName); var options = SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement | (request.canAggregate ? SubTokensOptions.CanAggregate : 0); List<QueryFilterItem> result = new List<QueryFilterItem>(); foreach (var f in request.filters) { result.AddRange(ToQueryFiltersEmbedded(f, qd, options, 0)); } return result; } public static IEnumerable<QueryFilterItem> ToQueryFiltersEmbedded(FilterNode filter, QueryDescription qd, SubTokensOptions options, int ident = 0) { if (filter.groupOperation == null) { var token = QueryUtils.Parse(filter.tokenString!, qd, options); var expectedValueType = filter.operation!.Value.IsList() ? typeof(ObservableCollection<>).MakeGenericType(token.Type.Nullify()) : token.Type; var val = filter.value is JsonElement jtok ? jtok.ToObject(expectedValueType, SignumServer.JsonSerializerOptions) : filter.value; yield return new QueryFilterItem { token = new QueryTokenTS(token, true), operation = filter.operation, valueString = FilterValueConverter.ToString(val, token.Type), indentation = ident, pinned = filter.pinned, }; } else { var token = filter.tokenString == null ? null : QueryUtils.Parse(filter.tokenString, qd, options); yield return new QueryFilterItem { isGroup = true, groupOperation = filter.groupOperation, token = token == null ? null : new QueryTokenTS(token, true), indentation = ident, valueString = filter.value != null ? FilterValueConverter.ToString(filter.value, typeof(string)) : null, pinned = filter.pinned, }; foreach (var f in filter.filters) { foreach (var fe in ToQueryFiltersEmbedded(f, qd, options, ident + 1)) { yield return fe; } } } } public class QueryFilterItem { public QueryTokenTS? token; public string? tokenString; public bool isGroup; public FilterGroupOperation? groupOperation; public FilterOperation? operation; public string? valueString; public PinnedFilter pinned; public DashboardBehaviour? dashboardBehaviour; public int indentation; } public class PinnedFilter { public string label; public int? row; public int? column; public PinnedFilterActive? active; public bool? splitText; } public class FilterNode { public FilterGroupOperation? groupOperation; public string? tokenString; //For Request public QueryTokenTS? token; //For response public FilterOperation? operation; public object? value; public List<FilterNode> filters; public PinnedFilter pinned; public DashboardBehaviour? dashboardBehaviour; } public class FilterElement { } [HttpPost("api/userAssets/export")] public FileStreamResult Export([Required, FromBody]Lite<IUserAssetEntity>[] lites) { var bytes = UserAssetsExporter.ToXml(lites.RetrieveFromListOfLite().ToArray()); string typeName = lites.Select(a => a.EntityType).Distinct().SingleEx().Name; var fileName = "{0}{1}.xml".FormatWith(typeName, lites.ToString(a => a.Id.ToString(), "_")); return FilesController.GetFileStreamResult(new MemoryStream(bytes), fileName); } [HttpPost("api/userAssets/importPreview")] public UserAssetPreviewModel ImportPreview([Required, FromBody]FileUpload file) { return UserAssetsImporter.Preview(file.content); } [HttpPost("api/userAssets/import")] public void Import([Required, FromBody]FileUploadWithModel file) { UserAssetsImporter.Import(file.file.content, file.model); } public class FileUpload { public string fileName; public byte[] content; } public class FileUploadWithModel { public FileUpload file; public UserAssetPreviewModel model; } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.IO; namespace NUnit.Framework.Constraints { /// <summary> /// The EqualConstraintResult class is tailored for formatting /// and displaying the result of an EqualConstraint. /// </summary> public class EqualConstraintResult : ConstraintResult { private readonly object expectedValue; private readonly Tolerance tolerance; private readonly bool caseInsensitive; private readonly bool clipStrings; private readonly IList<NUnitEqualityComparer.FailurePoint> failurePoints; #region Message Strings private static readonly string StringsDiffer_1 = "String lengths are both {0}. Strings differ at index {1}."; private static readonly string StringsDiffer_2 = "Expected string length {0} but was {1}. Strings differ at index {2}."; private static readonly string StreamsDiffer_1 = "Stream lengths are both {0}. Streams differ at offset {1}."; private static readonly string StreamsDiffer_2 = "Expected Stream length {0} but was {1}.";// Streams differ at offset {2}."; private static readonly string CollectionType_1 = "Expected and actual are both {0}"; private static readonly string CollectionType_2 = "Expected is {0}, actual is {1}"; private static readonly string ValuesDiffer_1 = "Values differ at index {0}"; private static readonly string ValuesDiffer_2 = "Values differ at expected index {0}, actual index {1}"; #endregion /// <summary> /// Construct an EqualConstraintResult /// </summary> public EqualConstraintResult(EqualConstraint constraint, object actual, bool hasSucceeded) : base(constraint, actual, hasSucceeded) { this.expectedValue = constraint.Arguments[0]; this.tolerance = constraint.Tolerance; this.caseInsensitive = constraint.CaseInsensitive; this.clipStrings = constraint.ClipStrings; this.failurePoints = constraint.FailurePoints; } /// <summary> /// Write a failure message. Overridden to provide custom /// failure messages for EqualConstraint. /// </summary> /// <param name="writer">The MessageWriter to write to</param> public override void WriteMessageTo(MessageWriter writer) { DisplayDifferences(writer, expectedValue, ActualValue, 0); } private void DisplayDifferences(MessageWriter writer, object expected, object actual, int depth) { if (expected is string && actual is string) DisplayStringDifferences(writer, (string)expected, (string)actual); else if (expected is ICollection && actual is ICollection) DisplayCollectionDifferences(writer, (ICollection)expected, (ICollection)actual, depth); else if (expected is IEnumerable && actual is IEnumerable) DisplayEnumerableDifferences(writer, (IEnumerable)expected, (IEnumerable)actual, depth); else if (expected is Stream && actual is Stream) DisplayStreamDifferences(writer, (Stream)expected, (Stream)actual, depth); else if (tolerance != null) writer.DisplayDifferences(expected, actual, tolerance); else writer.DisplayDifferences(expected, actual); } #region DisplayStringDifferences private void DisplayStringDifferences(MessageWriter writer, string expected, string actual) { int mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, caseInsensitive); if (expected.Length == actual.Length) writer.WriteMessageLine(StringsDiffer_1, expected.Length, mismatch); else writer.WriteMessageLine(StringsDiffer_2, expected.Length, actual.Length, mismatch); writer.DisplayStringDifferences(expected, actual, mismatch, caseInsensitive, clipStrings); } #endregion #region DisplayStreamDifferences private void DisplayStreamDifferences(MessageWriter writer, Stream expected, Stream actual, int depth) { if (expected.Length == actual.Length) { long offset = failurePoints[depth].Position; writer.WriteMessageLine(StreamsDiffer_1, expected.Length, offset); } else writer.WriteMessageLine(StreamsDiffer_2, expected.Length, actual.Length); } #endregion #region DisplayCollectionDifferences /// <summary> /// Display the failure information for two collections that did not match. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected collection.</param> /// <param name="actual">The actual collection</param> /// <param name="depth">The depth of this failure in a set of nested collections</param> private void DisplayCollectionDifferences(MessageWriter writer, ICollection expected, ICollection actual, int depth) { DisplayTypesAndSizes(writer, expected, actual, depth); if (failurePoints.Count > depth) { NUnitEqualityComparer.FailurePoint failurePoint = failurePoints[depth]; DisplayFailurePoint(writer, expected, actual, failurePoint, depth); if (failurePoint.ExpectedHasData && failurePoint.ActualHasData) DisplayDifferences( writer, failurePoint.ExpectedValue, failurePoint.ActualValue, ++depth); else if (failurePoint.ActualHasData) { writer.Write(" Extra: "); writer.WriteCollectionElements(actual.Skip(failurePoint.Position), 0, 3); } else { writer.Write(" Missing: "); writer.WriteCollectionElements(expected.Skip(failurePoint.Position), 0, 3); } } } /// <summary> /// Displays a single line showing the types and sizes of the expected /// and actual collections or arrays. If both are identical, the value is /// only shown once. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected collection or array</param> /// <param name="actual">The actual collection or array</param> /// <param name="indent">The indentation level for the message line</param> private void DisplayTypesAndSizes(MessageWriter writer, IEnumerable expected, IEnumerable actual, int indent) { string sExpected = MsgUtils.GetTypeRepresentation(expected); if (expected is ICollection && !(expected is Array)) sExpected += string.Format(" with {0} elements", ((ICollection)expected).Count); string sActual = MsgUtils.GetTypeRepresentation(actual); if (actual is ICollection && !(actual is Array)) sActual += string.Format(" with {0} elements", ((ICollection)actual).Count); if (sExpected == sActual) writer.WriteMessageLine(indent, CollectionType_1, sExpected); else writer.WriteMessageLine(indent, CollectionType_2, sExpected, sActual); } /// <summary> /// Displays a single line showing the point in the expected and actual /// arrays at which the comparison failed. If the arrays have different /// structures or dimensions, both values are shown. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected array</param> /// <param name="actual">The actual array</param> /// <param name="failurePoint">Index of the failure point in the underlying collections</param> /// <param name="indent">The indentation level for the message line</param> private void DisplayFailurePoint(MessageWriter writer, IEnumerable expected, IEnumerable actual, NUnitEqualityComparer.FailurePoint failurePoint, int indent) { Array expectedArray = expected as Array; Array actualArray = actual as Array; int expectedRank = expectedArray != null ? expectedArray.Rank : 1; int actualRank = actualArray != null ? actualArray.Rank : 1; bool useOneIndex = expectedRank == actualRank; if (expectedArray != null && actualArray != null) for (int r = 1; r < expectedRank && useOneIndex; r++) if (expectedArray.GetLength(r) != actualArray.GetLength(r)) useOneIndex = false; int[] expectedIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(expected, failurePoint.Position); if (useOneIndex) { writer.WriteMessageLine(indent, ValuesDiffer_1, MsgUtils.GetArrayIndicesAsString(expectedIndices)); } else { int[] actualIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(actual, failurePoint.Position); writer.WriteMessageLine(indent, ValuesDiffer_2, MsgUtils.GetArrayIndicesAsString(expectedIndices), MsgUtils.GetArrayIndicesAsString(actualIndices)); } } private static object GetValueFromCollection(ICollection collection, int index) { Array array = collection as Array; if (array != null && array.Rank > 1) return array.GetValue(MsgUtils.GetArrayIndicesFromCollectionIndex(array, index)); if (collection is IList) return ((IList)collection)[index]; foreach (object obj in collection) if (--index < 0) return obj; return null; } #endregion #region DisplayEnumerableDifferences /// <summary> /// Display the failure information for two IEnumerables that did not match. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected enumeration.</param> /// <param name="actual">The actual enumeration</param> /// <param name="depth">The depth of this failure in a set of nested collections</param> private void DisplayEnumerableDifferences(MessageWriter writer, IEnumerable expected, IEnumerable actual, int depth) { DisplayTypesAndSizes(writer, expected, actual, depth); if (failurePoints.Count > depth) { NUnitEqualityComparer.FailurePoint failurePoint = failurePoints[depth]; DisplayFailurePoint(writer, expected, actual, failurePoint, depth); if (failurePoint.ExpectedHasData && failurePoint.ActualHasData) DisplayDifferences( writer, failurePoint.ExpectedValue, failurePoint.ActualValue, ++depth); else if (failurePoint.ActualHasData) { writer.Write($" Extra: < {MsgUtils.FormatValue(failurePoint.ActualValue)}, ... >"); } else { writer.Write($" Missing: < {MsgUtils.FormatValue(failurePoint.ExpectedValue)}, ... >"); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using Xunit; namespace System.Globalization.Tests { public class CultureInfoAll { [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoke to Win32 function public void TestAllCultures() { Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed"); Assert.All(cultures, Validate); } private void Validate(CultureInfo ci) { Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME)); // si-LK has some special case when running on Win7 so we just ignore this one if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase)) { Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName); } // zh-Hans and zh-Hant has different behavior on different platform Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase); Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME)); ValidateDTFI(ci); ValidateNFI(ci); ValidateRegionInfo(ci); } private void ValidateDTFI(CultureInfo ci) { DateTimeFormatInfo dtfi = ci.DateTimeFormat; Calendar cal = dtfi.Calendar; int calId = GetCalendarId(cal); Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames); Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames); Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames); Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames); Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase); Assert.Equal(calId, GetDefaultcalendar(ci)); Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK))); Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR)); Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true)); Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern); Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern); Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern); string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0]; string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE)); string longTimePattern1 = GetTimeFormats(ci, 0)[0]; string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT)); string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1; string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2; Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 }); Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 }); Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 }); Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) }); Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) }); Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) }); int eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); eraNameIndex = 1; Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase)); } private void ValidateNFI(CultureInfo ci) { NumberFormatInfo nfi = ci.NumberFormat; Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes); Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol); } private void ValidateRegionInfo(CultureInfo ci) { if (ci.Name.Length == 0) // no region for invariant return; RegionInfo ri = new RegionInfo(ci.Name); Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol); Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName); Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric); Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol); Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase); Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase); } private int[] ConvertWin32GroupString(String win32Str) { // None of these cases make any sense if (win32Str == null || win32Str.Length == 0) { return (new int[] { 3 }); } if (win32Str[0] == '0') { return (new int[] { 0 }); } // Since its in n;n;n;n;n format, we can always get the length quickly int[] values; if (win32Str[win32Str.Length - 1] == '0') { // Trailing 0 gets dropped. 1;0 -> 1 values = new int[(win32Str.Length / 2)]; } else { // Need extra space for trailing zero 1 -> 1;0 values = new int[(win32Str.Length / 2) + 2]; values[values.Length - 1] = 0; } int i; int j; for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++) { // Note that this # shouldn't ever be zero, 'cause 0 is only at end // But we'll test because its registry that could be anything if (win32Str[i] < '1' || win32Str[i] > '9') return new int[] { 3 }; values[j] = (int)(win32Str[i] - '0'); } return (values); } private List<string> _timePatterns; private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam) { _timePatterns.Add(ReescapeWin32String(lpTimeFormatString)); return true; } private string[] GetTimeFormats(CultureInfo ci, uint flags) { _timePatterns = new List<string>(); Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), String.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags)); return _timePatterns.ToArray(); } internal String ReescapeWin32String(String str) { // If we don't have data, then don't try anything if (str == null) return null; StringBuilder result = null; bool inQuote = false; for (int i = 0; i < str.Length; i++) { // Look for quote if (str[i] == '\'') { // Already in quote? if (inQuote) { // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote? if (i + 1 < str.Length && str[i + 1] == '\'') { // Found another ', so we have ''. Need to add \' instead. // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append a \' and keep going (so we don't turn off quote mode) result.Append("\\'"); i++; continue; } // Turning off quote mode, fall through to add it inQuote = false; } else { // Found beginning quote, fall through to add it inQuote = true; } } // Is there a single \ character? else if (str[i] == '\\') { // Found a \, need to change it to \\ // 1st make sure we have our stringbuilder if (result == null) result = new StringBuilder(str, 0, i, str.Length * 2); // Append our \\ to the string & continue result.Append("\\\\"); continue; } // If we have a builder we need to add our character if (result != null) result.Append(str[i]); } // Unchanged string? , just return input string if (result == null) return str; // String changed, need to use the builder return result.ToString(); } private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[13]; for (uint i = 0; i < 13; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i, false); } return names; } private int ConvertFirstDayOfWeekMonToSun(int iTemp) { // Convert Mon-Sun to Sun-Sat format iTemp++; if (iTemp > 6) { // Wrap Sunday and convert invalid data to Sunday iTemp = 0; } return iTemp; } private string[] GetDayNames(CultureInfo ci, int calendar, uint calType) { string[] names = new string[7]; for (uint i = 1; i < 7; i++) { names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true); } names[0] = GetCalendarInfo(ci, calendar, calType + 6, true); return names; } private int GetCalendarId(Calendar cal) { int calId = 0; if (cal is System.Globalization.GregorianCalendar) { calId = (int)(cal as GregorianCalendar).CalendarType; } else if (cal is System.Globalization.JapaneseCalendar) { calId = CAL_JAPAN; } else if (cal is System.Globalization.TaiwanCalendar) { calId = CAL_TAIWAN; } else if (cal is System.Globalization.KoreanCalendar) { calId = CAL_KOREA; } else if (cal is System.Globalization.HijriCalendar) { calId = CAL_HIJRI; } else if (cal is System.Globalization.ThaiBuddhistCalendar) { calId = CAL_THAI; } else if (cal is System.Globalization.HebrewCalendar) { calId = CAL_HEBREW; } else if (cal is System.Globalization.UmAlQuraCalendar) { calId = CAL_UMALQURA; } else if (cal is System.Globalization.PersianCalendar) { calId = CAL_PERSIAN; } else { throw new KeyNotFoundException(String.Format("Got a calendar {0} which we cannot map its Id", cal)); } return calId; } internal bool EnumLocales(string name, uint dwFlags, IntPtr param) { CultureInfo ci = new CultureInfo(name); if (!ci.IsNeutralCulture) cultures.Add(ci); return true; } private string GetLocaleInfo(CultureInfo ci, uint lctype) { Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, String.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci)); return sb.ToString(); } private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail) { if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0) { Assert.False(throwInFail, String.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar)); return ""; } return ReescapeWin32String(sb.ToString()); } private List<int> _optionalCals = new List<int>(); private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _optionalCals.Add(calendar); return true; } private int[] GetOptionalCalendars(CultureInfo ci) { _optionalCals = new List<int>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed."); return _optionalCals.ToArray(); } private List<string> _calPatterns; private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam) { _calPatterns.Add(ReescapeWin32String(lpCalendarInfoString)); return true; } private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType) { _calPatterns = new List<string>(); Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo."); return _calPatterns.ToArray(); } private int GetDefaultcalendar(CultureInfo ci) { int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE); if (calId != 0) return calId; int[] cals = GetOptionalCalendars(ci); Assert.True(cals.Length > 0); return cals[0]; } private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType) { int data = 0; Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, String.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType)); return data; } internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param); internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam); internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam); internal static StringBuilder sb = new StringBuilder(400); internal static List<CultureInfo> cultures = new List<CultureInfo>(); internal const uint LOCALE_WINDOWS = 0x00000001; internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072; internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073; internal const uint LOCALE_SPARENT = 0x0000006d; internal const uint LOCALE_SISO639LANGNAME = 0x00000059; internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM" internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM" internal const uint LOCALE_ICALENDARTYPE = 0x00001009; internal const uint LOCALE_RETURN_NUMBER = 0x20000000; internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D; internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; internal const uint LOCALE_SLONGDATE = 0x00000020; internal const uint LOCALE_STIMEFORMAT = 0x00001003; internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000; internal const uint LOCALE_SSHORTDATE = 0x0000001F; internal const uint LOCALE_SSHORTTIME = 0x00000079; internal const uint LOCALE_SYEARMONTH = 0x00001006; internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign internal const uint LOCALE_SDECIMAL = 0x0000000E; internal const uint LOCALE_STHOUSAND = 0x0000000F; internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017; internal const uint LOCALE_SMONDECIMALSEP = 0x00000016; internal const uint LOCALE_SCURRENCY = 0x00000014; internal const uint LOCALE_IDIGITS = 0x00000011; internal const uint LOCALE_ICURRDIGITS = 0x00000019; internal const uint LOCALE_ICURRENCY = 0x0000001B; internal const uint LOCALE_INEGCURR = 0x0000001C; internal const uint LOCALE_INEGNUMBER = 0x00001010; internal const uint LOCALE_SMONGROUPING = 0x00000018; internal const uint LOCALE_SNAN = 0x00000069; internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity internal const uint LOCALE_SGROUPING = 0x00000010; internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074; internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075; internal const uint LOCALE_SPERCENT = 0x00000076; internal const uint LOCALE_SPERMILLE = 0x00000077; internal const uint LOCALE_SPOSINFINITY = 0x0000006a; internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002; internal const uint LOCALE_IMEASURE = 0x0000000D; internal const uint LOCALE_SINTLSYMBOL = 0x00000015; internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008; internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e; internal const uint CAL_SMONTHNAME1 = 0x00000015; internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022; internal const uint CAL_ICALINTVALUE = 0x00000001; internal const uint CAL_SDAYNAME1 = 0x00000007; internal const uint CAL_SLONGDATE = 0x00000006; internal const uint CAL_SMONTHDAY = 0x00000038; internal const uint CAL_SSHORTDATE = 0x00000005; internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031; internal const uint CAL_SYEARMONTH = 0x0000002f; internal const uint CAL_SERASTRING = 0x00000004; internal const uint CAL_SABBREVERASTRING = 0x00000039; internal const uint ENUM_ALL_CALENDARS = 0xffffffff; internal const uint TIME_NOSECONDS = 0x00000002; internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4; // Taiwan Era calendar internal const int CAL_KOREA = 5; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7; // Thai calendar internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam); } }
using System; using System.Collections.Generic; using System.EnterpriseServices; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; namespace HandlesExplorer.Services { #region ENUMs internal enum NT_STATUS { STATUS_SUCCESS = 0x00000000, STATUS_BUFFER_OVERFLOW = unchecked((int)0x80000005L), STATUS_INFO_LENGTH_MISMATCH = unchecked((int)0xC0000004L) } internal enum SYSTEM_INFORMATION_CLASS { SystemBasicInformation = 0, SystemPerformanceInformation = 2, SystemTimeOfDayInformation = 3, SystemProcessInformation = 5, SystemProcessorPerformanceInformation = 8, SystemHandleInformation = 16, SystemInterruptInformation = 23, SystemExceptionInformation = 33, SystemRegistryQuotaInformation = 37, SystemLookasideInformation = 45 } internal enum OBJECT_INFORMATION_CLASS { ObjectBasicInformation = 0, ObjectNameInformation = 1, ObjectTypeInformation = 2, ObjectAllTypesInformation = 3, ObjectHandleInformation = 4 } [Flags] internal enum ProcessAccessRights { PROCESS_DUP_HANDLE = 0x00000040 } [Flags] internal enum DuplicateHandleOptions { DUPLICATE_CLOSE_SOURCE = 0x1, DUPLICATE_SAME_ACCESS = 0x2 } #endregion [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] internal sealed class SafeObjectHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeObjectHandle() : base(true) { } internal SafeObjectHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { base.SetHandle(preexistingHandle); } protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(base.handle); } } [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeProcessHandle() : base(true) { } internal SafeProcessHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { base.SetHandle(preexistingHandle); } protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(base.handle); } } #region Native Methods internal static class NativeMethods { [DllImport("ntdll.dll")] internal static extern NT_STATUS NtQuerySystemInformation( [In] SYSTEM_INFORMATION_CLASS SystemInformationClass, [In] IntPtr SystemInformation, [In] int SystemInformationLength, [Out] out int ReturnLength); [DllImport("ntdll.dll")] internal static extern NT_STATUS NtQueryObject( [In] IntPtr Handle, [In] OBJECT_INFORMATION_CLASS ObjectInformationClass, [In] IntPtr ObjectInformation, [In] int ObjectInformationLength, [Out] out int ReturnLength); [DllImport("kernel32.dll", SetLastError = true)] internal static extern SafeProcessHandle OpenProcess( [In] ProcessAccessRights dwDesiredAccess, [In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, [In] int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DuplicateHandle( [In] IntPtr hSourceProcessHandle, [In] IntPtr hSourceHandle, [In] IntPtr hTargetProcessHandle, [Out] out SafeObjectHandle lpTargetHandle, [In] int dwDesiredAccess, [In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, [In] DuplicateHandleOptions dwOptions); [DllImport("kernel32.dll")] internal static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetProcessId( [In] IntPtr Process); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle( [In] IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] internal static extern int QueryDosDevice( [In] string lpDeviceName, [Out] StringBuilder lpTargetPath, [In] int ucchMax); } #endregion [ComVisible(true), EventTrackingEnabled(true)] public class DetectOpenFiles : ServicedComponent { private static Dictionary<string, string> deviceMap; private const string networkDevicePrefix = "\\Device\\LanmanRedirector\\"; private const int MAX_PATH = 260; private enum SystemHandleType { OB_TYPE_UNKNOWN = 0, OB_TYPE_TYPE = 1, OB_TYPE_DIRECTORY, OB_TYPE_SYMBOLIC_LINK, OB_TYPE_TOKEN, OB_TYPE_PROCESS, OB_TYPE_THREAD, OB_TYPE_UNKNOWN_7, OB_TYPE_EVENT, OB_TYPE_EVENT_PAIR, OB_TYPE_MUTANT, OB_TYPE_UNKNOWN_11, OB_TYPE_SEMAPHORE, OB_TYPE_TIMER, OB_TYPE_PROFILE, OB_TYPE_WINDOW_STATION, OB_TYPE_DESKTOP, OB_TYPE_SECTION, OB_TYPE_KEY, OB_TYPE_PORT, OB_TYPE_WAITABLE_PORT, OB_TYPE_UNKNOWN_21, OB_TYPE_UNKNOWN_22, OB_TYPE_UNKNOWN_23, OB_TYPE_UNKNOWN_24, //OB_TYPE_CONTROLLER, //OB_TYPE_DEVICE, //OB_TYPE_DRIVER, OB_TYPE_IO_COMPLETION, OB_TYPE_FILE }; private const int handleTypeTokenCount = 27; private static readonly string[] handleTypeTokens = new string[] { "", "", "Directory", "SymbolicLink", "Token", "Process", "Thread", "Unknown7", "Event", "EventPair", "Mutant", "Unknown11", "Semaphore", "Timer", "Profile", "WindowStation", "Desktop", "Section", "Key", "Port", "WaitablePort", "Unknown21", "Unknown22", "Unknown23", "Unknown24", "IoCompletion", "File" }; [StructLayout(LayoutKind.Sequential)] private struct SYSTEM_HANDLE_ENTRY { public int OwnerPid; public byte ObjectType; public byte HandleFlags; public short HandleValue; public int ObjectPointer; public int AccessMask; } /// <summary> /// Gets the open files enumerator. /// </summary> /// <param name="processId">The process id.</param> /// <returns></returns> public static IEnumerator<FileSystemInfo> GetOpenFilesEnumerator(int processId) { return new OpenFiles(processId).GetEnumerator(); } private sealed class OpenFiles : IEnumerable<FileSystemInfo> { private readonly int processId; internal OpenFiles(int processId) { this.processId = processId; } #region IEnumerable<FileSystemInfo> Members public IEnumerator<FileSystemInfo> GetEnumerator() { NT_STATUS ret; int length = 0x10000; // Loop, probing for required memory. do { IntPtr ptr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // CER guarantees that the address of the allocated // memory is actually assigned to ptr if an // asynchronous exception occurs. ptr = Marshal.AllocHGlobal(length); } int returnLength; ret = NativeMethods.NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ptr, length, out returnLength); if (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH) { // Round required memory up to the nearest 64KB boundary. length = ((returnLength + 0xffff) & ~0xffff); } else if (ret == NT_STATUS.STATUS_SUCCESS) { int handleCount = Marshal.ReadInt32(ptr); int offset = sizeof(int); int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_ENTRY)); for (int i = 0; i < handleCount; i++) { SYSTEM_HANDLE_ENTRY handleEntry = (SYSTEM_HANDLE_ENTRY)Marshal.PtrToStructure((IntPtr)((int)ptr + offset), typeof(SYSTEM_HANDLE_ENTRY)); if (handleEntry.OwnerPid == processId) { IntPtr handle = (IntPtr)handleEntry.HandleValue; SystemHandleType handleType; if (GetHandleType(handle, handleEntry.OwnerPid, out handleType) && handleType == SystemHandleType.OB_TYPE_FILE) { string devicePath; if (GetFileNameFromHandle(handle, handleEntry.OwnerPid, out devicePath)) { string dosPath; if (ConvertDevicePathToDosPath(devicePath, out dosPath)) { if (File.Exists(dosPath)) { yield return new FileInfo(dosPath); } else if (Directory.Exists(dosPath)) { yield return new DirectoryInfo(dosPath); } } } } } offset += size; } } } finally { // CER guarantees that the allocated memory is freed, // if an asynchronous exception occurs. Marshal.FreeHGlobal(ptr); //sw.Flush(); //sw.Close(); } } while (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } #region Private Members private static bool GetFileNameFromHandle(IntPtr handle, int processId, out string fileName) { IntPtr currentProcess = NativeMethods.GetCurrentProcess(); bool remote = (processId != NativeMethods.GetProcessId(currentProcess)); SafeProcessHandle processHandle = null; SafeObjectHandle objectHandle = null; try { if (remote) { processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId); if (NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS)) { handle = objectHandle.DangerousGetHandle(); } } return GetFileNameFromHandle(handle, out fileName, 200); } finally { if (remote) { if (processHandle != null) { processHandle.Close(); } if (objectHandle != null) { objectHandle.Close(); } } } } private static bool GetFileNameFromHandle(IntPtr handle, out string fileName, int wait) { using (FileNameFromHandleState f = new FileNameFromHandleState(handle)) { ThreadPool.QueueUserWorkItem(new WaitCallback(GetFileNameFromHandle), f); if (f.WaitOne(wait)) { fileName = f.FileName; return f.RetValue; } else { fileName = string.Empty; return false; } } } private class FileNameFromHandleState : IDisposable { private ManualResetEvent _mr; private IntPtr _handle; private string _fileName; private bool _retValue; public IntPtr Handle { get { return _handle; } } public string FileName { get { return _fileName; } set { _fileName = value; } } public bool RetValue { get { return _retValue; } set { _retValue = value; } } public FileNameFromHandleState(IntPtr handle) { _mr = new ManualResetEvent(false); this._handle = handle; } public bool WaitOne(int wait) { return _mr.WaitOne(wait, false); } public void Set() { _mr.Set(); } #region IDisposable Members public void Dispose() { if (_mr != null) _mr.Close(); } #endregion } private static void GetFileNameFromHandle(object state) { FileNameFromHandleState s = (FileNameFromHandleState)state; string fileName; s.RetValue = GetFileNameFromHandle(s.Handle, out fileName); s.FileName = fileName; s.Set(); } private static bool GetFileNameFromHandle(IntPtr handle, out string fileName) { IntPtr ptr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { int length = 0x200; // 512 bytes RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // CER guarantees the assignment of the allocated // memory address to ptr, if an ansynchronous exception // occurs. ptr = Marshal.AllocHGlobal(length); } NT_STATUS ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length); if (ret == NT_STATUS.STATUS_BUFFER_OVERFLOW) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // CER guarantees that the previous allocation is freed, // and that the newly allocated memory address is // assigned to ptr if an asynchronous exception occurs. Marshal.FreeHGlobal(ptr); ptr = Marshal.AllocHGlobal(length); } ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length); } if (ret == NT_STATUS.STATUS_SUCCESS) { fileName = Marshal.PtrToStringUni((IntPtr)((int)ptr + 8), (length - 9) / 2); return fileName.Length != 0; } } finally { // CER guarantees that the allocated memory is freed, // if an asynchronous exception occurs. Marshal.FreeHGlobal(ptr); } fileName = string.Empty; return false; } private static bool GetHandleType(IntPtr handle, int processId, out SystemHandleType handleType) { string token = GetHandleTypeToken(handle, processId); return GetHandleTypeFromToken(token, out handleType); } private static bool GetHandleType(IntPtr handle, out SystemHandleType handleType) { string token = GetHandleTypeToken(handle); return GetHandleTypeFromToken(token, out handleType); } private static bool GetHandleTypeFromToken(string token, out SystemHandleType handleType) { for (int i = 1; i < handleTypeTokenCount; i++) { if (handleTypeTokens[i] == token) { handleType = (SystemHandleType)i; return true; } } handleType = SystemHandleType.OB_TYPE_UNKNOWN; return false; } private static string GetHandleTypeToken(IntPtr handle, int processId) { IntPtr currentProcess = NativeMethods.GetCurrentProcess(); bool remote = (processId != NativeMethods.GetProcessId(currentProcess)); SafeProcessHandle processHandle = null; SafeObjectHandle objectHandle = null; try { if (remote) { processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId); if (NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS)) { handle = objectHandle.DangerousGetHandle(); } } return GetHandleTypeToken(handle); } finally { if (remote) { if (processHandle != null) { processHandle.Close(); } if (objectHandle != null) { objectHandle.Close(); } } } } private static string GetHandleTypeToken(IntPtr handle) { int length; NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, IntPtr.Zero, 0, out length); IntPtr ptr = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { ptr = Marshal.AllocHGlobal(length); } if (NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, ptr, length, out length) == NT_STATUS.STATUS_SUCCESS) { return Marshal.PtrToStringUni((IntPtr)((int)ptr + 0x60)); } } finally { Marshal.FreeHGlobal(ptr); } return string.Empty; } private static bool ConvertDevicePathToDosPath(string devicePath, out string dosPath) { EnsureDeviceMap(); int i = devicePath.Length; while (i > 0 && (i = devicePath.LastIndexOf('\\', i - 1)) != -1) { string drive; if (deviceMap.TryGetValue(devicePath.Substring(0, i), out drive)) { dosPath = string.Concat(drive, devicePath.Substring(i)); return dosPath.Length != 0; } } dosPath = string.Empty; return false; } private static void EnsureDeviceMap() { if (deviceMap == null) { Dictionary<string, string> localDeviceMap = BuildDeviceMap(); Interlocked.CompareExchange<Dictionary<string, string>>(ref deviceMap, localDeviceMap, null); } } private static Dictionary<string, string> BuildDeviceMap() { string[] logicalDrives = Environment.GetLogicalDrives(); Dictionary<string, string> localDeviceMap = new Dictionary<string, string>(logicalDrives.Length); StringBuilder lpTargetPath = new StringBuilder(MAX_PATH); foreach (string drive in logicalDrives) { string lpDeviceName = drive.Substring(0, 2); NativeMethods.QueryDosDevice(lpDeviceName, lpTargetPath, MAX_PATH); localDeviceMap.Add(NormalizeDeviceName(lpTargetPath.ToString()), lpDeviceName); } localDeviceMap.Add(networkDevicePrefix.Substring(0, networkDevicePrefix.Length - 1), "\\"); return localDeviceMap; } private static string NormalizeDeviceName(string deviceName) { if (string.Compare(deviceName, 0, networkDevicePrefix, 0, networkDevicePrefix.Length, StringComparison.InvariantCulture) == 0) { string shareName = deviceName.Substring(deviceName.IndexOf('\\', networkDevicePrefix.Length) + 1); return string.Concat(networkDevicePrefix, shareName); } return deviceName; } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Collections.Generic.HashSet_1.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Collections.Generic { public partial class HashSet<T> : System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback, ISet<T>, ICollection<T>, IEnumerable<T>, System.Collections.IEnumerable { #region Methods and constructors public bool Add(T item) { return default(bool); } public void Clear() { } public bool Contains(T item) { return default(bool); } public void CopyTo(T[] array, int arrayIndex) { } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int arrayIndex, int count) { } public static IEqualityComparer<System.Collections.Generic.HashSet<T>> CreateSetComparer() { Contract.Ensures(Contract.Result<System.Collections.Generic.IEqualityComparer<System.Collections.Generic.HashSet<T>>>() != null); return default(IEqualityComparer<System.Collections.Generic.HashSet<T>>); } public void ExceptWith(IEnumerable<T> other) { } public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.HashSet<T>.Enumerator); } public virtual new void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public HashSet() { } public HashSet(IEnumerable<T> collection) { } public HashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer) { } protected HashSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public HashSet(IEqualityComparer<T> comparer) { } public void IntersectWith(IEnumerable<T> other) { } public bool IsProperSubsetOf(IEnumerable<T> other) { return default(bool); } public bool IsProperSupersetOf(IEnumerable<T> other) { return default(bool); } public bool IsSubsetOf(IEnumerable<T> other) { return default(bool); } public bool IsSupersetOf(IEnumerable<T> other) { return default(bool); } public virtual new void OnDeserialization(Object sender) { } public bool Overlaps(IEnumerable<T> other) { return default(bool); } public bool Remove(T item) { return default(bool); } public int RemoveWhere(Predicate<T> match) { Contract.Ensures(0 <= Contract.Result<int>()); return default(int); } public bool SetEquals(IEnumerable<T> other) { return default(bool); } public void SymmetricExceptWith(IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(IEnumerator<T>); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public void TrimExcess() { } public void UnionWith(IEnumerable<T> other) { } #endregion #region Properties and indexers public IEqualityComparer<T> Comparer { get { return default(IEqualityComparer<T>); } } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } } #endregion } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; using InWorldz.Phlox.Glue; using InWorldz.Phlox.Types; using OpenSim.Framework; using OpenMetaverse; using Nini.Config; using System.Threading; using OpenSim.Region.Framework; using OpenSim.Region.CoreModules.Capabilities; namespace InWorldz.Phlox.Engine { public delegate void WorkArrivedDelegate(); public class EngineInterface : INonSharedRegionModule, IScriptEngine, IScriptModule { public const System.Threading.ThreadPriority SUBTASK_PRIORITY = System.Threading.ThreadPriority.Lowest; /// <summary> /// Amount of time to wait for state data from the script engine before we give up /// </summary> private const int STATE_REQUEST_TIMEOUT = 10 * 1000; private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Scene _scene; ScriptLoader _scriptLoader; ExecutionScheduler _exeScheduler; MasterScheduler _masterScheduler; SupportedEventList _eventList = new SupportedEventList(); EventRouter _eventRouter; StateManager _stateManager; private IConfigSource _configSource; public IConfig _scriptConfigSource; private bool _enabled; public string Name { get { return "InWorldz.Phlox"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(Nini.Config.IConfigSource source) { _configSource = source; Preload(); } private static void PreloadMethods(Type type) { foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (method.IsAbstract) continue; if (method.ContainsGenericParameters || method.IsGenericMethod || method.IsGenericMethodDefinition) continue; if ((method.Attributes & MethodAttributes.PinvokeImpl) > 0) continue; try { System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle); } catch { } } } private static void Preload() { foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { PreloadMethods(type); } foreach (var type in Assembly.GetAssembly(typeof(InWorldz.Phlox.VM.Interpreter)).GetTypes()) { PreloadMethods(type); } } public void Close() { } private void WorkArrived() { _masterScheduler.WorkArrived(); } public void AddRegion(Scene scene) { if (ConfigSource.Configs[ScriptEngineName] == null) ConfigSource.AddConfig(ScriptEngineName); _scriptConfigSource = ConfigSource.Configs[ScriptEngineName]; _enabled = _scriptConfigSource.GetBoolean("Enabled", true); if (!_enabled) return; IWorldComm comms = scene.RequestModuleInterface<IWorldComm>(); if (comms == null) { _log.Error("[Phlox]: Script engine can not start, no worldcomm module found"); return; } comms.SetWorkArrivedDelegate(this.WorkArrived); _scene = scene; _exeScheduler = new ExecutionScheduler(this.WorkArrived, this, comms); _stateManager = new StateManager(_exeScheduler); _exeScheduler.StateManager = _stateManager; _scriptLoader = new ScriptLoader(scene.CommsManager.AssetCache, _exeScheduler, this.WorkArrived, this); _scriptLoader.StateManager = _stateManager; _masterScheduler = new MasterScheduler(_exeScheduler, _scriptLoader, _stateManager); _stateManager.MMasterScheduler = _masterScheduler; _eventRouter = new EventRouter(this); _scene.EventManager.OnRezScript += new EventManager.NewRezScript(EventManager_OnRezScript); _scene.EventManager.OnRemoveScript += new EventManager.RemoveScript(EventManager_OnRemoveScript); _scene.EventManager.OnReloadScript += new EventManager.ReloadScript(EventManager_OnReloadScript); _scene.EventManager.OnScriptReset += new EventManager.ScriptResetDelegate(EventManager_OnScriptReset); _scene.EventManager.OnGetScriptRunning += new EventManager.GetScriptRunning(EventManager_OnGetScriptRunning); _scene.EventManager.OnStartScript += new EventManager.StartScript(EventManager_OnStartScript); _scene.EventManager.OnStopScript += new EventManager.StopScript(EventManager_OnStopScript); _scene.EventManager.OnCompileScript += new EventManager.CompileScript(EventManager_OnCompileScript); _scene.EventManager.OnGroupCrossedToNewParcel += new EventManager.GroupCrossedToNewParcelDelegate(EventManager_OnGroupCrossedToNewParcel); _scene.EventManager.OnSOGOwnerGroupChanged += new EventManager.SOGOwnerGroupChangedDelegate(EventManager_OnSOGOwnerGroupChanged); _scene.EventManager.OnCrossedAvatarReady += OnCrossedAvatarReady; _scene.EventManager.OnGroupBeginInTransit += EventManager_OnGroupBeginInTransit; _scene.EventManager.OnGroupEndInTransit += EventManager_OnGroupEndInTransit; _masterScheduler.Start(); _scene.StackModuleInterface<IScriptModule>(this); Phlox.Util.Preloader.Preload(); } void EventManager_OnGroupEndInTransit(SceneObjectGroup sog, bool transitSuccess) { if (!transitSuccess) { sog.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, EnableDisableFlag.CrossingWaitEnable); } }); } } void EventManager_OnGroupBeginInTransit(SceneObjectGroup sog) { sog.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, EnableDisableFlag.CrossingWaitDisable); } }); } void EventManager_OnSOGOwnerGroupChanged(SceneObjectGroup sog, UUID oldGroup, UUID newGroup) { ILandObject parcel = _scene.LandChannel.GetLandObject(sog.RootPart.GroupPosition.X, sog.RootPart.GroupPosition.Y); bool scriptsCanRun = ScriptsCanRun(parcel, sog.RootPart); EnableDisableFlag flag = scriptsCanRun ? EnableDisableFlag.ParcelEnable : EnableDisableFlag.ParcelDisable; sog.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, flag); } }); } public bool ScriptsCanRun(ILandObject parcel, SceneObjectPart hostPart) { if (hostPart.ParentGroup.IsAttachment) { return true; } bool parcelAllowsOtherScripts = parcel != null && (parcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0; bool parcelAllowsGroupScripts = parcel != null && (parcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0; bool parcelMatchesObjectGroup = parcel != null && parcel.landData.GroupID == hostPart.GroupID; bool ownerOwnsParcel = parcel != null && parcel.landData.OwnerID == hostPart.OwnerID; if (ownerOwnsParcel || parcelAllowsOtherScripts || (parcelAllowsGroupScripts && parcelMatchesObjectGroup)) { return true; } return false; } void EventManager_OnGroupCrossedToNewParcel(SceneObjectGroup group, ILandObject oldParcel, ILandObject newParcel) { if (group.IsAttachment) { //attachment scripts always run and are unaffected by crossings return; } bool scriptsCouldRun = false; bool scriptsCanRun = false; bool oldParcelAllowedOtherScripts = oldParcel != null && (oldParcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0; bool oldParcelAllowedGroupScripts = oldParcel != null && (oldParcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0; bool oldParcelMatchesObjectGroup = oldParcel != null && oldParcel.landData.GroupID == group.GroupID; bool ownerOwnedOldParcel = oldParcel != null && oldParcel.landData.OwnerID == group.OwnerID; bool newParcelAllowsOtherScripts = newParcel != null && (newParcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0; bool newParcelAllowsGroupScripts = newParcel != null && (newParcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0; bool newParcelMatchesObjectGroup = newParcel != null && newParcel.landData.GroupID == group.GroupID; bool ownerOwnsNewParcel = newParcel != null && newParcel.landData.OwnerID == group.OwnerID; if (oldParcel == null || ownerOwnedOldParcel || oldParcelAllowedOtherScripts || (oldParcelAllowedGroupScripts && oldParcelMatchesObjectGroup)) { scriptsCouldRun = true; } if (ownerOwnsNewParcel || newParcelAllowsOtherScripts || (newParcelAllowsGroupScripts && newParcelMatchesObjectGroup)) { scriptsCanRun = true; } List<TaskInventoryItem> scripts = new List<TaskInventoryItem>(); if (scriptsCanRun != scriptsCouldRun) { EnableDisableFlag flag = scriptsCanRun ? EnableDisableFlag.ParcelEnable : EnableDisableFlag.ParcelDisable; if (flag == EnableDisableFlag.ParcelDisable) { //do not parcel disable any scripted group that is holding avatar controls if (group.HasAvatarControls) { return; } } group.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem script in part.Inventory.GetScripts()) { _exeScheduler.ChangeEnabledStatus(script.ItemID, flag); } }); } } void EventManager_OnCompileScript(string scriptSource, OpenSim.Region.Framework.Interfaces.ICompilationListener compListener) { //compile script to get error output only, do not start a run CompilerFrontend frontEnd = new CompilerFrontend(new CompilationListenerAdaptor(compListener), "."); frontEnd.Compile(scriptSource); } void EventManager_OnStopScript(uint localID, OpenMetaverse.UUID itemID) { _exeScheduler.ChangeEnabledStatus(itemID, EnableDisableFlag.GeneralDisable); } void EventManager_OnStartScript(uint localID, OpenMetaverse.UUID itemID) { _exeScheduler.ChangeEnabledStatus(itemID, EnableDisableFlag.GeneralEnable); } void EventManager_OnGetScriptRunning(OpenSim.Framework.IClientAPI controllingClient, OpenMetaverse.UUID objectID, OpenMetaverse.UUID itemID) { _exeScheduler.PostScriptInfoRequest(new ScriptInfoRequest(itemID, ScriptInfoRequest.Type.ScriptRunningRequest, delegate(ScriptInfoRequest req) { IEventQueue eq = World.RequestModuleInterface<IEventQueue>(); if (eq != null) { eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, req.IsRunning, false), controllingClient.AgentId); } } )); } void EventManager_OnScriptReset(uint localID, OpenMetaverse.UUID itemID) { _exeScheduler.ResetScript(itemID); } void EventManager_OnRemoveScript(uint localID, OpenMetaverse.UUID itemID, SceneObjectPart part, EventManager.ScriptPostUnloadDelegate callback, bool allowedDrop, bool fireEvents, ReplaceItemArgs replaceArgs) { _scriptLoader.PostLoadUnloadRequest( new LoadUnloadRequest { RequestType = LoadUnloadRequest.LUType.Unload, LocalId = localID, PostUnloadCallback = callback, CallbackParams = new LoadUnloadRequest.UnloadCallbackParams { Prim = part, ItemId = itemID, AllowedDrop = allowedDrop, FireEvents = fireEvents, ReplaceArgs = replaceArgs, } }); } void EventManager_OnRezScript(uint localID, TaskInventoryItem item, string script, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener) { //try to find the prim associated with the localid SceneObjectPart part = _scene.SceneGraph.GetPrimByLocalId(localID); if (part == null) { _log.ErrorFormat("[Phlox]: Unable to load script {0}. Prim {1} no longer exists", item.ItemID, localID); return; } ILandObject parcel = _scene.LandChannel.GetLandObject(part.GroupPosition.X, part.GroupPosition.Y); bool startDisabled = !ScriptsCanRun(parcel, part); _scriptLoader.PostLoadUnloadRequest(new LoadUnloadRequest { RequestType = LoadUnloadRequest.LUType.Load, OldItemId = item.OldItemID, PostOnRez = (startFlags & ScriptStartFlags.PostOnRez) != 0, ChangedRegionStart = (startFlags & ScriptStartFlags.ChangedRegionStart) != 0, StartParam = startParam, StateSource = (OpenSim.Region.Framework.ScriptStateSource)stateSource, Listener = listener, StartLocalDisabled = startDisabled, StartGlobalDisabled = (startFlags & ScriptStartFlags.StartGloballyDisabled) != 0, FromCrossing = (startFlags & ScriptStartFlags.FromCrossing) != 0, CallbackParams = new LoadUnloadRequest.UnloadCallbackParams { Prim = part, ItemId = item.ItemID, ReplaceArgs = null, // signals that it is not used AllowedDrop = false, // not used FireEvents = false, // not used } }); } void EventManager_OnReloadScript(uint localID, OpenMetaverse.UUID itemID, string script, int? startParam, ScriptStartFlags startFlags, string engine, int stateSource, ICompilationListener listener) { //try to find the prim associated with the localid SceneObjectPart part = _scene.SceneGraph.GetPrimByLocalId(localID); if (part == null) { _log.ErrorFormat("[Phlox]: Unable to reload script {0}. Prim {1} no longer exists", itemID, localID); return; } ILandObject parcel = _scene.LandChannel.GetLandObject(part.GroupPosition.X, part.GroupPosition.Y); bool startDisabled = !ScriptsCanRun(parcel, part); _scriptLoader.PostLoadUnloadRequest(new LoadUnloadRequest { RequestType = LoadUnloadRequest.LUType.Reload, PostOnRez = (startFlags & ScriptStartFlags.PostOnRez) != 0, ChangedRegionStart = (startFlags & ScriptStartFlags.ChangedRegionStart) != 0, StartParam = startParam, StateSource = (OpenSim.Region.Framework.ScriptStateSource)stateSource, Listener = listener, StartLocalDisabled = startDisabled, StartGlobalDisabled = (startFlags & ScriptStartFlags.StartGloballyDisabled) != 0, CallbackParams = new LoadUnloadRequest.UnloadCallbackParams { Prim = part, ItemId = itemID, ReplaceArgs = null, // signals that it is not used AllowedDrop = false, // not used FireEvents = false, // not used } }); } public void RemoveRegion(Scene scene) { if (_masterScheduler == null) return; // happens under Phlox if disabled _masterScheduler.Stop(); } public void RegionLoaded(Scene scene) { } #region IScriptEngine Members public IScriptWorkItem QueueEventHandler(object parms) { throw new NotImplementedException(); } public OpenSim.Region.Framework.Scenes.Scene World { get { return _scene; } } public IScriptModule ScriptModule { get { return this; } } VM.DetectVariables DetectParamsToDetectVariables(OpenSim.Region.ScriptEngine.Shared.DetectParams parm) { return new VM.DetectVariables { Grab = new Vector3(), Key = parm.Key.ToString(), BotID = parm.BotID.ToString(), Group = parm.Group.ToString(), LinkNumber = parm.LinkNum, Name = parm.Name, Owner = parm.Owner.ToString(), Pos = parm.Position, Rot = parm.Rotation, Type = parm.Type, Vel = parm.Velocity, TouchBinormal = parm.TouchBinormal, TouchFace = parm.TouchFace, TouchNormal = parm.TouchNormal, TouchPos = parm.TouchPos, TouchST = parm.TouchST, TouchUV = parm.TouchUV }; } VM.DetectVariables[] DetectParamsArrayToDetectVariablesArray(OpenSim.Region.ScriptEngine.Shared.DetectParams[] parms) { if (parms == null) { return new VM.DetectVariables[0]; } VM.DetectVariables[] retVars = new VM.DetectVariables[parms.Length]; for (int i = 0; i < parms.Length; i++) { retVars[i] = this.DetectParamsToDetectVariables(parms[i]); } return retVars; } public bool PostScriptEvent(OpenMetaverse.UUID itemID, OpenSim.Region.ScriptEngine.Shared.EventParams parms) { FunctionSig eventInfo = _eventList.GetEventByName(parms.EventName); VM.DetectVariables[] detectVars = this.DetectParamsArrayToDetectVariablesArray(parms.DetectParams); VM.PostedEvent evt = new VM.PostedEvent { EventType = (SupportedEventList.Events) eventInfo.TableIndex, Args = parms.Params, DetectVars = detectVars }; evt.Normalize(); _exeScheduler.PostEvent(itemID, evt); return true; } public bool PostObjectEvent(uint localID, OpenSim.Region.ScriptEngine.Shared.EventParams parms) { SceneObjectPart part = World.SceneGraph.GetPrimByLocalId(localID); if (part != null) { //grab the local ids of all the scripts and send the event to each script IList<TaskInventoryItem> scripts = part.Inventory.GetScripts(); foreach (TaskInventoryItem script in scripts) { this.PostScriptEvent(script.ItemID, parms); } } return false; } public OpenSim.Region.ScriptEngine.Shared.DetectParams GetDetectParams(OpenMetaverse.UUID item, int number) { throw new NotImplementedException(); } public void SetMinEventDelay(OpenMetaverse.UUID itemID, double delay) { throw new NotImplementedException(); } public int GetStartParameter(OpenMetaverse.UUID itemID) { throw new NotImplementedException(); } public void SetScriptState(OpenMetaverse.UUID itemID, bool state) { EnableDisableFlag flag = state ? EnableDisableFlag.GeneralEnable : EnableDisableFlag.GeneralDisable; _exeScheduler.ChangeEnabledStatus(itemID, flag); } /// <summary> /// Should only be called by the LSL api as it directly accesses the scripts /// </summary> /// <param name="itemID"></param> /// <returns></returns> public bool GetScriptState(OpenMetaverse.UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script == null) return false; return script.ScriptState.Enabled; } public void SetState(OpenMetaverse.UUID itemID, string newState) { throw new NotImplementedException(); } public void ApiResetScript(OpenMetaverse.UUID itemID) { _exeScheduler.ResetNow(itemID); } public void ResetScript(OpenMetaverse.UUID itemID) { _exeScheduler.ResetScript(itemID); } public Nini.Config.IConfig Config { get { return _scriptConfigSource; } } public Nini.Config.IConfigSource ConfigSource { get { return _configSource; } } public string ScriptEngineName { get { return "InWorldz.Phlox"; } } public IScriptApi GetApi(OpenMetaverse.UUID itemID, string name) { throw new NotImplementedException(); } public void UpdateTouchData(uint localId, OpenSim.Region.ScriptEngine.Shared.DetectParams[] det) { SceneObjectPart part = World.SceneGraph.GetPrimByLocalId(localId); if (part != null) { //grab the local ids of all the scripts and send the event to each script IList<TaskInventoryItem> scripts = part.Inventory.GetScripts(); foreach (TaskInventoryItem script in scripts) { VM.DetectVariables[] detectVars = this.DetectParamsArrayToDetectVariablesArray(det); _exeScheduler.UpdateTouchData(script.ItemID, detectVars); } } } #endregion #region IScriptModule Members public string GetAssemblyName(OpenMetaverse.UUID itemID) { throw new NotImplementedException(); } public string GetXMLState(OpenMetaverse.UUID itemID, StopScriptReason stopScriptReason) { if (!_masterScheduler.IsRunning) { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0} master scheduler has died", itemID); return String.Empty; } StateDataRequest req = new StateDataRequest(itemID, true); req.DisableScriptReason = stopScriptReason; _exeScheduler.RequestStateData(req); bool success = req.WaitForData(STATE_REQUEST_TIMEOUT); if (req.SerializedStateData != null) { return Convert.ToBase64String(req.SerializedStateData); } else { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0}, timeout: {1}", itemID, !success); return String.Empty; } } public byte[] GetBinaryStateSnapshot(OpenMetaverse.UUID itemID, StopScriptReason stopScriptReason) { if (!_masterScheduler.IsRunning) { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0} master scheduler has died", itemID); return null; } StateDataRequest req = new StateDataRequest(itemID, true); req.DisableScriptReason = stopScriptReason; _exeScheduler.RequestStateData(req); bool success = req.WaitForData(STATE_REQUEST_TIMEOUT); if (req.SerializedStateData != null) { return req.SerializedStateData; } else { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0}, timeout: {1}", itemID, !success); return null; } } public ScriptRuntimeInformation GetScriptInformation(UUID itemId) { if (!_masterScheduler.IsRunning) { _log.ErrorFormat("[Phlox]: Unable to retrieve state data for {0} master scheduler has died", itemId); return null; } StateDataRequest req = new StateDataRequest(itemId, false); req.DisableScriptReason = StopScriptReason.None; _exeScheduler.RequestStateData(req); bool success = req.WaitForData(STATE_REQUEST_TIMEOUT); if (!success) return null; Serialization.SerializedRuntimeState state = (Serialization.SerializedRuntimeState)req.RawStateData; ScriptRuntimeInformation info = new ScriptRuntimeInformation { CurrentEvent = state.RunningEvent == null ? "none" : state.RunningEvent.EventType.ToString(), CurrentState = state.RunState.ToString() + " | GlobalEnable: " + state.Enabled + " | " + req.CurrentLocalEnableState.ToString(), MemoryUsed = state.MemInfo.MemoryUsed, TotalRuntime = state.TotalRuntime, NextWakeup = state.NextWakeup, StackFrameFunctionName = state.TopFrame == null ? "none" : state.TopFrame.FunctionInfo.Name, TimerInterval = state.TimerInterval, TimerLastScheduledOn = state.TimerLastScheduledOn }; return info; } public bool PostScriptEvent(OpenMetaverse.UUID itemID, string name, object[] args) { return this.PostScriptEvent(itemID, new OpenSim.Region.ScriptEngine.Shared.EventParams(name, args, null)); } public bool PostObjectEvent(uint localId, string name, object[] args) { return this.PostObjectEvent(localId, new OpenSim.Region.ScriptEngine.Shared.EventParams(name, args, null)); } #endregion /// <summary> /// Can only be called from inside the script run thread as it directly accesses script data /// </summary> /// <param name="itemID"></param> /// <returns></returns> public float GetTotalRuntime(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.ScriptState.TotalRuntime; } return 0.0f; } public int GetFreeMemory(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.ScriptState.MemInfo.MemoryFree; } return 0; } public int GetUsedMemory(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.ScriptState.MemInfo.MemoryUsed; } return 0; } public int GetMaxMemory() { // Same for all scripts. return VM.MemoryInfo.MAX_MEMORY; } public float GetAverageScriptTime(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script != null) { return script.GetAverageScriptTime(); } return 0.0f; } /// <summary> /// Can only be called from inside the script run thread as it directly accesses script data /// Returns the amount of free space in the event queue (0 - 1.0) /// </summary> /// <param name="itemID"></param> /// <returns></returns> public float GetEventQueueFreeSpacePercentage(UUID itemID) { VM.Interpreter script = _exeScheduler.FindScript(itemID); if (script == null) return 1.0f; if (script.ScriptState.EventQueue.Count >= VM.RuntimeState.MAX_EVENT_QUEUE_SIZE) return 0.0f; // No space else return 1.0f - (float)script.ScriptState.EventQueue.Count / VM.RuntimeState.MAX_EVENT_QUEUE_SIZE; } /// <summary> /// Sets a timer. Can only be called from inside the script run thread as it directly accesses script data /// </summary> /// <param name="itemID"></param> /// <returns></returns> public void SetTimerEvent(uint localID, UUID itemID, float sec) { _exeScheduler.SetTimer(itemID, sec); } public void SysReturn(UUID itemId, object retValue, int delay) { _exeScheduler.PostSyscallReturn(itemId, retValue, delay); } public void ChangeScriptEnabledLandStatus(SceneObjectGroup group, bool enabled) { group.ForEachPart(delegate(SceneObjectPart part) { foreach (TaskInventoryItem item in part.Inventory.GetScripts()) { if (enabled) { _exeScheduler.ChangeEnabledStatus(item.ItemID, EnableDisableFlag.ParcelEnable); } else { _exeScheduler.ChangeEnabledStatus(item.ItemID, EnableDisableFlag.ParcelDisable); } } }); } /// <summary> /// Continues scripted controls of a seated avatar after crossing /// </summary> /// <param name="satOnPart"></param> /// <param name="client"></param> public void OnCrossedAvatarReady(SceneObjectPart satPart, UUID agentId) { if (satPart == null) return; SceneObjectGroup satOnGroup = satPart.ParentGroup; List<TaskInventoryItem> allScripts = new List<TaskInventoryItem>(); if (satOnGroup != null) { satOnGroup.ForEachPart(delegate(SceneObjectPart part) { allScripts.AddRange(part.Inventory.GetScripts()); }); } foreach (TaskInventoryItem item in allScripts) { _exeScheduler.QueueCrossedAvatarReady(item.ItemID, agentId); } } public void DisableScriptTraces() { _exeScheduler.QueueCommand(new PendingCommand { CommandType = PendingCommand.PCType.StopAllTraces }); } /// <summary> /// Returns serialized compiled script instances given a set of script asset ids /// </summary> /// <param name="assetIds"></param> /// <returns></returns> public Dictionary<UUID, byte[]> GetBytecodeForAssets(IEnumerable<UUID> assetIds) { if (!_masterScheduler.IsRunning) { _log.Error("[Phlox]: Unable to retrieve bytecode data for scripts, master scheduler has died"); return new Dictionary<UUID,byte[]>(); } const int DATA_WAIT_TIMEOUT = 3000; RetrieveBytecodeRequest rbRequest = new RetrieveBytecodeRequest { ScriptIds = assetIds }; _scriptLoader.PostRetrieveByteCodeRequest(rbRequest); rbRequest.WaitForData(DATA_WAIT_TIMEOUT); return rbRequest.Bytecodes; } } }
// 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.Threading; using Xunit; public class ChangedTests { [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Changed_LastWrite_File() { using (var file = Utility.CreateTestFile()) using (var watcher = new FileSystemWatcher(".")) { watcher.Filter = Path.GetFileName(file.Path); AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; File.SetLastWriteTime(file.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccurred, "changed"); } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public static void FileSystemWatcher_Changed_LastWrite_Directory() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher(".")) { watcher.Filter = Path.GetFileName(dir.Path); AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastWriteTime(dir.Path, DateTime.Now + TimeSpan.FromSeconds(10)); Utility.ExpectEvent(eventOccurred, "changed"); } } [Fact] public static void FileSystemWatcher_Changed_Negative() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // run all scenarios together to avoid unnecessary waits, // assert information is verbose enough to trace to failure cause watcher.EnableRaisingEvents = true; // create a file using (var testFile = new TemporaryTestFile(Path.Combine(dir.Path, "file"))) using (var testDir = new TemporaryTestDirectory(Path.Combine(dir.Path, "dir"))) { // rename a file in the same directory testFile.Move(testFile.Path + "_rename"); // renaming a directory testDir.Move(testDir.Path + "_rename"); // deleting a file & directory by leaving the using block } Utility.ExpectNoEvent(eventOccurred, "changed"); } } [Fact, ActiveIssue(2279)] public static void FileSystemWatcher_Changed_WatchedFolder() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.EnableRaisingEvents = true; Directory.SetLastAccessTime(watcher.Path, DateTime.Now); Utility.ExpectEvent(eventOccurred, "changed"); } } [Fact] public static void FileSystemWatcher_Changed_NestedDirectories() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Changed, (AutoResetEvent are, TemporaryTestDirectory ttd) => { Directory.SetLastAccessTime(ttd.Path, DateTime.Now); Utility.ExpectEvent(are, "changed"); }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess); } [Fact] public static void FileSystemWatcher_Changed_FileInNestedDirectory() { Utility.TestNestedDirectoriesHelper(WatcherChangeTypes.Changed, (AutoResetEvent are, TemporaryTestDirectory ttd) => { using (var nestedFile = new TemporaryTestFile(Path.Combine(ttd.Path, "nestedFile"))) { Directory.SetLastAccessTime(nestedFile.Path, DateTime.Now); Utility.ExpectEvent(are, "changed"); } }, NotifyFilters.DirectoryName | NotifyFilters.LastAccess | NotifyFilters.FileName); } [Fact] public static void FileSystemWatcher_Changed_FileDataChange() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Attach the FSW to the existing structure watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = File.Create(Path.Combine(dir.Path, "testfile.txt"))) { watcher.EnableRaisingEvents = true; // Change the nested file and verify we get the changed event byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectEvent(eventOccurred, "file changed"); } } [Theory] [InlineData(true)] [InlineData(false)] public static void FileSystemWatcher_Changed_PreSeededNestedStructure(bool includeSubdirectories) { // Make a nested structure before the FSW is setup using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) using (var dir1 = Utility.CreateTestDirectory(Path.Combine(dir.Path, "dir1"))) using (var dir2 = Utility.CreateTestDirectory(Path.Combine(dir1.Path, "dir2"))) using (var dir3 = Utility.CreateTestDirectory(Path.Combine(dir2.Path, "dir3"))) { string filePath = Path.Combine(dir3.Path, "testfile.txt"); File.WriteAllBytes(filePath, new byte[4096]); // Attach the FSW to the existing structure AutoResetEvent eventOccurred = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.Attributes; watcher.IncludeSubdirectories = includeSubdirectories; watcher.EnableRaisingEvents = true; File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetAttributes(filePath, FileAttributes.Normal); if (includeSubdirectories) Utility.ExpectEvent(eventOccurred, "file changed"); else Utility.ExpectNoEvent(eventOccurred, "file changed"); // Restart the FSW watcher.EnableRaisingEvents = false; watcher.EnableRaisingEvents = true; File.SetAttributes(filePath, FileAttributes.ReadOnly); File.SetAttributes(filePath, FileAttributes.Normal); if (includeSubdirectories) Utility.ExpectEvent(eventOccurred, "second file change"); else Utility.ExpectNoEvent(eventOccurred, "second file change"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Changed_SymLinkFileDoesntFireEvent() { using (var dir = Utility.CreateTestDirectory()) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; using (var file = Utility.CreateTestFile(Path.GetTempFileName())) { Utility.CreateSymLink(file.Path, Path.Combine(dir.Path, "link"), false); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectNoEvent(are, "symlink'd file change"); } } [Fact, ActiveIssue(1477, PlatformID.Windows)] public static void FileSystemWatcher_Changed_SymLinkFolderDoesntFireEvent() { using (var dir = Utility.CreateTestDirectory()) using (var tempDir = Utility.CreateTestDirectory(Path.Combine(Path.GetTempPath(), "FooBar"))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent are = Utility.WatchForEvents(watcher, WatcherChangeTypes.Changed); // Setup the watcher watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; watcher.IncludeSubdirectories = true; using (var file = Utility.CreateTestFile(Path.Combine(tempDir.Path, "test"))) { // Create the symlink first Utility.CreateSymLink(tempDir.Path, Path.Combine(dir.Path, "link"), true); watcher.EnableRaisingEvents = true; // Changing the temp file should not fire an event through the symlink byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } Utility.ExpectNoEvent(are, "symlink'd file change"); } } }
// 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 Xunit; namespace System.IO.Tests { public class File_Create_str : FileSystemTest { #region Utilities public virtual FileStream Create(string path) { return File.Create(path); } #endregion #region UniversalTests [Fact] public void NullPath() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyPath() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Fact] public void NonExistentPath() { Assert.Throws<DirectoryNotFoundException>(() => Create(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); } [Fact] public void CreateCurrentDirectory() { Assert.Throws<UnauthorizedAccessException>(() => Create(".")); } [Fact] public void ValidCreation() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] public void ValidCreation_ExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [PlatformSpecific(TestPlatforms.Windows)] // Valid Windows path extended prefix, long path [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] public void ValidCreation_LongPathExtendedSyntax() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500)); Assert.StartsWith(IOInputs.ExtendedPrefix, testDir.FullName); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Equal(0, stream.Length); Assert.Equal(0, stream.Position); } } [Fact] public void CreateInParentDirectory() { string testFile = GetTestFileName(); using (FileStream stream = Create(Path.Combine(TestDirectory, "DoesntExists", "..", testFile))) { Assert.True(File.Exists(Path.Combine(TestDirectory, testFile))); } } [Fact] public void LegalSymbols() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName() + "!@#$%^&"); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); } } [Fact] public void InvalidDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName(), GetTestFileName()); Assert.Throws<DirectoryNotFoundException>(() => Create(testFile)); } [Fact] public void FileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (FileStream stream = Create(testFile)) { Assert.True(File.Exists(testFile)); Assert.Throws<IOException>(() => Create(testFile)); } } [Fact] public void FileAlreadyExists() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] public void OverwriteReadOnly() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); Create(testFile).Dispose(); Assert.True(File.Exists(testFile)); } [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/8655")] public void LongPathSegment() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); // Long path should throw PathTooLongException on Desktop and IOException // elsewhere. if (PlatformDetection.IsFullFramework) { Assert.Throws<PathTooLongException>( () => Create(Path.Combine(testDir.FullName, new string('a', 300)))); } else { Assert.Throws<IOException>( () => Create(Path.Combine(testDir.FullName, new string('a', 300)))); } //TODO #645: File creation does not yet have long path support on Unix or Windows //using (Create(Path.Combine(testDir.FullName, new string('k', 257)))) //{ // Assert.True(File.Exists(Path.Combine(testDir.FullName, new string('k', 257)))); //} } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(CaseSensitivePlatforms)] public void CaseSensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (File.Create(testFile + "AAAA")) using (File.Create(testFile + "aAAa")) { Assert.False(File.Exists(testFile + "AaAa")); Assert.True(File.Exists(testFile + "AAAA")); Assert.True(File.Exists(testFile + "aAAa")); Assert.Equal(2, Directory.GetFiles(testDir.FullName).Length); } Assert.Throws<DirectoryNotFoundException>(() => File.Create(testFile.ToLowerInvariant())); } [Fact] [PlatformSpecific(CaseInsensitivePlatforms)] public void CaseInsensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); File.Create(testFile + "AAAA").Dispose(); File.Create(testFile.ToLowerInvariant() + "aAAa").Dispose(); Assert.Equal(1, Directory.GetFiles(testDir.FullName).Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with wildcard characters on Windows public void WindowsWildCharacterPath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "dls;d", "442349-0", "v443094(*)(+*$#$*", new string(Path.DirectorySeparatorChar, 3)))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "Test*t"))); Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t"))); } [Theory, InlineData(" "), InlineData(" "), InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\0"), InlineData("\t")] [PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with whitespace on Windows public void WindowsWhitespacePath(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void CreateNullThrows_Unix() { Assert.Throws<ArgumentException>(() => Create("\0")); } [Theory, InlineData(" "), InlineData(" "), InlineData("\n"), InlineData(">"), InlineData("<"), InlineData("\t")] [PlatformSpecific(TestPlatforms.AnyUnix)] // Valid file name with Whitespace on Unix public void UnixWhitespacePath(string path) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (Create(Path.Combine(testDir.FullName, path))) { Assert.True(File.Exists(Path.Combine(testDir.FullName, path))); } } #endregion } public class File_Create_str_i : File_Create_str { public override FileStream Create(string path) { return File.Create(path, 4096); // Default buffer size } public virtual FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize); } [Fact] public void NegativeBuffer() { Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Create(GetTestFilePath(), -100)); } } public class File_Create_str_i_fo : File_Create_str_i { public override FileStream Create(string path) { return File.Create(path, 4096, FileOptions.Asynchronous); } public override FileStream Create(string path, int bufferSize) { return File.Create(path, bufferSize, FileOptions.Asynchronous); } } }
// 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.Runtime.InteropServices; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.Security.Cryptography { [System.Runtime.InteropServices.ComVisible(true)] public class CryptoStream : Stream, IDisposable { // Member veriables private readonly Stream _stream; private readonly ICryptoTransform _Transform; private byte[] _InputBuffer; // read from _stream before _Transform private int _InputBufferIndex = 0; private int _InputBlockSize; private byte[] _OutputBuffer; // buffered output of _Transform private int _OutputBufferIndex = 0; private int _OutputBlockSize; private readonly CryptoStreamMode _transformMode; private bool _canRead = false; private bool _canWrite = false; private bool _finalBlockTransformed = false; // Constructors public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) { _stream = stream; _transformMode = mode; _Transform = transform; switch (_transformMode) { case CryptoStreamMode.Read: if (!(_stream.CanRead)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotReadable, "stream")); _canRead = true; break; case CryptoStreamMode.Write: if (!(_stream.CanWrite)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotWritable, "stream")); _canWrite = true; break; default: throw new ArgumentException(SR.Argument_InvalidValue); } InitializeBuffer(); } public override bool CanRead { [Pure] get { return _canRead; } } // For now, assume we can never seek into the middle of a cryptostream // and get the state right. This is too strict. public override bool CanSeek { [Pure] get { return false; } } public override bool CanWrite { [Pure] get { return _canWrite; } } public override long Length { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } set { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public bool HasFlushedFinalBlock { get { return _finalBlockTransformed; } } // The flush final block functionality used to be part of close, but that meant you couldn't do something like this: // MemoryStream ms = new MemoryStream(); // CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); // cs.Write(foo, 0, foo.Length); // cs.Close(); // and get the encrypted data out of ms, because the cs.Close also closed ms and the data went away. // so now do this: // cs.Write(foo, 0, foo.Length); // cs.FlushFinalBlock() // which can only be called once // byte[] ciphertext = ms.ToArray(); // cs.Close(); public void FlushFinalBlock() { if (_finalBlockTransformed) throw new NotSupportedException(SR.Cryptography_CryptoStream_FlushFinalBlockTwice); // We have to process the last block here. First, we have the final block in _InputBuffer, so transform it byte[] finalBytes = _Transform.TransformFinalBlock(_InputBuffer, 0, _InputBufferIndex); _finalBlockTransformed = true; // Now, write out anything sitting in the _OutputBuffer... if (_canWrite && _OutputBufferIndex > 0) { _stream.Write(_OutputBuffer, 0, _OutputBufferIndex); _OutputBufferIndex = 0; } // Write out finalBytes if (_canWrite) _stream.Write(finalBytes, 0, finalBytes.Length); // If the inner stream is a CryptoStream, then we want to call FlushFinalBlock on it too, otherwise just Flush. CryptoStream innerCryptoStream = _stream as CryptoStream; if (innerCryptoStream != null) { if (!innerCryptoStream.HasFlushedFinalBlock) { innerCryptoStream.FlushFinalBlock(); } } else { _stream.Flush(); } // zeroize plain text material before returning if (_InputBuffer != null) Array.Clear(_InputBuffer, 0, _InputBuffer.Length); if (_OutputBuffer != null) Array.Clear(_OutputBuffer, 0, _OutputBuffer.Length); return; } public override void Flush() { return; } public override Task FlushAsync(CancellationToken cancellationToken) { return base.FlushAsync(cancellationToken); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override int Read(byte[] buffer, int offset, int count) { // argument checking if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // read <= count bytes from the input stream, transforming as we go. // Basic idea: first we deliver any bytes we already have in the // _OutputBuffer, because we know they're good. Then, if asked to deliver // more bytes, we read & transform a block at a time until either there are // no bytes ready or we've delivered enough. int bytesToDeliver = count; int currentOutputIndex = offset; if (_OutputBufferIndex != 0) { // we have some already-transformed bytes in the output buffer if (_OutputBufferIndex <= count) { Buffer.BlockCopy(_OutputBuffer, 0, buffer, offset, _OutputBufferIndex); bytesToDeliver -= _OutputBufferIndex; currentOutputIndex += _OutputBufferIndex; _OutputBufferIndex = 0; } else { Buffer.BlockCopy(_OutputBuffer, 0, buffer, offset, count); Buffer.BlockCopy(_OutputBuffer, count, _OutputBuffer, 0, _OutputBufferIndex - count); _OutputBufferIndex -= count; return (count); } } // _finalBlockTransformed == true implies we're at the end of the input stream // if we got through the previous if block then _OutputBufferIndex = 0, meaning // we have no more transformed bytes to give // so return count-bytesToDeliver, the amount we were able to hand back // eventually, we'll just always return 0 here because there's no more to read if (_finalBlockTransformed) { return (count - bytesToDeliver); } // ok, now loop until we've delivered enough or there's nothing available int amountRead = 0; int numOutputBytes; // OK, see first if it's a multi-block transform and we can speed up things if (bytesToDeliver > _OutputBlockSize) { if (_Transform.CanTransformMultipleBlocks) { int BlocksToProcess = bytesToDeliver / _OutputBlockSize; int numWholeBlocksInBytes = BlocksToProcess * _InputBlockSize; byte[] tempInputBuffer = new byte[numWholeBlocksInBytes]; // get first the block already read Buffer.BlockCopy(_InputBuffer, 0, tempInputBuffer, 0, _InputBufferIndex); amountRead = _InputBufferIndex; amountRead += _stream.Read(tempInputBuffer, _InputBufferIndex, numWholeBlocksInBytes - _InputBufferIndex); _InputBufferIndex = 0; if (amountRead <= _InputBlockSize) { _InputBuffer = tempInputBuffer; _InputBufferIndex = amountRead; goto slow; } // Make amountRead an integral multiple of _InputBlockSize int numWholeReadBlocksInBytes = (amountRead / _InputBlockSize) * _InputBlockSize; int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes; if (numIgnoredBytes != 0) { _InputBufferIndex = numIgnoredBytes; Buffer.BlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _InputBuffer, 0, numIgnoredBytes); } byte[] tempOutputBuffer = new byte[(numWholeReadBlocksInBytes / _InputBlockSize) * _OutputBlockSize]; numOutputBytes = _Transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0); Buffer.BlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); // Now, tempInputBuffer and tempOutputBuffer are no more needed, so zeroize them to protect plain text Array.Clear(tempInputBuffer, 0, tempInputBuffer.Length); Array.Clear(tempOutputBuffer, 0, tempOutputBuffer.Length); bytesToDeliver -= numOutputBytes; currentOutputIndex += numOutputBytes; } } slow: // try to fill _InputBuffer so we have something to transform while (bytesToDeliver > 0) { while (_InputBufferIndex < _InputBlockSize) { amountRead = _stream.Read(_InputBuffer, _InputBufferIndex, _InputBlockSize - _InputBufferIndex); // first, check to see if we're at the end of the input stream if (amountRead == 0) goto ProcessFinalBlock; _InputBufferIndex += amountRead; } numOutputBytes = _Transform.TransformBlock(_InputBuffer, 0, _InputBlockSize, _OutputBuffer, 0); _InputBufferIndex = 0; if (bytesToDeliver >= numOutputBytes) { Buffer.BlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); currentOutputIndex += numOutputBytes; bytesToDeliver -= numOutputBytes; } else { Buffer.BlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _OutputBufferIndex = numOutputBytes - bytesToDeliver; Buffer.BlockCopy(_OutputBuffer, bytesToDeliver, _OutputBuffer, 0, _OutputBufferIndex); return count; } } return count; ProcessFinalBlock: // if so, then call TransformFinalBlock to get whatever is left byte[] finalBytes = _Transform.TransformFinalBlock(_InputBuffer, 0, _InputBufferIndex); // now, since _OutputBufferIndex must be 0 if we're in the while loop at this point, // reset it to be what we just got back _OutputBuffer = finalBytes; _OutputBufferIndex = finalBytes.Length; // set the fact that we've transformed the final block _finalBlockTransformed = true; // now, return either everything we just got or just what's asked for, whichever is smaller if (bytesToDeliver < _OutputBufferIndex) { Buffer.BlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _OutputBufferIndex -= bytesToDeliver; Buffer.BlockCopy(_OutputBuffer, bytesToDeliver, _OutputBuffer, 0, _OutputBufferIndex); return (count); } else { Buffer.BlockCopy(_OutputBuffer, 0, buffer, currentOutputIndex, _OutputBufferIndex); bytesToDeliver -= _OutputBufferIndex; _OutputBufferIndex = 0; return (count - bytesToDeliver); } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return base.ReadAsync(buffer, offset, count, cancellationToken); } public override void Write(byte[] buffer, int offset, int count) { if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (offset < 0) throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); Contract.EndContractBlock(); // write <= count bytes to the output stream, transforming as we go. // Basic idea: using bytes in the _InputBuffer first, make whole blocks, // transform them, and write them out. Cache any remaining bytes in the _InputBuffer. int bytesToWrite = count; int currentInputIndex = offset; // if we have some bytes in the _InputBuffer, we have to deal with those first, // so let's try to make an entire block out of it if (_InputBufferIndex > 0) { if (count >= _InputBlockSize - _InputBufferIndex) { // we have enough to transform at least a block, so fill the input block Buffer.BlockCopy(buffer, offset, _InputBuffer, _InputBufferIndex, _InputBlockSize - _InputBufferIndex); currentInputIndex += (_InputBlockSize - _InputBufferIndex); bytesToWrite -= (_InputBlockSize - _InputBufferIndex); _InputBufferIndex = _InputBlockSize; // Transform the block and write it out } else { // not enough to transform a block, so just copy the bytes into the _InputBuffer // and return Buffer.BlockCopy(buffer, offset, _InputBuffer, _InputBufferIndex, count); _InputBufferIndex += count; return; } } // If the OutputBuffer has anything in it, write it out if (_OutputBufferIndex > 0) { _stream.Write(_OutputBuffer, 0, _OutputBufferIndex); _OutputBufferIndex = 0; } // At this point, either the _InputBuffer is full, empty, or we've already returned. // If full, let's process it -- we now know the _OutputBuffer is empty int numOutputBytes; if (_InputBufferIndex == _InputBlockSize) { numOutputBytes = _Transform.TransformBlock(_InputBuffer, 0, _InputBlockSize, _OutputBuffer, 0); // write out the bytes we just got _stream.Write(_OutputBuffer, 0, numOutputBytes); // reset the _InputBuffer _InputBufferIndex = 0; } while (bytesToWrite > 0) { if (bytesToWrite >= _InputBlockSize) { // We have at least an entire block's worth to transform // If the transform will handle multiple blocks at once, do that if (_Transform.CanTransformMultipleBlocks) { int numWholeBlocks = bytesToWrite / _InputBlockSize; int numWholeBlocksInBytes = numWholeBlocks * _InputBlockSize; byte[] _tempOutputBuffer = new byte[numWholeBlocks * _OutputBlockSize]; numOutputBytes = _Transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, _tempOutputBuffer, 0); _stream.Write(_tempOutputBuffer, 0, numOutputBytes); currentInputIndex += numWholeBlocksInBytes; bytesToWrite -= numWholeBlocksInBytes; } else { // do it the slow way numOutputBytes = _Transform.TransformBlock(buffer, currentInputIndex, _InputBlockSize, _OutputBuffer, 0); _stream.Write(_OutputBuffer, 0, numOutputBytes); currentInputIndex += _InputBlockSize; bytesToWrite -= _InputBlockSize; } } else { // In this case, we don't have an entire block's worth left, so store it up in the // input buffer, which by now must be empty. Buffer.BlockCopy(buffer, currentInputIndex, _InputBuffer, 0, bytesToWrite); _InputBufferIndex += bytesToWrite; return; } } return; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return base.WriteAsync(buffer, offset, count, cancellationToken); } protected override void Dispose(bool disposing) { try { if (disposing) { if (!_finalBlockTransformed) { FlushFinalBlock(); } _stream.Dispose(); } } finally { try { // Ensure we don't try to transform the final block again if we get disposed twice // since it's null after this _finalBlockTransformed = true; // we need to clear all the internal buffers if (_InputBuffer != null) Array.Clear(_InputBuffer, 0, _InputBuffer.Length); if (_OutputBuffer != null) Array.Clear(_OutputBuffer, 0, _OutputBuffer.Length); _InputBuffer = null; _OutputBuffer = null; _canRead = false; _canWrite = false; } finally { base.Dispose(disposing); } } } // Private methods private void InitializeBuffer() { if (_Transform != null) { _InputBlockSize = _Transform.InputBlockSize; _InputBuffer = new byte[_InputBlockSize]; _OutputBlockSize = _Transform.OutputBlockSize; _OutputBuffer = new byte[_OutputBlockSize]; } } } }
//--------------------------------------------------------------------- // <copyright file="FunctionOverloadResolver.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Common.EntitySql { using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; /// <summary> /// Represents function overload resolution mechanism, used by L2E and eSQL frontends. /// </summary> internal static class FunctionOverloadResolver { /// <summary> /// Resolves <paramref name="argTypes"/> against the list of function signatures. /// </summary> /// <returns>Funciton metadata</returns> internal static EdmFunction ResolveFunctionOverloads(IList<EdmFunction> functionsMetadata, IList<TypeUsage> argTypes, bool isGroupAggregateFunction, out bool isAmbiguous) { return ResolveFunctionOverloads( functionsMetadata, argTypes, (edmFunction) => edmFunction.Parameters, (functionParameter) => functionParameter.TypeUsage, (functionParameter) => functionParameter.Mode, (argType) => TypeSemantics.FlattenType(argType), (paramType, argType) => TypeSemantics.FlattenType(paramType), (fromType, toType) => TypeSemantics.IsPromotableTo(fromType, toType), (fromType, toType) => TypeSemantics.IsStructurallyEqual(fromType, toType), isGroupAggregateFunction, out isAmbiguous); } /// <summary> /// Resolves <paramref name="argTypes"/> against the list of function signatures. /// </summary> /// <returns>Funciton metadata</returns> internal static EdmFunction ResolveFunctionOverloads(IList<EdmFunction> functionsMetadata, IList<TypeUsage> argTypes, Func<TypeUsage, IEnumerable<TypeUsage>> flattenArgumentType, Func<TypeUsage, TypeUsage, IEnumerable<TypeUsage>> flattenParameterType, Func<TypeUsage, TypeUsage, bool> isPromotableTo, Func<TypeUsage, TypeUsage, bool> isStructurallyEqual, bool isGroupAggregateFunction, out bool isAmbiguous) { return ResolveFunctionOverloads( functionsMetadata, argTypes, (edmFunction) => edmFunction.Parameters, (functionParameter) => functionParameter.TypeUsage, (functionParameter) => functionParameter.Mode, flattenArgumentType, flattenParameterType, isPromotableTo, isStructurallyEqual, isGroupAggregateFunction, out isAmbiguous); } /// <summary> /// Resolves <paramref name="argTypes"/> against the list of function signatures. /// </summary> /// <param name="getSignatureParams">function formal signature getter</param> /// <param name="getParameterTypeUsage">TypeUsage getter for a signature param</param> /// <param name="getParameterMode">ParameterMode getter for a signature param</param> /// <returns>Funciton metadata</returns> internal static TFunctionMetadata ResolveFunctionOverloads<TFunctionMetadata, TFunctionParameterMetadata>( IList<TFunctionMetadata> functionsMetadata, IList<TypeUsage> argTypes, Func<TFunctionMetadata, IList<TFunctionParameterMetadata>> getSignatureParams, Func<TFunctionParameterMetadata, TypeUsage> getParameterTypeUsage, Func<TFunctionParameterMetadata, ParameterMode> getParameterMode, Func<TypeUsage, IEnumerable<TypeUsage>> flattenArgumentType, Func<TypeUsage, TypeUsage, IEnumerable<TypeUsage>> flattenParameterType, Func<TypeUsage, TypeUsage, bool> isPromotableTo, Func<TypeUsage, TypeUsage, bool> isStructurallyEqual, bool isGroupAggregateFunction, out bool isAmbiguous) where TFunctionMetadata : class { // // Flatten argument list // List<TypeUsage> argTypesFlat = new List<TypeUsage>(argTypes.Count); foreach (TypeUsage argType in argTypes) { argTypesFlat.AddRange(flattenArgumentType(argType)); } // // Find a candidate overload with the best total rank, remember the candidate and its composite rank. // TFunctionMetadata bestCandidate = null; isAmbiguous = false; List<int[]> ranks = new List<int[]>(functionsMetadata.Count); int[] bestCandidateRank = null; for (int i = 0, maxTotalRank = int.MinValue; i < functionsMetadata.Count; i++) { int totalRank; int[] rank; if (TryRankFunctionParameters(argTypes, argTypesFlat, getSignatureParams(functionsMetadata[i]), getParameterTypeUsage, getParameterMode, flattenParameterType, isPromotableTo, isStructurallyEqual, isGroupAggregateFunction, out totalRank, out rank)) { if (totalRank == maxTotalRank) { isAmbiguous = true; } else if (totalRank > maxTotalRank) { isAmbiguous = false; maxTotalRank = totalRank; bestCandidate = functionsMetadata[i]; bestCandidateRank = rank; } Debug.Assert(argTypesFlat.Count == rank.Length, "argTypesFlat.Count == rank.Length"); ranks.Add(rank); } } // // If there is a best candidate, check it for ambiguity against composite ranks of other candidates // if (bestCandidate != null && !isAmbiguous && argTypesFlat.Count > 1 && // best candidate may be ambiguous only in the case of 2 or more arguments ranks.Count > 1) { Debug.Assert(bestCandidateRank != null); // // Search collection of composite ranks to see if there is an overload that would render the best candidate ambiguous // isAmbiguous = ranks.Any(rank => { Debug.Assert(rank.Length == bestCandidateRank.Length, "composite ranks have different number of elements"); if (!Object.ReferenceEquals(bestCandidateRank, rank)) // do not compare best cadnidate against itself { // All individual ranks of the best candidate must equal or better than the ranks of all other candidates, // otherwise we consider it ambigous, even though it has an unambigously best total rank. for (int i = 0; i < rank.Length; ++i) { if (bestCandidateRank[i] < rank[i]) { return true; } } } return false; }); } return isAmbiguous ? null : bestCandidate; } /// <summary> /// Check promotability, returns true if argument list is promotable to the overload and overload was successfully ranked, otherwise false. /// Ranks the overload parameter types against the argument list. /// </summary> /// <param name="argumentList">list of argument types</param> /// <param name="flatArgumentList">flattened list of argument types</param> /// <param name="overloadParamList1">list of overload parameter types</param> /// <param name="getParameterTypeUsage">TypeUsage getter for the overload parameters</param> /// <param name="getParameterMode">ParameterMode getter for the overload parameters</param> /// <param name="totalRank">returns total promotion rank of the overload, 0 if no arguments</param> /// <param name="parameterRanks">returns individual promotion ranks of the overload parameters, empty array if no arguments</param> private static bool TryRankFunctionParameters<TFunctionParameterMetadata>(IList<TypeUsage> argumentList, IList<TypeUsage> flatArgumentList, IList<TFunctionParameterMetadata> overloadParamList, Func<TFunctionParameterMetadata, TypeUsage> getParameterTypeUsage, Func<TFunctionParameterMetadata, ParameterMode> getParameterMode, Func<TypeUsage, TypeUsage, IEnumerable<TypeUsage>> flattenParameterType, Func<TypeUsage, TypeUsage, bool> isPromotableTo, Func<TypeUsage, TypeUsage, bool> isStructurallyEqual, bool isGroupAggregateFunction, out int totalRank, out int[] parameterRanks) { totalRank = 0; parameterRanks = null; if (argumentList.Count != overloadParamList.Count) { return false; } // // Check promotability and flatten the parameter types // List<TypeUsage> flatOverloadParamList = new List<TypeUsage>(flatArgumentList.Count); for (int i = 0; i < overloadParamList.Count; ++i) { TypeUsage argumentType = argumentList[i]; TypeUsage parameterType = getParameterTypeUsage(overloadParamList[i]); // // Parameter mode must match. // ParameterMode parameterMode = getParameterMode(overloadParamList[i]); if (parameterMode != ParameterMode.In && parameterMode != ParameterMode.InOut) { return false; } // // If function being ranked is a group aggregate, consider the element type. // if (isGroupAggregateFunction) { if (!TypeSemantics.IsCollectionType(parameterType)) { // // Even though it is the job of metadata to ensure that the provider manifest is consistent. // Ensure that if a function is marked as aggregate, then the argument type must be of collection{GivenType}. // throw EntityUtil.EntitySqlError(Strings.InvalidArgumentTypeForAggregateFunction); } parameterType = TypeHelpers.GetElementTypeUsage(parameterType); } // // If argument is not promotable - reject the overload. // if (!isPromotableTo(argumentType, parameterType)) { return false; } // // Flatten the parameter type. // flatOverloadParamList.AddRange(flattenParameterType(parameterType, argumentType)); } Debug.Assert(flatArgumentList.Count == flatOverloadParamList.Count, "flatArgumentList.Count == flatOverloadParamList.Count"); // // Rank argument promotions // parameterRanks = new int[flatOverloadParamList.Count]; for (int i = 0; i < parameterRanks.Length; ++i) { int rank = GetPromotionRank(flatArgumentList[i], flatOverloadParamList[i], isPromotableTo, isStructurallyEqual); totalRank += rank; parameterRanks[i] = rank; } return true; } /// <summary> /// Ranks the <paramref name="fromType"/> -> <paramref name="toType"/> promotion. /// Range of values: 0 to negative infinity, with 0 as the best rank (promotion to self). /// <paramref name="fromType"/> must be promotable to <paramref name="toType"/>, otherwise internal error is thrown. /// </summary> private static int GetPromotionRank(TypeUsage fromType, TypeUsage toType, Func<TypeUsage, TypeUsage, bool> isPromotableTo, Func<TypeUsage, TypeUsage, bool> isStructurallyEqual) { // // Only promotable types are allowed at this point. // Debug.Assert(isPromotableTo(fromType, toType), "isPromotableTo(fromType, toType)"); // // If both types are the same return rank 0 - the best match. // if (isStructurallyEqual(fromType, toType)) { return 0; } // // In the case of eSQL untyped null will float up to the point of isStructurallyEqual(...) above. // Below it eveything should be normal. // Debug.Assert(fromType != null, "fromType != null"); Debug.Assert(toType != null, "toType != null"); // // Handle primitive types // PrimitiveType primitiveFromType = fromType.EdmType as PrimitiveType; PrimitiveType primitiveToType = toType.EdmType as PrimitiveType; if (primitiveFromType != null && primitiveToType != null) { if (Helper.AreSameSpatialUnionType(primitiveFromType, primitiveToType)) { return 0; } IList<PrimitiveType> promotions = EdmProviderManifest.Instance.GetPromotionTypes(primitiveFromType); int promotionIndex = promotions.IndexOf(primitiveToType); if (promotionIndex < 0) { throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.FailedToGeneratePromotionRank, 1); } return -promotionIndex; } // // Handle entity/relship types // EntityTypeBase entityBaseFromType = fromType.EdmType as EntityTypeBase; EntityTypeBase entityBaseToType = toType.EdmType as EntityTypeBase; if (entityBaseFromType != null && entityBaseToType != null) { int promotionIndex = 0; EdmType t; for (t = entityBaseFromType; t != entityBaseToType && t != null; t = t.BaseType, ++promotionIndex); if (t == null) { throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.FailedToGeneratePromotionRank, 2); } return -promotionIndex; } throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.FailedToGeneratePromotionRank, 3); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Orleans.Streams; namespace Orleans.Runtime.Host { /// <summary> /// Interfacse exposed by ServiceRuntimeWrapper for functionality provided /// by Microsoft.WindowsAzure.ServiceRuntime. /// </summary> public interface IServiceRuntimeWrapper { /// <summary> /// Deployment ID of the hosted service /// </summary> string DeploymentId { get; } /// <summary> /// Name of the role instance /// </summary> string InstanceName { get; } /// <summary> /// Name of the worker/web role /// </summary> string RoleName { get; } /// <summary> /// Update domain of the role instance /// </summary> int UpdateDomain { get; } /// <summary> /// Fault domain of the role instance /// </summary> int FaultDomain { get; } /// <summary> /// Number of instances in the worker/web role /// </summary> int RoleInstanceCount { get; } /// <summary> /// Returns IP endpoint by name /// </summary> /// <param name="endpointName">Name of the IP endpoint</param> /// <returns></returns> IPEndPoint GetIPEndpoint(string endpointName); /// <summary> /// Returns value of the given configuration setting /// </summary> /// <param name="configurationSettingName"></param> /// <returns></returns> string GetConfigurationSettingValue(string configurationSettingName); /// <summary> /// Subscribes given even handler for role instance Stopping event /// </summary> /// /// <param name="handlerObject">Object that handler is part of, or null for a static method</param> /// <param name="handler">Handler to subscribe</param> void SubscribeForStoppingNotifcation(object handlerObject, EventHandler<object> handler); /// <summary> /// Unsubscribes given even handler from role instance Stopping event /// </summary> /// /// <param name="handlerObject">Object that handler is part of, or null for a static method</param> /// <param name="handler">Handler to unsubscribe</param> void UnsubscribeFromStoppingNotifcation(object handlerObject, EventHandler<object> handler); } /// <summary> /// The purpose of this class is to wrap the functionality provided /// by Microsoft.WindowsAzure.ServiceRuntime.dll, so that we can access it via Reflection, /// and not have a compile-time dependency on it. /// Microsoft.WindowsAzure.ServiceRuntime.dll doesn't have an official NuGet package. /// By loading it via Reflection we solve this problem, and do not need an assembly /// binding redirect for it, as we can call any compatible version. /// Microsoft.WindowsAzure.ServiceRuntime.dll hasn't changed in years, so the chance of a breaking change /// is relatively low. /// </summary> internal class ServiceRuntimeWrapper : IServiceRuntimeWrapper, IDeploymentConfiguration { private readonly TraceLogger logger; private Assembly assembly; private Type roleEnvironmentType; private EventInfo stoppingEvent; private MethodInfo stoppingEventAdd; private MethodInfo stoppingEventRemove; private Type roleInstanceType; private dynamic currentRoleInstance; private dynamic instanceEndpoints; private dynamic role; public ServiceRuntimeWrapper() { logger = TraceLogger.GetLogger("ServiceRuntimeWrapper"); Initialize(); } public string DeploymentId { get; private set; } public string InstanceId { get; private set; } public string RoleName { get; private set; } public int UpdateDomain { get; private set; } public int FaultDomain { get; private set; } public string InstanceName { get { return ExtractInstanceName(InstanceId, DeploymentId); } } public int RoleInstanceCount { get { dynamic instances = role.Instances; return instances.Count; } } public IList<string> GetAllSiloInstanceNames() { dynamic instances = role.Instances; var list = new List<string>(); foreach(dynamic instance in instances) list.Add(ExtractInstanceName(instance.Id,DeploymentId)); return list; } public IPEndPoint GetIPEndpoint(string endpointName) { try { dynamic ep = instanceEndpoints.GetType() .GetProperty("Item") .GetMethod.Invoke(instanceEndpoints, new object[] {endpointName}); return ep.IPEndpoint; } catch (Exception exc) { var errorMsg = string.Format("Unable to obtain endpoint info for role {0} from role config parameter {1} -- Endpoints defined = [{2}]", RoleName, endpointName, string.Join(", ", instanceEndpoints)); logger.Error(ErrorCode.SiloEndpointConfigError, errorMsg, exc); throw new OrleansException(errorMsg, exc); } } public string GetConfigurationSettingValue(string configurationSettingName) { return (string) roleEnvironmentType.GetMethod("GetConfigurationSettingValue").Invoke(null, new object[] {configurationSettingName}); } public void SubscribeForStoppingNotifcation(object handlerObject, EventHandler<object> handler) { var handlerDelegate = handler.GetMethodInfo().CreateDelegate(stoppingEvent.EventHandlerType, handlerObject); stoppingEventAdd.Invoke(null, new object[] { handlerDelegate }); } public void UnsubscribeFromStoppingNotifcation(object handlerObject, EventHandler<object> handler) { var handlerDelegate = handler.GetMethodInfo().CreateDelegate(stoppingEvent.EventHandlerType, handlerObject); stoppingEventRemove.Invoke(null, new[] { handlerDelegate }); } private void Initialize() { assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault( a => a.FullName.StartsWith("Microsoft.WindowsAzure.ServiceRuntime")); // If we are runing within a worker role Microsoft.WindowsAzure.ServiceRuntime should already be loaded if (assembly == null) { const string msg1 = "Microsoft.WindowsAzure.ServiceRuntime is not loaded. Trying to load it with Assembly.LoadWithPartialName()."; logger.Warn(ErrorCode.AzureServiceRuntime_NotLoaded, msg1); // Microsoft.WindowsAzure.ServiceRuntime isn't loaded. We may be running within a web role or not in Azure. // Trying to load by partial name, so that we are not version specific. // Assembly.LoadWithPartialName has been deprecated. Is there a better way to load any version of a known assembly? #pragma warning disable 618 assembly = Assembly.LoadWithPartialName("Microsoft.WindowsAzure.ServiceRuntime"); #pragma warning restore 618 if (assembly == null) { const string msg2 = "Failed to find or load Microsoft.WindowsAzure.ServiceRuntime."; logger.Error(ErrorCode.AzureServiceRuntime_FailedToLoad, msg2); throw new OrleansException(msg2); } } roleEnvironmentType = assembly.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment"); stoppingEvent = roleEnvironmentType.GetEvent("Stopping"); stoppingEventAdd = stoppingEvent.GetAddMethod(); stoppingEventRemove = stoppingEvent.GetRemoveMethod(); roleInstanceType = assembly.GetType("Microsoft.WindowsAzure.ServiceRuntime.RoleInstance"); DeploymentId = (string) roleEnvironmentType.GetProperty("DeploymentId").GetValue(null); if (string.IsNullOrWhiteSpace(DeploymentId)) throw new OrleansException("DeploymentId is null or whitespace."); currentRoleInstance = roleEnvironmentType.GetProperty("CurrentRoleInstance").GetValue(null); if (currentRoleInstance == null) throw new OrleansException("CurrentRoleInstance is null."); InstanceId = currentRoleInstance.Id; UpdateDomain = currentRoleInstance.UpdateDomain; FaultDomain = currentRoleInstance.FaultDomain; instanceEndpoints = currentRoleInstance.InstanceEndpoints; role = currentRoleInstance.Role; RoleName = role.Name; } private static string ExtractInstanceName(string instanceId, string deploymentId) { return instanceId.Length > deploymentId.Length && instanceId.StartsWith(deploymentId) ? instanceId.Substring(deploymentId.Length + 1) : instanceId; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using YamlDotNet.Core; using YamlDotNet.Core.Events; using VersionDirective = YamlDotNet.Core.Tokens.VersionDirective; using TagDirective = YamlDotNet.Core.Tokens.TagDirective; namespace YamlDotNet.UnitTests { [TestClass] public class ParserTests : YamlTest { private static Parser CreateParser(string name) { return new Parser(YamlFile(name)); } private void AssertHasNext(Parser parser) { Assert.IsTrue(parser.MoveNext(), "The parser does not contain more events."); } private void AssertDoesNotHaveNext(Parser parser) { Assert.IsFalse(parser.MoveNext(), "The parser should not contain more events."); } private void AssertCurrent(Parser parser, ParsingEvent expected) { Console.WriteLine(expected.GetType().Name); Assert.IsTrue(expected.GetType().IsAssignableFrom(parser.Current.GetType()), "The event is not of the expected type."); foreach (var property in expected.GetType().GetProperties()) { if(property.PropertyType != typeof(Mark) && property.CanRead) { object value = property.GetValue(parser.Current, null); object expectedValue = property.GetValue(expected, null); if(expectedValue != null && Type.GetTypeCode(expectedValue.GetType()) == TypeCode.Object && expectedValue is IEnumerable) { Console.Write("\t{0} = {{", property.Name); bool isFirst = true; foreach(var item in (IEnumerable)value) { if(isFirst) { isFirst = false; } else { Console.Write(", "); } Console.Write(item); } Console.WriteLine("}"); if(expectedValue is ICollection && value is ICollection) { Assert.AreEqual(((ICollection)expectedValue).Count, ((ICollection)value).Count, "The collection does not contain the correct number of items."); } IEnumerator values = ((IEnumerable)value).GetEnumerator(); IEnumerator expectedValues = ((IEnumerable)expectedValue).GetEnumerator(); while(expectedValues.MoveNext()) { Assert.IsTrue(values.MoveNext(), "The property does not contain enough items."); Assert.AreEqual(expectedValues.Current, values.Current, string.Format("The property '{0}' is incorrect.", property.Name)); } Assert.IsFalse(values.MoveNext(), "The property contains too many items."); } else { Console.WriteLine("\t{0} = {1}", property.Name, value); Assert.AreEqual(expectedValue, value, string.Format("The property '{0}' is incorrect.", property.Name)); } } } } private void AssertNext(Parser parser, ParsingEvent expected) { AssertHasNext(parser); AssertCurrent(parser, expected); } [TestMethod] public void EmptyDocument() { Parser parser = CreateParser("empty.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } private static TagDirectiveCollection defaultDirectives = new TagDirectiveCollection(new TagDirective[] { new TagDirective("!", "!"), new TagDirective("!!", "tag:yaml.org,2002:"), }); [TestMethod] public void VerifyEventsOnExample1() { Parser parser = CreateParser("test1.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(new VersionDirective(new Core.Version(1, 1)), new TagDirectiveCollection(new TagDirective[] { new TagDirective("!", "!foo"), new TagDirective("!yaml!", "tag:yaml.org,2002:"), new TagDirective("!!", "tag:yaml.org,2002:"), }), false)); AssertNext(parser, new Scalar(null, null, string.Empty, ScalarStyle.Plain, true, false)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample2() { Parser parser = CreateParser("test2.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new Scalar(null, null, "a scalar", ScalarStyle.SingleQuoted, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample3() { Parser parser = CreateParser("test3.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "a scalar", ScalarStyle.SingleQuoted, false, true)); AssertNext(parser, new DocumentEnd(false)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample4() { Parser parser = CreateParser("test4.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new Scalar(null, null, "a scalar", ScalarStyle.SingleQuoted, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "another scalar", ScalarStyle.SingleQuoted, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "yet another scalar", ScalarStyle.SingleQuoted, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample5() { Parser parser = CreateParser("test5.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new SequenceStart("A", null, true, SequenceStyle.Flow)); AssertNext(parser, new AnchorAlias("A")); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample6() { Parser parser = CreateParser("test6.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new Scalar(null, "tag:yaml.org,2002:float", "3.14", ScalarStyle.DoubleQuoted, false, false)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample7() { Parser parser = CreateParser("test7.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "", ScalarStyle.Plain, true, false)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "a plain scalar", ScalarStyle.Plain, true, false)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "a single-quoted scalar", ScalarStyle.SingleQuoted, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "a double-quoted scalar", ScalarStyle.DoubleQuoted, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "a literal scalar", ScalarStyle.Literal, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new DocumentStart(null, defaultDirectives, false)); AssertNext(parser, new Scalar(null, null, "a folded scalar", ScalarStyle.Folded, false, true)); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample8() { Parser parser = CreateParser("test8.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Flow)); AssertNext(parser, new Scalar(null, null, "item 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 3", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample9() { Parser parser = CreateParser("test9.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Flow)); AssertNext(parser, new Scalar(null, null, "a simple key", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "a value", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "a complex key", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "another value", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample10() { Parser parser = CreateParser("test10.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new Scalar(null, null, "item 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new Scalar(null, null, "item 3.1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 3.2", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "key 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "key 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingEnd()); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample11() { Parser parser = CreateParser("test11.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "a simple key", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "a value", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "a complex key", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "another value", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "a mapping", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "key 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "key 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingEnd()); AssertNext(parser, new Scalar(null, null, "a sequence", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new Scalar(null, null, "item 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new MappingEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample12() { Parser parser = CreateParser("test12.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new Scalar(null, null, "item 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "key 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "key 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingEnd()); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "complex key", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "complex value", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingEnd()); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample13() { Parser parser = CreateParser("test13.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "a sequence", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new Scalar(null, null, "item 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new Scalar(null, null, "a mapping", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "key 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "key 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "value 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new MappingEnd()); AssertNext(parser, new MappingEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } [TestMethod] public void VerifyTokensOnExample14() { Parser parser = CreateParser("test14.yaml"); AssertNext(parser, new StreamStart()); AssertNext(parser, new DocumentStart(null, defaultDirectives, true)); AssertNext(parser, new MappingStart(null, null, true, MappingStyle.Block)); AssertNext(parser, new Scalar(null, null, "key", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceStart(null, null, true, SequenceStyle.Block)); AssertNext(parser, new Scalar(null, null, "item 1", ScalarStyle.Plain, true, false)); AssertNext(parser, new Scalar(null, null, "item 2", ScalarStyle.Plain, true, false)); AssertNext(parser, new SequenceEnd()); AssertNext(parser, new MappingEnd()); AssertNext(parser, new DocumentEnd(true)); AssertNext(parser, new StreamEnd()); AssertDoesNotHaveNext(parser); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { #region Tables Struct public partial struct Tables { public static readonly string AspnetApplication = @"aspnet_Applications"; public static readonly string AspnetRole = @"aspnet_Roles"; public static readonly string AspnetUser = @"aspnet_Users"; public static readonly string AspnetUsersInRole = @"aspnet_UsersInRoles"; public static readonly string AuditLog = @"AuditLog"; public static readonly string DataLog = @"DataLog"; public static readonly string DataSchema = @"DataSchema"; public static readonly string DataSource = @"DataSource"; public static readonly string DataSourceTransformation = @"DataSourceTransformation"; public static readonly string DataSourceType = @"DataSourceType"; public static readonly string DigitalObjectIdentifier = @"DigitalObjectIdentifiers"; public static readonly string ImportBatch = @"ImportBatch"; public static readonly string ImportBatchSummary = @"ImportBatchSummary"; public static readonly string Instrument = @"Instrument"; public static readonly string InstrumentSensor = @"Instrument_Sensor"; public static readonly string ModuleX = @"Module"; public static readonly string Observation = @"Observation"; public static readonly string Offering = @"Offering"; public static readonly string Organisation = @"Organisation"; public static readonly string OrganisationInstrument = @"Organisation_Instrument"; public static readonly string OrganisationSite = @"Organisation_Site"; public static readonly string OrganisationStation = @"Organisation_Station"; public static readonly string OrganisationRole = @"OrganisationRole"; public static readonly string Phenomenon = @"Phenomenon"; public static readonly string PhenomenonOffering = @"PhenomenonOffering"; public static readonly string PhenomenonUOM = @"PhenomenonUOM"; public static readonly string Programme = @"Programme"; public static readonly string Project = @"Project"; public static readonly string ProjectStation = @"Project_Station"; public static readonly string RoleModule = @"RoleModule"; public static readonly string SchemaColumn = @"SchemaColumn"; public static readonly string SchemaColumnType = @"SchemaColumnType"; public static readonly string Sensor = @"Sensor"; public static readonly string Site = @"Site"; public static readonly string Station = @"Station"; public static readonly string StationInstrument = @"Station_Instrument"; public static readonly string Status = @"Status"; public static readonly string StatusReason = @"StatusReason"; public static readonly string TransformationType = @"TransformationType"; public static readonly string UnitOfMeasure = @"UnitOfMeasure"; } #endregion #region Schemas public partial class Schemas { public static TableSchema.Table AspnetApplication { get { return DataService.GetSchema("aspnet_Applications", "ObservationsDB"); } } public static TableSchema.Table AspnetRole { get { return DataService.GetSchema("aspnet_Roles", "ObservationsDB"); } } public static TableSchema.Table AspnetUser { get { return DataService.GetSchema("aspnet_Users", "ObservationsDB"); } } public static TableSchema.Table AspnetUsersInRole { get { return DataService.GetSchema("aspnet_UsersInRoles", "ObservationsDB"); } } public static TableSchema.Table AuditLog { get { return DataService.GetSchema("AuditLog", "ObservationsDB"); } } public static TableSchema.Table DataLog { get { return DataService.GetSchema("DataLog", "ObservationsDB"); } } public static TableSchema.Table DataSchema { get { return DataService.GetSchema("DataSchema", "ObservationsDB"); } } public static TableSchema.Table DataSource { get { return DataService.GetSchema("DataSource", "ObservationsDB"); } } public static TableSchema.Table DataSourceTransformation { get { return DataService.GetSchema("DataSourceTransformation", "ObservationsDB"); } } public static TableSchema.Table DataSourceType { get { return DataService.GetSchema("DataSourceType", "ObservationsDB"); } } public static TableSchema.Table DigitalObjectIdentifier { get { return DataService.GetSchema("DigitalObjectIdentifiers", "ObservationsDB"); } } public static TableSchema.Table ImportBatch { get { return DataService.GetSchema("ImportBatch", "ObservationsDB"); } } public static TableSchema.Table ImportBatchSummary { get { return DataService.GetSchema("ImportBatchSummary", "ObservationsDB"); } } public static TableSchema.Table Instrument { get { return DataService.GetSchema("Instrument", "ObservationsDB"); } } public static TableSchema.Table InstrumentSensor { get { return DataService.GetSchema("Instrument_Sensor", "ObservationsDB"); } } public static TableSchema.Table ModuleX { get { return DataService.GetSchema("Module", "ObservationsDB"); } } public static TableSchema.Table Observation { get { return DataService.GetSchema("Observation", "ObservationsDB"); } } public static TableSchema.Table Offering { get { return DataService.GetSchema("Offering", "ObservationsDB"); } } public static TableSchema.Table Organisation { get { return DataService.GetSchema("Organisation", "ObservationsDB"); } } public static TableSchema.Table OrganisationInstrument { get { return DataService.GetSchema("Organisation_Instrument", "ObservationsDB"); } } public static TableSchema.Table OrganisationSite { get { return DataService.GetSchema("Organisation_Site", "ObservationsDB"); } } public static TableSchema.Table OrganisationStation { get { return DataService.GetSchema("Organisation_Station", "ObservationsDB"); } } public static TableSchema.Table OrganisationRole { get { return DataService.GetSchema("OrganisationRole", "ObservationsDB"); } } public static TableSchema.Table Phenomenon { get { return DataService.GetSchema("Phenomenon", "ObservationsDB"); } } public static TableSchema.Table PhenomenonOffering { get { return DataService.GetSchema("PhenomenonOffering", "ObservationsDB"); } } public static TableSchema.Table PhenomenonUOM { get { return DataService.GetSchema("PhenomenonUOM", "ObservationsDB"); } } public static TableSchema.Table Programme { get { return DataService.GetSchema("Programme", "ObservationsDB"); } } public static TableSchema.Table Project { get { return DataService.GetSchema("Project", "ObservationsDB"); } } public static TableSchema.Table ProjectStation { get { return DataService.GetSchema("Project_Station", "ObservationsDB"); } } public static TableSchema.Table RoleModule { get { return DataService.GetSchema("RoleModule", "ObservationsDB"); } } public static TableSchema.Table SchemaColumn { get { return DataService.GetSchema("SchemaColumn", "ObservationsDB"); } } public static TableSchema.Table SchemaColumnType { get { return DataService.GetSchema("SchemaColumnType", "ObservationsDB"); } } public static TableSchema.Table Sensor { get { return DataService.GetSchema("Sensor", "ObservationsDB"); } } public static TableSchema.Table Site { get { return DataService.GetSchema("Site", "ObservationsDB"); } } public static TableSchema.Table Station { get { return DataService.GetSchema("Station", "ObservationsDB"); } } public static TableSchema.Table StationInstrument { get { return DataService.GetSchema("Station_Instrument", "ObservationsDB"); } } public static TableSchema.Table Status { get { return DataService.GetSchema("Status", "ObservationsDB"); } } public static TableSchema.Table StatusReason { get { return DataService.GetSchema("StatusReason", "ObservationsDB"); } } public static TableSchema.Table TransformationType { get { return DataService.GetSchema("TransformationType", "ObservationsDB"); } } public static TableSchema.Table UnitOfMeasure { get { return DataService.GetSchema("UnitOfMeasure", "ObservationsDB"); } } } #endregion #region View Struct public partial struct Views { public static readonly string VAuditLog = @"vAuditLog"; public static readonly string VDataLog = @"vDataLog"; public static readonly string VDataQuery = @"vDataQuery"; public static readonly string VDataSchema = @"vDataSchema"; public static readonly string VDataSource = @"vDataSource"; public static readonly string VDataSourceTransformation = @"vDataSourceTransformation"; public static readonly string VImportBatch = @"vImportBatch"; public static readonly string VImportBatchSummary = @"vImportBatchSummary"; public static readonly string VInstrumentOrganisation = @"vInstrumentOrganisation"; public static readonly string VInstrumentSensor = @"vInstrumentSensor"; public static readonly string VInventoryDataset = @"vInventoryDatasets"; public static readonly string VInventorySensor = @"vInventorySensors"; public static readonly string VModuleRoleModule = @"vModuleRoleModule"; public static readonly string VObservation = @"vObservation"; public static readonly string VObservationApi = @"vObservationApi"; public static readonly string VObservationExpansion = @"vObservationExpansion"; public static readonly string VObservationJSON = @"vObservationJSON"; public static readonly string VObservationODatum = @"vObservationOData"; public static readonly string VOfferingPhenomena = @"vOfferingPhenomena"; public static readonly string VOrganisationInstrument = @"vOrganisationInstrument"; public static readonly string VOrganisationSite = @"vOrganisationSite"; public static readonly string VOrganisationStation = @"vOrganisationStation"; public static readonly string VProject = @"vProject"; public static readonly string VProjectStation = @"vProjectStation"; public static readonly string VSchemaColumn = @"vSchemaColumn"; public static readonly string VSensor = @"vSensor"; public static readonly string VSensorDate = @"vSensorDates"; public static readonly string VSensorLocation = @"vSensorLocation"; public static readonly string VSiteOrganisation = @"vSiteOrganisation"; public static readonly string VStation = @"vStation"; public static readonly string VStationDataset = @"vStationDatasets"; public static readonly string VStationInstrument = @"vStationInstrument"; public static readonly string VStationOrganisation = @"vStationOrganisation"; public static readonly string VUnitOfMeasurePhenomena = @"vUnitOfMeasurePhenomena"; public static readonly string VUserInfo = @"vUserInfo"; } #endregion #region Query Factories public static partial class DB { public static DataProvider _provider = DataService.Providers["ObservationsDB"]; static ISubSonicRepository _repository; public static ISubSonicRepository Repository { get { if (_repository == null) return new SubSonicRepository(_provider); return _repository; } set { _repository = value; } } public static Select SelectAllColumnsFrom<T>() where T : RecordBase<T>, new() { return Repository.SelectAllColumnsFrom<T>(); } public static Select Select() { return Repository.Select(); } public static Select Select(params string[] columns) { return Repository.Select(columns); } public static Select Select(params Aggregate[] aggregates) { return Repository.Select(aggregates); } public static Update Update<T>() where T : RecordBase<T>, new() { return Repository.Update<T>(); } public static Insert Insert() { return Repository.Insert(); } public static Delete Delete() { return Repository.Delete(); } public static InlineQuery Query() { return Repository.Query(); } } #endregion } #region Databases public partial struct Databases { public static readonly string ObservationsDB = @"ObservationsDB"; } #endregion
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F04_SubContinent (editable child object).<br/> /// This is a generated base class of <see cref="F04_SubContinent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="F05_CountryObjects"/> of type <see cref="F05_CountryColl"/> (1:M relation to <see cref="F06_Country"/>)<br/> /// This class is an item of <see cref="F03_SubContinentColl"/> collection. /// </remarks> [Serializable] public partial class F04_SubContinent : BusinessBase<F04_SubContinent> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Continent_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> SubContinent_IDProperty = RegisterProperty<int>(p => p.SubContinent_ID, "SubContinents ID"); /// <summary> /// Gets the SubContinents ID. /// </summary> /// <value>The SubContinents ID.</value> public int SubContinent_ID { get { return GetProperty(SubContinent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="SubContinent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_NameProperty = RegisterProperty<string>(p => p.SubContinent_Name, "SubContinents Name"); /// <summary> /// Gets or sets the SubContinents Name. /// </summary> /// <value>The SubContinents Name.</value> public string SubContinent_Name { get { return GetProperty(SubContinent_NameProperty); } set { SetProperty(SubContinent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F05_SubContinent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<F05_SubContinent_Child> F05_SubContinent_SingleObjectProperty = RegisterProperty<F05_SubContinent_Child>(p => p.F05_SubContinent_SingleObject, "F05 SubContinent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the F05 Sub Continent Single Object ("parent load" child property). /// </summary> /// <value>The F05 Sub Continent Single Object.</value> public F05_SubContinent_Child F05_SubContinent_SingleObject { get { return GetProperty(F05_SubContinent_SingleObjectProperty); } private set { LoadProperty(F05_SubContinent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F05_SubContinent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<F05_SubContinent_ReChild> F05_SubContinent_ASingleObjectProperty = RegisterProperty<F05_SubContinent_ReChild>(p => p.F05_SubContinent_ASingleObject, "F05 SubContinent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the F05 Sub Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The F05 Sub Continent ASingle Object.</value> public F05_SubContinent_ReChild F05_SubContinent_ASingleObject { get { return GetProperty(F05_SubContinent_ASingleObjectProperty); } private set { LoadProperty(F05_SubContinent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F05_CountryObjects"/> property. /// </summary> public static readonly PropertyInfo<F05_CountryColl> F05_CountryObjectsProperty = RegisterProperty<F05_CountryColl>(p => p.F05_CountryObjects, "F05 Country Objects", RelationshipTypes.Child); /// <summary> /// Gets the F05 Country Objects ("parent load" child property). /// </summary> /// <value>The F05 Country Objects.</value> public F05_CountryColl F05_CountryObjects { get { return GetProperty(F05_CountryObjectsProperty); } private set { LoadProperty(F05_CountryObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F04_SubContinent"/> object. /// </summary> /// <returns>A reference to the created <see cref="F04_SubContinent"/> object.</returns> internal static F04_SubContinent NewF04_SubContinent() { return DataPortal.CreateChild<F04_SubContinent>(); } /// <summary> /// Factory method. Loads a <see cref="F04_SubContinent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F04_SubContinent"/> object.</returns> internal static F04_SubContinent GetF04_SubContinent(SafeDataReader dr) { F04_SubContinent obj = new F04_SubContinent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(F05_CountryObjectsProperty, F05_CountryColl.NewF05_CountryColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F04_SubContinent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F04_SubContinent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F04_SubContinent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(SubContinent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(F05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<F05_SubContinent_Child>()); LoadProperty(F05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<F05_SubContinent_ReChild>()); LoadProperty(F05_CountryObjectsProperty, DataPortal.CreateChild<F05_CountryColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F04_SubContinent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_IDProperty, dr.GetInt32("SubContinent_ID")); LoadProperty(SubContinent_NameProperty, dr.GetString("SubContinent_Name")); // parent properties parent_Continent_ID = dr.GetInt32("Parent_Continent_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="F05_SubContinent_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F05_SubContinent_Child child) { LoadProperty(F05_SubContinent_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="F05_SubContinent_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(F05_SubContinent_ReChild child) { LoadProperty(F05_SubContinent_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="F04_SubContinent"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F02_Continent parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddF04_SubContinent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_Continent_ID", parent.Continent_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@SubContinent_Name", ReadProperty(SubContinent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(SubContinent_IDProperty, (int) cmd.Parameters["@SubContinent_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="F04_SubContinent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateF04_SubContinent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@SubContinent_Name", ReadProperty(SubContinent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="F04_SubContinent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteF04_SubContinent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SubContinent_ID", ReadProperty(SubContinent_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(F05_SubContinent_SingleObjectProperty, DataPortal.CreateChild<F05_SubContinent_Child>()); LoadProperty(F05_SubContinent_ASingleObjectProperty, DataPortal.CreateChild<F05_SubContinent_ReChild>()); LoadProperty(F05_CountryObjectsProperty, DataPortal.CreateChild<F05_CountryColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace Aurora.Modules.Search { public class AuroraSearchModule : ISharedRegionModule { #region Declares //private static readonly ILog MainConsole.Instance = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly List<IScene> m_Scenes = new List<IScene>(); private IGroupsModule GroupsModule; private IProfileConnector ProfileFrontend; private IDirectoryServiceConnector directoryService; private bool m_SearchEnabled; #endregion #region Client public void NewClient(IClientAPI client) { // Subscribe to messages client.OnDirPlacesQuery += DirPlacesQuery; client.OnDirFindQuery += DirFindQuery; client.OnDirPopularQuery += DirPopularQuery; client.OnDirLandQuery += DirLandQuery; client.OnDirClassifiedQuery += DirClassifiedQuery; // Response after Directory Queries client.OnEventInfoRequest += EventInfoRequest; client.OnMapItemRequest += HandleMapItemRequest; client.OnPlacesQuery += OnPlacesQueryRequest; client.OnAvatarPickerRequest += ProcessAvatarPickerRequest; } private void OnClosingClient(IClientAPI client) { client.OnDirPlacesQuery -= DirPlacesQuery; client.OnDirFindQuery -= DirFindQuery; client.OnDirPopularQuery -= DirPopularQuery; client.OnDirLandQuery -= DirLandQuery; client.OnDirClassifiedQuery -= DirClassifiedQuery; // Response after Directory Queries client.OnEventInfoRequest -= EventInfoRequest; client.OnMapItemRequest -= HandleMapItemRequest; client.OnPlacesQuery -= OnPlacesQueryRequest; client.OnAvatarPickerRequest -= ProcessAvatarPickerRequest; } #endregion #region Search Module #region Delegates public delegate void SendPacket<T>(T[] data); #endregion /// <summary> /// Parcel request /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryID"></param> /// <param name = "queryText">The thing to search for</param> /// <param name = "queryFlags"></param> /// <param name = "category"></param> /// <param name = "simName"></param> /// <param name = "queryStart"></param> protected void DirPlacesQuery(IClientAPI remoteClient, UUID queryID, string queryText, int queryFlags, int category, string simName, int queryStart) { List<DirPlacesReplyData> ReturnValues = directoryService.FindLand(queryText, category.ToString(), queryStart, (uint) queryFlags, remoteClient.ScopeID); #if (!ISWIN) SplitPackets<DirPlacesReplyData>(ReturnValues, delegate(DirPlacesReplyData[] data) { remoteClient.SendDirPlacesReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirPlacesReply(queryID, data)); #endif } public void DirPopularQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags) { List<DirPopularReplyData> ReturnValues = directoryService.FindPopularPlaces(queryFlags, remoteClient.ScopeID); remoteClient.SendDirPopularReply(queryID, ReturnValues.ToArray()); } /// <summary> /// Land for sale request /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryID"></param> /// <param name = "queryFlags"></param> /// <param name = "searchType"></param> /// <param name = "price"></param> /// <param name = "area"></param> /// <param name = "queryStart"></param> public void DirLandQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags, uint searchType, uint price, uint area, int queryStart) { List<DirLandReplyData> ReturnValues = new List<DirLandReplyData>(directoryService.FindLandForSale(searchType.ToString(), price, area, queryStart, queryFlags, remoteClient.ScopeID)); #if (!ISWIN) SplitPackets<DirLandReplyData>(ReturnValues, delegate(DirLandReplyData[] data) { remoteClient.SendDirLandReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirLandReply(queryID, data)); #endif } /// <summary> /// Finds either people or events /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryID">Just a UUID to send back to the client</param> /// <param name = "queryText">The term to search for</param> /// <param name = "queryFlags">Flags like maturity, etc</param> /// <param name = "queryStart">Where in the search should we start? 0, 10, 20, etc</param> public void DirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { if ((queryFlags & 1) != 0) //People query { DirPeopleQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } else if ((queryFlags & 32) != 0) //Events query { DirEventsQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } } //TODO: Flagged to optimize public void DirPeopleQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { //Find the user accounts List<UserAccount> accounts = m_Scenes[0].UserAccountService.GetUserAccounts(remoteClient.AllScopeIDs, queryText); List<DirPeopleReplyData> ReturnValues = new List<DirPeopleReplyData>(); foreach (UserAccount item in accounts) { //This is really bad, we should not be searching for all of these people again in the Profile service IUserProfileInfo UserProfile = ProfileFrontend.GetUserProfile(item.PrincipalID); if (UserProfile == null) { DirPeopleReplyData person = new DirPeopleReplyData { agentID = item.PrincipalID, firstName = item.FirstName, lastName = item.LastName }; if (GroupsModule == null) person.group = ""; else { person.group = ""; GroupMembershipData[] memberships = GroupsModule.GetMembershipData(item.PrincipalID); foreach (GroupMembershipData membership in memberships.Where(membership => membership.Active)) { person.group = membership.GroupName; } } //Then we have to pull the GUI to see if the user is online or not UserInfo Pinfo = m_Scenes[0].RequestModuleInterface<IAgentInfoService>().GetUserInfo(item.PrincipalID.ToString()); if (Pinfo != null && Pinfo.IsOnline) //If it is null, they are offline person.online = true; person.reputation = 0; ReturnValues.Add(person); } else if (UserProfile.AllowPublish) //Check whether they want to be in search or not { DirPeopleReplyData person = new DirPeopleReplyData { agentID = item.PrincipalID, firstName = item.FirstName, lastName = item.LastName }; if (GroupsModule == null) person.group = ""; else { person.group = ""; //Check what group they have set GroupMembershipData[] memberships = GroupsModule.GetMembershipData(item.PrincipalID); foreach (GroupMembershipData membership in memberships.Where(membership => membership.Active)) { person.group = membership.GroupName; } } //Then we have to pull the GUI to see if the user is online or not UserInfo Pinfo = m_Scenes[0].RequestModuleInterface<IAgentInfoService>().GetUserInfo(item.PrincipalID.ToString()); if (Pinfo != null && Pinfo.IsOnline) person.online = true; person.reputation = 0; ReturnValues.Add(person); } } #if (!ISWIN) SplitPackets<DirPeopleReplyData>(ReturnValues, delegate(DirPeopleReplyData[] data) { remoteClient.SendDirPeopleReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirPeopleReply(queryID, data)); #endif } public void DirEventsQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { List<DirEventsReplyData> ReturnValues = new List<DirEventsReplyData>(directoryService.FindEvents(queryText, queryFlags, queryStart, remoteClient.ScopeID)); #if (!ISWIN) SplitPackets<DirEventsReplyData>(ReturnValues, delegate(DirEventsReplyData[] data) { remoteClient.SendDirEventsReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirEventsReply(queryID, data)); #endif } public void DirClassifiedQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category, int queryStart) { List<DirClassifiedReplyData> ReturnValues = new List<DirClassifiedReplyData>(directoryService.FindClassifieds(queryText, category.ToString(), queryFlags, queryStart, remoteClient.ScopeID)); #if (!ISWIN) SplitPackets<DirClassifiedReplyData>(ReturnValues, delegate(DirClassifiedReplyData[] data) { remoteClient.SendDirClassifiedReply(queryID, data); }); #else SplitPackets(ReturnValues, data => remoteClient.SendDirClassifiedReply(queryID, data)); #endif } public void SplitPackets<T>(List<T> packets, SendPacket<T> send) { if (packets.Count == 0) { send(new T[0]); return; } int i = 0; while (i < packets.Count) { int count = Math.Min(10, packets.Count); //Split into sets of 10 packets T[] data = packets.GetRange(i, count).ToArray(); i += count; if (data.Length != 0) send(data); } } /// <summary> /// Tell the client about X event /// </summary> /// <param name = "remoteClient"></param> /// <param name = "queryEventID">ID of the event</param> public void EventInfoRequest(IClientAPI remoteClient, uint queryEventID) { //Find the event EventData data = directoryService.GetEventInfo(queryEventID); if (data == null) return; //Send the event remoteClient.SendEventInfoReply(data); } public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { //All the parts are in for this, except for popular places and those are not in as they are not reqested anymore. List<mapItemReply> mapitems = new List<mapItemReply>(); mapItemReply mapitem = new mapItemReply(); uint xstart = 0; uint ystart = 0; Utils.LongToUInts(remoteClient.Scene.RegionInfo.RegionHandle, out xstart, out ystart); GridRegion GR = null; GR = regionhandle == 0 ? new GridRegion(remoteClient.Scene.RegionInfo) : m_Scenes[0].GridService.GetRegionByPosition(remoteClient.AllScopeIDs, (int)xstart, (int)ystart); if (GR == null) { //No region??? return; } #region Telehub if (itemtype == (uint) GridItemType.Telehub) { IRegionConnector GF = DataManager.DataManager.RequestPlugin<IRegionConnector>(); if (GF == null) return; int tc = Environment.TickCount; //Find the telehub Telehub telehub = GF.FindTelehub(GR.RegionID, GR.RegionHandle); if (telehub != null) { mapitem = new mapItemReply { x = (uint) (GR.RegionLocX + telehub.TelehubLocX), y = (uint) (GR.RegionLocY + telehub.TelehubLocY), id = GR.RegionID, name = Util.Md5Hash(GR.RegionName + tc.ToString()), Extra = 1, Extra2 = 0 }; //The position is in GLOBAL coordinates (in meters) //This is how the name is sent, go figure //Not sure, but this is what gets sent mapitems.Add(mapitem); remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion #region Land for sale //PG land that is for sale if (itemtype == (uint) GridItemType.LandForSale) { if (directoryService == null) return; //Find all the land, use "0" for the flags so we get all land for sale, no price or area checking List<DirLandReplyData> Landdata = directoryService.FindLandForSaleInRegion("0", uint.MaxValue, 0, 0, 0, GR.RegionID); int locX = 0; int locY = 0; foreach (DirLandReplyData landDir in Landdata) { if (landDir == null) continue; LandData landdata = directoryService.GetParcelInfo(landDir.parcelID); if (landdata == null || landdata.Maturity != 0) continue; //Not a PG land foreach (IScene scene in m_Scenes.Where(scene => scene.RegionInfo.RegionID == landdata.RegionID)) { //Global coords, so add the meters locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } if (locY == 0 && locX == 0) { //Ask the grid service for the coordinates if the region is not local GridRegion r = m_Scenes[0].GridService.GetRegionByUUID(remoteClient.AllScopeIDs, landdata.RegionID); if (r != null) { locX = r.RegionLocX; locY = r.RegionLocY; } } if (locY == 0 && locX == 0) //Couldn't find the region, don't send continue; mapitem = new mapItemReply { x = (uint) (locX + landdata.UserLocation.X), y = (uint) (locY + landdata.UserLocation.Y), id = landDir.parcelID, name = landDir.name, Extra = landDir.actualArea, Extra2 = landDir.salePrice }; //Global coords, so make sure its in meters mapitems.Add(mapitem); } //Send all the map items if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } //Adult or mature land that is for sale if (itemtype == (uint) GridItemType.AdultLandForSale) { if (directoryService == null) return; //Find all the land, use "0" for the flags so we get all land for sale, no price or area checking List<DirLandReplyData> Landdata = directoryService.FindLandForSale("0", uint.MaxValue, 0, 0, 0, remoteClient.ScopeID); int locX = 0; int locY = 0; foreach (DirLandReplyData landDir in Landdata) { LandData landdata = directoryService.GetParcelInfo(landDir.parcelID); if (landdata == null || landdata.Maturity == 0) continue; //Its PG #if (!ISWIN) foreach (IScene scene in m_Scenes) { if (scene.RegionInfo.RegionID == landdata.RegionID) { locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } } #else foreach (IScene scene in m_Scenes.Where(scene => scene.RegionInfo.RegionID == landdata.RegionID)) { locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } #endif if (locY == 0 && locX == 0) { //Ask the grid service for the coordinates if the region is not local GridRegion r = m_Scenes[0].GridService.GetRegionByUUID(remoteClient.AllScopeIDs, landdata.RegionID); if (r != null) { locX = r.RegionLocX; locY = r.RegionLocY; } } if (locY == 0 && locX == 0) //Couldn't find the region, don't send continue; mapitem = new mapItemReply { x = (uint) (locX + landdata.UserLocation.X), y = (uint) (locY + landdata.UserLocation.Y), id = landDir.parcelID, name = landDir.name, Extra = landDir.actualArea, Extra2 = landDir.salePrice }; //Global coords, so make sure its in meters mapitems.Add(mapitem); } //Send the results if we have any if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion #region Events if (itemtype == (uint) GridItemType.PgEvent || itemtype == (uint) GridItemType.MatureEvent || itemtype == (uint) GridItemType.AdultEvent) { if (directoryService == null) return; //Find the maturity level int maturity = itemtype == (uint) GridItemType.PgEvent ? (int) DirectoryManager.EventFlags.PG : (itemtype == (uint) GridItemType.MatureEvent) ? (int) DirectoryManager.EventFlags.Mature : (int) DirectoryManager.EventFlags.Adult; //Gets all the events occuring in the given region by maturity level List<DirEventsReplyData> Eventdata = directoryService.FindAllEventsInRegion(GR.RegionName, maturity); foreach (DirEventsReplyData eventData in Eventdata) { //Get more info on the event EventData eventdata = directoryService.GetEventInfo(eventData.eventID); if (eventdata == null) continue; //Can't do anything about it Vector3 globalPos = eventdata.globalPos; mapitem = new mapItemReply { x = (uint) (globalPos.X + (remoteClient.Scene.RegionInfo.RegionSizeX/2)), y = (uint) (globalPos.Y + (remoteClient.Scene.RegionInfo.RegionSizeY/2)), id = UUID.Random(), name = eventData.name, Extra = (int) eventdata.dateUTC, Extra2 = (int) eventdata.eventID }; //Use global position plus half the region so that it doesn't always appear in the bottom corner mapitems.Add(mapitem); } //Send if we have any if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion #region Classified if (itemtype == (uint) GridItemType.Classified) { if (directoryService == null) return; //Get all the classifieds in this region List<Classified> Classifieds = directoryService.GetClassifiedsInRegion(GR.RegionName); foreach (Classified classified in Classifieds) { //Get the region so we have its position GridRegion region = m_Scenes[0].GridService.GetRegionByName(remoteClient.AllScopeIDs, classified.SimName); mapitem = new mapItemReply { x = (uint) (region.RegionLocX + classified.GlobalPos.X + (remoteClient.Scene.RegionInfo.RegionSizeX/2)), y = (uint) (region.RegionLocY + classified.GlobalPos.Y + (remoteClient.Scene.RegionInfo.RegionSizeY/2)), id = classified.CreatorUUID, name = classified.Name, Extra = 0, Extra2 = 0 }; //Use global position plus half the sim so that all classifieds are not in the bottom corner mapitems.Add(mapitem); } //Send the events, if we have any if (mapitems.Count != 0) { remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } #endregion } public void OnPlacesQueryRequest(UUID QueryID, UUID TransactionID, string QueryText, uint QueryFlags, byte Category, string SimName, IClientAPI client) { if (QueryFlags == 64) //Agent Owned { //Get all the parcels client.SendPlacesQuery(directoryService.GetParcelByOwner(client.AgentId).ToArray(), QueryID, TransactionID); } if (QueryFlags == 256) //Group Owned { //Find all the group owned land List<ExtendedLandData> parcels = directoryService.GetParcelByOwner(QueryID); //Send if we have any parcels if (parcels.Count != 0) client.SendPlacesQuery(parcels.ToArray(), QueryID, TransactionID); } } public void ProcessAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query) { IScene scene = client.Scene; List<UserAccount> accounts = scene.UserAccountService.GetUserAccounts(scene.RegionInfo.AllScopeIDs, query); if (accounts == null) accounts = new List<UserAccount>(0); AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); // TODO: don't create new blocks if recycling an old packet AvatarPickerReplyPacket.DataBlock[] searchData = new AvatarPickerReplyPacket.DataBlock[accounts.Count]; AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock {AgentID = avatarID, QueryID = RequestID}; replyPacket.AgentData = agentData; int i = 0; foreach (UserAccount item in accounts) { UUID translatedIDtem = item.PrincipalID; searchData[i] = new AvatarPickerReplyPacket.DataBlock { AvatarID = translatedIDtem, FirstName = Utils.StringToBytes(item.FirstName), LastName = Utils.StringToBytes(item.LastName) }; i++; } if (accounts.Count == 0) { searchData = new AvatarPickerReplyPacket.DataBlock[0]; } replyPacket.Data = searchData; AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs { AgentID = replyPacket.AgentData.AgentID, QueryID = replyPacket.AgentData.QueryID }; List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>(); for (i = 0; i < replyPacket.Data.Length; i++) { AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs { AvatarID = replyPacket.Data[i].AvatarID, FirstName = replyPacket.Data[i].FirstName, LastName = replyPacket.Data[i].LastName }; data_args.Add(data_arg); } client.SendAvatarPickerReply(agent_data, data_args); } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig searchConfig = config.Configs["Search"]; if (searchConfig != null) //Check whether we are enabled if (searchConfig.GetString("SearchModule", Name) == Name) m_SearchEnabled = true; } public void AddRegion(IScene scene) { if (!m_SearchEnabled) return; m_Scenes.Add(scene); scene.EventManager.OnNewClient += NewClient; scene.EventManager.OnClosingClient += OnClosingClient; } public void RemoveRegion(IScene scene) { if (!m_SearchEnabled) return; m_Scenes.Remove(scene); scene.EventManager.OnNewClient -= NewClient; scene.EventManager.OnClosingClient -= OnClosingClient; } public void RegionLoaded(IScene scene) { if (!m_SearchEnabled) return; //Pull in the services we need ProfileFrontend = DataManager.DataManager.RequestPlugin<IProfileConnector>(); directoryService = DataManager.DataManager.RequestPlugin<IDirectoryServiceConnector>(); GroupsModule = scene.RequestModuleInterface<IGroupsModule>(); } public Type ReplaceableInterface { get { return null; } } public bool IsSharedModule { get { return false; } } public void PostInitialise() { } public void Close() { } public string Name { get { return "AuroraSearchModule"; } } #endregion } }
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay // //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. /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections.Generic; using System.Text; using Thrift.Protocol; namespace Netfox.SnooperMessenger.Protocol { #if !SILVERLIGHT [Serializable] #endif public partial class MNMessagesSyncDeltaAdminTextMessage : TBase { private MNMessagesSyncMessageMetadata _MessageMetadata; private string _Type; private Dictionary<string, string> _UntypedData; public MNMessagesSyncMessageMetadata MessageMetadata { get { return _MessageMetadata; } set { __isset.MessageMetadata = true; this._MessageMetadata = value; } } public string Type { get { return _Type; } set { __isset.Type = true; this._Type = value; } } public Dictionary<string, string> UntypedData { get { return _UntypedData; } set { __isset.UntypedData = true; this._UntypedData = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool MessageMetadata; public bool Type; public bool UntypedData; } public MNMessagesSyncDeltaAdminTextMessage() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.Struct) { MessageMetadata = new MNMessagesSyncMessageMetadata(); MessageMetadata.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.String) { Type = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.Map) { { UntypedData = new Dictionary<string, string>(); TMap _map82 = iprot.ReadMapBegin(); for( int _i83 = 0; _i83 < _map82.Count; ++_i83) { string _key84; string _val85; _key84 = iprot.ReadString(); _val85 = iprot.ReadString(); UntypedData[_key84] = _val85; } iprot.ReadMapEnd(); } } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("MNMessagesSyncDeltaAdminTextMessage"); oprot.WriteStructBegin(struc); TField field = new TField(); if (MessageMetadata != null && __isset.MessageMetadata) { field.Name = "MessageMetadata"; field.Type = TType.Struct; field.ID = 1; oprot.WriteFieldBegin(field); MessageMetadata.Write(oprot); oprot.WriteFieldEnd(); } if (Type != null && __isset.Type) { field.Name = "Type"; field.Type = TType.String; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteString(Type); oprot.WriteFieldEnd(); } if (UntypedData != null && __isset.UntypedData) { field.Name = "UntypedData"; field.Type = TType.Map; field.ID = 3; oprot.WriteFieldBegin(field); { oprot.WriteMapBegin(new TMap(TType.String, TType.String, UntypedData.Count)); foreach (string _iter86 in UntypedData.Keys) { oprot.WriteString(_iter86); oprot.WriteString(UntypedData[_iter86]); } oprot.WriteMapEnd(); } oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("MNMessagesSyncDeltaAdminTextMessage("); bool __first = true; if (MessageMetadata != null && __isset.MessageMetadata) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("MessageMetadata: "); __sb.Append(MessageMetadata== null ? "<null>" : MessageMetadata.ToString()); } if (Type != null && __isset.Type) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Type: "); __sb.Append(Type); } if (UntypedData != null && __isset.UntypedData) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("UntypedData: "); __sb.Append(UntypedData); } __sb.Append(")"); return __sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Aspose.HTML.Live.Demos.UI.Helpers.Html { public class HtmlDiff { /// <summary> /// This value defines balance between speed and memory utilization. The higher it is the faster it works and more memory consumes. /// </summary> private const int MatchGranularityMaximum = 4; private readonly StringBuilder _content; private string _newText; private string _oldText; private static Dictionary<string, int> _specialCaseClosingTags = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) { {"</strong>", 0}, {"</em>", 0}, {"</b>",0}, {"</i>",0}, {"</big>",0}, {"</small>",0}, {"</u>",0}, {"</sub>",0}, {"</sup>",0}, {"</strike>",0}, {"</s>",0} }; private static readonly Regex _specialCaseOpeningTagRegex = new Regex( "<((strong)|(b)|(i)|(em)|(big)|(small)|(u)|(sub)|(sup)|(strike)|(s))[\\>\\s]+", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary> /// Tracks opening and closing formatting tags to ensure that we don't inadvertently generate invalid html during the diff process. /// </summary> private Stack<string> _specialTagDiffStack; private string[] _newWords; private string[] _oldWords; private int _matchGranularity; private List<Regex> _blockExpressions; /// <summary> /// Defines how to compare repeating words. Valid values are from 0 to 1. /// This value allows to exclude some words from comparison that eventually /// reduces the total time of the diff algorithm. /// 0 means that all words are excluded so the diff will not find any matching words at all. /// 1 (default value) means that all words participate in comparison so this is the most accurate case. /// 0.5 means that any word that occurs more than 50% times may be excluded from comparison. This doesn't /// mean that such words will definitely be excluded but only gives a permission to exclude them if necessary. /// </summary> public double RepeatingWordsAccuracy { get; set; } /// <summary> /// If true all whitespaces are considered as equal /// </summary> public bool IgnoreWhitespaceDifferences { get; set; } /// <summary> /// If some match is too small and located far from its neighbors then it is considered as orphan /// and removed. For example: /// <code> /// aaaaa bb ccccccccc dddddd ee /// 11111 bb 222222222 dddddd ee /// </code> /// will find two matches <code>bb</code> and <code>dddddd ee</code> but the first will be considered /// as orphan and ignored, as result it will consider texts <code>aaaaa bb ccccccccc</code> and /// <code>11111 bb 222222222</code> as single replacement: /// <code> /// &lt;del&gt;aaaaa bb ccccccccc&lt;/del&gt;&lt;ins&gt;11111 bb 222222222&lt;/ins&gt; dddddd ee /// </code> /// This property defines relative size of the match to be considered as orphan, from 0 to 1. /// 1 means that all matches will be considered as orphans. /// 0 (default) means that no match will be considered as orphan. /// 0.2 means that if match length is less than 20% of distance between its neighbors it is considered as orphan. /// </summary> public double OrphanMatchThreshold { get; set; } /// <summary> /// Initializes a new instance of the class. /// </summary> /// <param name="oldText">The old text.</param> /// <param name="newText">The new text.</param> public HtmlDiff(string oldText, string newText) { RepeatingWordsAccuracy = 1d; //by default all repeating words should be compared _oldText = oldText; _newText = newText; _content = new StringBuilder(); _specialTagDiffStack = new Stack<string>(); _blockExpressions = new List<Regex>(); } public static string Execute(string oldText, string newText) { return new HtmlDiff(oldText, newText).Build(); } /// <summary> /// Builds the HTML diff output /// </summary> /// <returns>HTML diff markup</returns> public string Build() { // If there is no difference, don't bother checking for differences if (_oldText == _newText) { return _newText; } SplitInputsToWords(); _matchGranularity = Math.Min(MatchGranularityMaximum, Math.Min(_oldWords.Length, _newWords.Length)); List<Operation> operations = Operations(); foreach (Operation item in operations) { PerformOperation(item); } return _content.ToString(); } /// <summary> /// Uses <paramref name="expression"/> to group text together so that any change detected within the group is treated as a single block /// </summary> /// <param name="expression"></param> public void AddBlockExpression(Regex expression) { _blockExpressions.Add(expression); } private void SplitInputsToWords() { _oldWords = WordSplitter.ConvertHtmlToListOfWords(_oldText, _blockExpressions); //free memory, allow it for GC _oldText = null; _newWords = WordSplitter.ConvertHtmlToListOfWords(_newText, _blockExpressions); //free memory, allow it for GC _newText = null; } private void PerformOperation(Operation operation) { #if DEBUG operation.PrintDebugInfo(_oldWords, _newWords); #endif switch (operation.Action) { case Action.Equal: ProcessEqualOperation(operation); break; case Action.Delete: ProcessDeleteOperation(operation, "diffdel"); break; case Action.Insert: ProcessInsertOperation(operation, "diffins"); break; case Action.None: break; case Action.Replace: ProcessReplaceOperation(operation); break; } } private void ProcessReplaceOperation(Operation operation) { ProcessDeleteOperation(operation, "diffmod"); ProcessInsertOperation(operation, "diffmod"); } private void ProcessInsertOperation(Operation operation, string cssClass) { List<string> text = _newWords.Where((s, pos) => pos >= operation.StartInNew && pos < operation.EndInNew).ToList(); InsertTag("ins", cssClass, text); } private void ProcessDeleteOperation(Operation operation, string cssClass) { List<string> text = _oldWords.Where((s, pos) => pos >= operation.StartInOld && pos < operation.EndInOld).ToList(); InsertTag("del", cssClass, text); } private void ProcessEqualOperation(Operation operation) { string[] result = _newWords.Where((s, pos) => pos >= operation.StartInNew && pos < operation.EndInNew).ToArray(); _content.Append(String.Join("", result)); } /// <summary> /// This method encloses words within a specified tag (ins or del), and adds this into "content", /// with a twist: if there are words contain tags, it actually creates multiple ins or del, /// so that they don't include any ins or del. This handles cases like /// old: '<p>a</p>' /// new: '<p>ab</p> /// <p> /// c</b>' /// diff result: '<p>a<ins>b</ins></p> /// <p> /// <ins>c</ins> /// </p> /// ' /// this still doesn't guarantee valid HTML (hint: think about diffing a text containing ins or /// del tags), but handles correctly more cases than the earlier version. /// P.S.: Spare a thought for people who write HTML browsers. They live in this ... every day. /// </summary> /// <param name="tag"></param> /// <param name="cssClass"></param> /// <param name="words"></param> private void InsertTag(string tag, string cssClass, List<string> words) { while (true) { if (words.Count == 0) { break; } string[] nonTags = ExtractConsecutiveWords(words, x => !Utils.IsTag(x)); string specialCaseTagInjection = string.Empty; bool specialCaseTagInjectionIsBefore = false; if (nonTags.Length != 0) { string text = Utils.WrapText(string.Join("", nonTags), tag, cssClass); _content.Append(text); } else { // Check if the tag is a special case if (_specialCaseOpeningTagRegex.IsMatch(words[0])) { _specialTagDiffStack.Push(words[0]); specialCaseTagInjection = "<ins class='mod'>"; if (tag == "del") { words.RemoveAt(0); // following tags may be formatting tags as well, follow through while (words.Count > 0 && _specialCaseOpeningTagRegex.IsMatch(words[0])) { words.RemoveAt(0); } } } else if (_specialCaseClosingTags.ContainsKey(words[0])) { var openingTag = _specialTagDiffStack.Count == 0 ? null : _specialTagDiffStack.Pop(); // If we didn't have an opening tag, and we don't have a match with the previous tag used if (openingTag == null || openingTag != words.Last().Replace("/", "")) { // do nothing } else { specialCaseTagInjection = "</ins>"; specialCaseTagInjectionIsBefore = true; } if (tag == "del") { words.RemoveAt(0); // following tags may be formatting tags as well, follow through while (words.Count > 0 && _specialCaseClosingTags.ContainsKey(words[0])) { words.RemoveAt(0); } } } } if (words.Count == 0 && specialCaseTagInjection.Length == 0) { break; } if (specialCaseTagInjectionIsBefore) { _content.Append(specialCaseTagInjection + String.Join("", ExtractConsecutiveWords(words, Utils.IsTag))); } else { _content.Append(String.Join("", ExtractConsecutiveWords(words, Utils.IsTag)) + specialCaseTagInjection); } } } private string[] ExtractConsecutiveWords(List<string> words, Func<string, bool> condition) { int? indexOfFirstTag = null; for (int i = 0; i < words.Count; i++) { string word = words[i]; if (i == 0 && word == " ") { words[i] = "&nbsp;"; } if (!condition(word)) { indexOfFirstTag = i; break; } } if (indexOfFirstTag != null) { string[] items = words.Where((s, pos) => pos >= 0 && pos < indexOfFirstTag).ToArray(); if (indexOfFirstTag.Value > 0) { words.RemoveRange(0, indexOfFirstTag.Value); } return items; } else { string[] items = words.Where((s, pos) => pos >= 0 && pos <= words.Count).ToArray(); words.RemoveRange(0, words.Count); return items; } } private List<Operation> Operations() { int positionInOld = 0, positionInNew = 0; var operations = new List<Operation>(); var matches = MatchingBlocks(); matches.Add(new Match(_oldWords.Length, _newWords.Length, 0)); //Remove orphans from matches. //If distance between left and right matches is 4 times longer than length of current match then it is considered as orphan var mathesWithoutOrphans = RemoveOrphans(matches); foreach (Match match in mathesWithoutOrphans) { bool matchStartsAtCurrentPositionInOld = (positionInOld == match.StartInOld); bool matchStartsAtCurrentPositionInNew = (positionInNew == match.StartInNew); Action action; if (matchStartsAtCurrentPositionInOld == false && matchStartsAtCurrentPositionInNew == false) { action = Action.Replace; } else if (matchStartsAtCurrentPositionInOld && matchStartsAtCurrentPositionInNew == false) { action = Action.Insert; } else if (matchStartsAtCurrentPositionInOld == false) { action = Action.Delete; } else // This occurs if the first few words are the same in both versions { action = Action.None; } if (action != Action.None) { operations.Add( new Operation(action, positionInOld, match.StartInOld, positionInNew, match.StartInNew)); } if (match.Size != 0) { operations.Add(new Operation( Action.Equal, match.StartInOld, match.EndInOld, match.StartInNew, match.EndInNew)); } positionInOld = match.EndInOld; positionInNew = match.EndInNew; } return operations; } private IEnumerable<Match> RemoveOrphans(IEnumerable<Match> matches) { Match prev = null; Match curr = null; foreach (var next in matches) { if (curr == null) { prev = new Match(0, 0, 0); curr = next; continue; } if (prev.EndInOld == curr.StartInOld && prev.EndInNew == curr.StartInNew || curr.EndInOld == next.StartInOld && curr.EndInNew == next.StartInNew) //if match has no diff on the left or on the right { yield return curr; prev = curr; curr = next; continue; } var oldDistanceInChars = Enumerable.Range(prev.EndInOld, next.StartInOld - prev.EndInOld) .Sum(i => _oldWords[i].Length); var newDistanceInChars = Enumerable.Range(prev.EndInNew, next.StartInNew - prev.EndInNew) .Sum(i => _newWords[i].Length); var currMatchLengthInChars = Enumerable.Range(curr.StartInNew, curr.EndInNew - curr.StartInNew) .Sum(i => _newWords[i].Length); if (currMatchLengthInChars > Math.Max(oldDistanceInChars, newDistanceInChars) * OrphanMatchThreshold) { yield return curr; } prev = curr; curr = next; } yield return curr; //assume that the last match is always vital } private List<Match> MatchingBlocks() { var matchingBlocks = new List<Match>(); FindMatchingBlocks(0, _oldWords.Length, 0, _newWords.Length, matchingBlocks); return matchingBlocks; } private void FindMatchingBlocks( int startInOld, int endInOld, int startInNew, int endInNew, List<Match> matchingBlocks) { Match match = FindMatch(startInOld, endInOld, startInNew, endInNew); if (match != null) { if (startInOld < match.StartInOld && startInNew < match.StartInNew) { FindMatchingBlocks(startInOld, match.StartInOld, startInNew, match.StartInNew, matchingBlocks); } matchingBlocks.Add(match); if (match.EndInOld < endInOld && match.EndInNew < endInNew) { FindMatchingBlocks(match.EndInOld, endInOld, match.EndInNew, endInNew, matchingBlocks); } } } private Match FindMatch(int startInOld, int endInOld, int startInNew, int endInNew) { // For large texts it is more likely that there is a Match of size bigger than maximum granularity. // If not then go down and try to find it with smaller granularity. for (int i = _matchGranularity; i > 0; i--) { var options = new MatchOptions { BlockSize = i, RepeatingWordsAccuracy = RepeatingWordsAccuracy, IgnoreWhitespaceDifferences = IgnoreWhitespaceDifferences }; var finder = new MatchFinder(_oldWords, _newWords, startInOld, endInOld, startInNew, endInNew, options); var match = finder.FindMatch(); if (match != null) return match; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Collections.ObjectModel { [Serializable] [DebuggerTypeProxy(typeof(DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private readonly IDictionary<TKey, TValue> _dictionary; [NonSerialized] private Object _syncRoot; [NonSerialized] private KeyCollection _keys; [NonSerialized] private ValueCollection _values; public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } Contract.EndContractBlock(); _dictionary = dictionary; } protected IDictionary<TKey, TValue> Dictionary { get { return _dictionary; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (_keys == null) { _keys = new KeyCollection(_dictionary.Keys); } return _keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (_values == null) { _values = new ValueCollection(_dictionary.Values); } return _values; } } #region IDictionary<TKey, TValue> Members public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } public TValue this[TKey key] { get { return _dictionary[key]; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool IDictionary<TKey, TValue>.Remove(TKey key) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return _dictionary[key]; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return _dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return _dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _dictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dictionary.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)_dictionary).GetEnumerator(); } #endregion #region IDictionary Members private static bool IsCompatibleKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return key is TKey; } void IDictionary.Add(object key, object value) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void IDictionary.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool IDictionary.Contains(object key) { return IsCompatibleKey(key) && ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { IDictionary d = _dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); } return new DictionaryEnumerator(_dictionary); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return Keys; } } void IDictionary.Remove(object key) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } ICollection IDictionary.Values { get { return Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { return this[(TKey)key]; } return null; } set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { _dictionary.CopyTo(pairs, index); } else { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { foreach (var item in _dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType); } try { foreach (var item in _dictionary) { objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { ICollection c = _dictionary as ICollection; if (c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } [Serializable] private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> _dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> _enumerator; public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _enumerator = _dictionary.GetEnumerator(); } public DictionaryEntry Entry { get { return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value); } } public object Key { get { return _enumerator.Current.Key; } } public object Value { get { return _enumerator.Current.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } } #endregion #region IReadOnlyDictionary members IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return Keys; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return Values; } } #endregion IReadOnlyDictionary members [Serializable] [DebuggerTypeProxy(typeof(CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private readonly ICollection<TKey> _collection; [NonSerialized] private Object _syncRoot; internal KeyCollection(ICollection<TKey> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } _collection = collection; } #region ICollection<T> Members void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void ICollection<TKey>.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool ICollection<TKey>.Contains(TKey item) { return _collection.Contains(item); } public void CopyTo(TKey[] array, int arrayIndex) { _collection.CopyTo(array, arrayIndex); } public int Count { get { return _collection.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection<TKey>.Remove(TKey item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } #endregion #region IEnumerable<T> Members public IEnumerator<TKey> GetEnumerator() { return _collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(_collection, array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { ICollection c = _collection as ICollection; if (c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } #endregion } [Serializable] [DebuggerTypeProxy(typeof(CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private readonly ICollection<TValue> _collection; [NonSerialized] private Object _syncRoot; internal ValueCollection(ICollection<TValue> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } _collection = collection; } #region ICollection<T> Members void ICollection<TValue>.Add(TValue item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } void ICollection<TValue>.Clear() { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } bool ICollection<TValue>.Contains(TValue item) { return _collection.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { _collection.CopyTo(array, arrayIndex); } public int Count { get { return _collection.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection<TValue>.Remove(TValue item) { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } #endregion #region IEnumerable<T> Members public IEnumerator<TValue> GetEnumerator() { return _collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(_collection, array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { ICollection c = _collection as ICollection; if (c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } #endregion ICollection Members } } // To share code when possible, use a non-generic class to get rid of irrelevant type parameters. internal static class ReadOnlyDictionaryHelpers { #region Helper method for our KeyCollection and ValueCollection // Abstracted away to avoid redundant implementations. internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < collection.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } // Easy out if the ICollection<T> implements the non-generic ICollection ICollection nonGenericCollection = collection as ICollection; if (nonGenericCollection != null) { nonGenericCollection.CopyTo(array, index); return; } T[] items = array as T[]; if (items != null) { collection.CopyTo(items, index); } else { /* FxOverRh: Type.IsAssignableNot() not an api on that platform. // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { throw new ArgumentException(SR.Argument_InvalidArrayType); } */ // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType); } try { foreach (var item in collection) { objects[index++] = item; } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } } #endregion Helper method for our KeyCollection and ValueCollection } }
//------------------------------------------------------------------------------ // <copyright file="ColumnCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.Web.UI; /// <devdoc> /// <para>Represents the collection of columns to be displayed in /// a <see cref='System.Web.UI.WebControls.DataGrid'/> /// control.</para> /// </devdoc> public sealed class DataGridColumnCollection : ICollection, IStateManager { private DataGrid owner; private ArrayList columns; private bool marked; /// <devdoc> /// <para>Initializes a new instance of <see cref='System.Web.UI.WebControls.DataGridColumnCollection'/> class.</para> /// </devdoc> public DataGridColumnCollection(DataGrid owner, ArrayList columns) { this.owner = owner; this.columns = columns; } /// <devdoc> /// <para>Gets the number of columns in the collection. This property is read-only.</para> /// </devdoc> [ Browsable(false) ] public int Count { get { return columns.Count; } } /// <devdoc> /// <para>Gets a value that specifies whether items in the <see cref='System.Web.UI.WebControls.DataGridColumnCollection'/> can be /// modified. This property is read-only.</para> /// </devdoc> [ Browsable(false) ] public bool IsReadOnly { get { return false; } } /// <devdoc> /// <para>Gets a value that indicates whether the <see cref='System.Web.UI.WebControls.DataGridColumnCollection'/> is thread-safe. This property is read-only.</para> /// </devdoc> [ Browsable(false) ] public bool IsSynchronized { get { return false; } } /// <devdoc> /// <para>Gets the object used to synchronize access to the collection. This property is read-only. </para> /// </devdoc> [ Browsable(false) ] public Object SyncRoot { get { return this; } } /// <devdoc> /// <para>Gets a <see cref='System.Web.UI.WebControls.DataGridColumn'/> at the specified index in the /// collection.</para> /// </devdoc> [ Browsable(false) ] public DataGridColumn this[int index] { get { return (DataGridColumn)columns[index]; } } /// <devdoc> /// <para>Appends a <see cref='System.Web.UI.WebControls.DataGridColumn'/> to the collection.</para> /// </devdoc> public void Add(DataGridColumn column) { AddAt(-1, column); } /// <devdoc> /// <para>Inserts a <see cref='System.Web.UI.WebControls.DataGridColumn'/> to the collection /// at the specified index.</para> /// </devdoc> public void AddAt(int index, DataGridColumn column) { if (column == null) { throw new ArgumentNullException("column"); } if (index == -1) { columns.Add(column); } else { columns.Insert(index, column); } column.SetOwner(owner); if (marked) ((IStateManager)column).TrackViewState(); OnColumnsChanged(); } /// <devdoc> /// <para>Empties the collection of all <see cref='System.Web.UI.WebControls.DataGridColumn'/> objects.</para> /// </devdoc> public void Clear() { columns.Clear(); OnColumnsChanged(); } /// <devdoc> /// <para>Copies the contents of the entire collection into an <see cref='System.Array' qualify='true'/> appending at /// the specified index of the <see cref='System.Array' qualify='true'/>.</para> /// </devdoc> public void CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } for (IEnumerator e = this.GetEnumerator(); e.MoveNext();) array.SetValue(e.Current, index++); } /// <devdoc> /// <para>Creates an enumerator for the <see cref='System.Web.UI.WebControls.DataGridColumnCollection'/> used to iterate through the collection.</para> /// </devdoc> public IEnumerator GetEnumerator() { return columns.GetEnumerator(); } /// <devdoc> /// <para>Returns the index of the first occurrence of a value in a <see cref='System.Web.UI.WebControls.DataGridColumn'/>.</para> /// </devdoc> public int IndexOf(DataGridColumn column) { if (column != null) { return columns.IndexOf(column); } return -1; } /// <devdoc> /// </devdoc> private void OnColumnsChanged() { if (owner != null) { owner.OnColumnsChanged(); } } /// <devdoc> /// <para>Removes a <see cref='System.Web.UI.WebControls.DataGridColumn'/> from the collection at the specified /// index.</para> /// </devdoc> public void RemoveAt(int index) { if ((index >= 0) && (index < Count)) { columns.RemoveAt(index); OnColumnsChanged(); } else { throw new ArgumentOutOfRangeException("index"); } } /// <devdoc> /// <para>Removes the specified <see cref='System.Web.UI.WebControls.DataGridColumn'/> from the collection.</para> /// </devdoc> public void Remove(DataGridColumn column) { int index = IndexOf(column); if (index >= 0) { RemoveAt(index); } } /// <internalonly/> /// <devdoc> /// Return true if tracking state changes. /// </devdoc> bool IStateManager.IsTrackingViewState { get { return marked; } } /// <internalonly/> /// <devdoc> /// Load previously saved state. /// </devdoc> void IStateManager.LoadViewState(object savedState) { if (savedState != null) { object[] columnsState = (object[])savedState; if (columnsState.Length == columns.Count) { for (int i = 0; i < columnsState.Length; i++) { if (columnsState[i] != null) { ((IStateManager)columns[i]).LoadViewState(columnsState[i]); } } } } } /// <internalonly/> /// <devdoc> /// Start tracking state changes. /// </devdoc> void IStateManager.TrackViewState() { marked = true; int columnCount = columns.Count; for (int i = 0; i < columnCount; i++) { ((IStateManager)columns[i]).TrackViewState(); } } /// <internalonly/> /// <devdoc> /// Return object containing state changes. /// </devdoc> object IStateManager.SaveViewState() { int columnCount = columns.Count; object[] columnsState = new object[columnCount]; bool savedState = false; for (int i = 0; i < columnCount; i++) { columnsState[i] = ((IStateManager)columns[i]).SaveViewState(); if (columnsState[i] != null) savedState = true; } return savedState ? columnsState : null; } } }
using System; using System.ComponentModel; using System.IO; using System.Threading; using System.Threading.Tasks; using Foundation; using UIKit; using RectangleF = CoreGraphics.CGRect; namespace Xamarin.Forms.Platform.iOS { public static class ImageExtensions { public static UIViewContentMode ToUIViewContentMode(this Aspect aspect) { switch (aspect) { case Aspect.AspectFill: return UIViewContentMode.ScaleAspectFill; case Aspect.Fill: return UIViewContentMode.ScaleToFill; case Aspect.AspectFit: default: return UIViewContentMode.ScaleAspectFit; } } } public class ImageRenderer : ViewRenderer<Image, UIImageView> { ImageSource _oldSource; bool _isDisposed; IElementController ElementController => Element as IElementController; protected override void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { UIImage oldUIImage; if (Control != null && (oldUIImage = Control.Image) != null) { oldUIImage.Dispose(); oldUIImage = null; } } _oldSource = null; _isDisposed = true; base.Dispose(disposing); } protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { if (Control == null) { var imageView = new UIImageView(RectangleF.Empty); imageView.ContentMode = UIViewContentMode.ScaleAspectFit; imageView.ClipsToBounds = true; SetNativeControl(imageView); } if (e.NewElement != null) { SetAspect(); SetImage(e.OldElement?.Source); SetOpacity(); } base.OnElementChanged(e); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == Image.SourceProperty.PropertyName) SetImage(_oldSource); else if (e.PropertyName == Image.IsOpaqueProperty.PropertyName) SetOpacity(); else if (e.PropertyName == Image.AspectProperty.PropertyName) SetAspect(); } void SetAspect() { Control.ContentMode = Element.Aspect.ToUIViewContentMode(); } async void SetImage(ImageSource oldSource) { var source = Element.Source; if (oldSource != null) { if (Equals(oldSource, source)) return; if (oldSource is FileImageSource && source is FileImageSource && ((FileImageSource)oldSource).File == ((FileImageSource)source).File) return; Control.Image = null; } IImageSourceHandler handler; ((IImageController)Element).SetIsLoading(true); if (source != null && (handler = Registrar.Registered.GetHandler<IImageSourceHandler>(source.GetType())) != null) { UIImage uiimage; try { uiimage = await handler.LoadImageAsync(source, scale: (float)UIScreen.MainScreen.Scale); } catch (OperationCanceledException) { uiimage = null; } var imageView = Control; if (imageView != null) { imageView.Image = uiimage; _oldSource = uiimage == null ? null : source; } else { _oldSource = null; } if (!_isDisposed) ((IVisualElementController)Element).NativeSizeChanged(); } else { Control.Image = null; _oldSource = null; } if (!_isDisposed) ((IImageController)Element).SetIsLoading(false); } void SetOpacity() { Control.Opaque = Element.IsOpaque; } } public interface IImageSourceHandler : IRegisterable { Task<UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1); } public sealed class FileImageSourceHandler : IImageSourceHandler { public Task<UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1f) { UIImage image = null; var filesource = imagesource as FileImageSource; if (filesource != null) { var file = filesource.File; if (!string.IsNullOrEmpty(file)) image = File.Exists(file) ? new UIImage(file) : UIImage.FromBundle(file); } return Task.FromResult(image); } } public sealed class StreamImagesourceHandler : IImageSourceHandler { public async Task<UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1f) { UIImage image = null; var streamsource = imagesource as StreamImageSource; if (streamsource != null && streamsource.Stream != null) { using (var streamImage = await ((IStreamImageSource)streamsource).GetStreamAsync(cancelationToken).ConfigureAwait(false)) { if (streamImage != null) image = UIImage.LoadFromData(NSData.FromStream(streamImage), scale); } } return image; } } public sealed class ImageLoaderSourceHandler : IImageSourceHandler { public async Task<UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default(CancellationToken), float scale = 1f) { UIImage image = null; var imageLoader = imagesource as UriImageSource; if (imageLoader != null && imageLoader.Uri != null) { using (var streamImage = await imageLoader.GetStreamAsync(cancelationToken).ConfigureAwait(false)) { if (streamImage != null) image = UIImage.LoadFromData(NSData.FromStream(streamImage), scale); } } return image; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.Archiving { public sealed class ArchiveTests : IClassFixture<IntegrationTestContext<TestableStartup<TelevisionDbContext>, TelevisionDbContext>> { private readonly IntegrationTestContext<TestableStartup<TelevisionDbContext>, TelevisionDbContext> _testContext; private readonly TelevisionFakers _fakers = new(); public ArchiveTests(IntegrationTestContext<TestableStartup<TelevisionDbContext>, TelevisionDbContext> testContext) { _testContext = testContext; testContext.UseController<TelevisionNetworksController>(); testContext.UseController<TelevisionStationsController>(); testContext.UseController<TelevisionBroadcastsController>(); testContext.UseController<BroadcastCommentsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceDefinition<TelevisionBroadcastDefinition>(); }); } [Fact] public async Task Can_get_archived_resource_by_ID() { // Arrange TelevisionBroadcast broadcast = _fakers.TelevisionBroadcast.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(broadcast); await dbContext.SaveChangesAsync(); }); string route = $"/televisionBroadcasts/{broadcast.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(broadcast.StringId); responseDocument.Data.SingleValue.Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeCloseTo(broadcast.ArchivedAt.GetValueOrDefault()); } [Fact] public async Task Can_get_unarchived_resource_by_ID() { // Arrange TelevisionBroadcast broadcast = _fakers.TelevisionBroadcast.Generate(); broadcast.ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(broadcast); await dbContext.SaveChangesAsync(); }); string route = $"/televisionBroadcasts/{broadcast.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(broadcast.StringId); responseDocument.Data.SingleValue.Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeNull(); } [Fact] public async Task Get_primary_resources_excludes_archived() { // Arrange List<TelevisionBroadcast> broadcasts = _fakers.TelevisionBroadcast.Generate(2); broadcasts[1].ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<TelevisionBroadcast>(); dbContext.Broadcasts.AddRange(broadcasts); await dbContext.SaveChangesAsync(); }); const string route = "/televisionBroadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(broadcasts[1].StringId); responseDocument.Data.ManyValue[0].Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeNull(); } [Fact] public async Task Get_primary_resources_with_filter_includes_archived() { // Arrange List<TelevisionBroadcast> broadcasts = _fakers.TelevisionBroadcast.Generate(2); broadcasts[1].ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<TelevisionBroadcast>(); dbContext.Broadcasts.AddRange(broadcasts); await dbContext.SaveChangesAsync(); }); const string route = "/televisionBroadcasts?filter=or(equals(archivedAt,null),not(equals(archivedAt,null)))"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(broadcasts[0].StringId); responseDocument.Data.ManyValue[0].Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeCloseTo(broadcasts[0].ArchivedAt.GetValueOrDefault()); responseDocument.Data.ManyValue[1].Id.Should().Be(broadcasts[1].StringId); responseDocument.Data.ManyValue[1].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_primary_resource_by_ID_with_include_excludes_archived() { // Arrange TelevisionStation station = _fakers.TelevisionStation.Generate(); station.Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); station.Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Stations.Add(station); await dbContext.SaveChangesAsync(); }); string route = $"/televisionStations/{station.StringId}?include=broadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(station.StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Id.Should().Be(station.Broadcasts.ElementAt(1).StringId); responseDocument.Included[0].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_primary_resource_by_ID_with_include_and_filter_includes_archived() { // Arrange TelevisionStation station = _fakers.TelevisionStation.Generate(); station.Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); station.Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Stations.Add(station); await dbContext.SaveChangesAsync(); }); string route = $"/televisionStations/{station.StringId}?include=broadcasts&filter[broadcasts]=or(equals(archivedAt,null),not(equals(archivedAt,null)))"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); DateTimeOffset archivedAt0 = station.Broadcasts.ElementAt(0).ArchivedAt.GetValueOrDefault(); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(station.StringId); responseDocument.Included.Should().HaveCount(2); responseDocument.Included[0].Id.Should().Be(station.Broadcasts.ElementAt(0).StringId); responseDocument.Included[0].Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeCloseTo(archivedAt0); responseDocument.Included[1].Id.Should().Be(station.Broadcasts.ElementAt(1).StringId); responseDocument.Included[1].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_secondary_resource_includes_archived() { // Arrange BroadcastComment comment = _fakers.BroadcastComment.Generate(); comment.AppliesTo = _fakers.TelevisionBroadcast.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Comments.Add(comment); await dbContext.SaveChangesAsync(); }); string route = $"/broadcastComments/{comment.StringId}/appliesTo"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); DateTimeOffset archivedAt = comment.AppliesTo.ArchivedAt.GetValueOrDefault(); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(comment.AppliesTo.StringId); responseDocument.Data.SingleValue.Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeCloseTo(archivedAt); } [Fact] public async Task Get_secondary_resources_excludes_archived() { // Arrange TelevisionStation station = _fakers.TelevisionStation.Generate(); station.Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); station.Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Stations.Add(station); await dbContext.SaveChangesAsync(); }); string route = $"/televisionStations/{station.StringId}/broadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(station.Broadcasts.ElementAt(1).StringId); responseDocument.Data.ManyValue[0].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_secondary_resources_with_filter_includes_archived() { // Arrange TelevisionStation station = _fakers.TelevisionStation.Generate(); station.Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); station.Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Stations.Add(station); await dbContext.SaveChangesAsync(); }); string route = $"/televisionStations/{station.StringId}/broadcasts?filter=or(equals(archivedAt,null),not(equals(archivedAt,null)))"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); DateTimeOffset archivedAt0 = station.Broadcasts.ElementAt(0).ArchivedAt.GetValueOrDefault(); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(station.Broadcasts.ElementAt(0).StringId); responseDocument.Data.ManyValue[0].Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeCloseTo(archivedAt0); responseDocument.Data.ManyValue[1].Id.Should().Be(station.Broadcasts.ElementAt(1).StringId); responseDocument.Data.ManyValue[1].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_secondary_resource_by_ID_with_include_excludes_archived() { // Arrange TelevisionNetwork network = _fakers.TelevisionNetwork.Generate(); network.Stations = _fakers.TelevisionStation.Generate(1).ToHashSet(); network.Stations.ElementAt(0).Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); network.Stations.ElementAt(0).Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Networks.Add(network); await dbContext.SaveChangesAsync(); }); string route = $"/televisionNetworks/{network.StringId}/stations?include=broadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(network.Stations.ElementAt(0).StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Id.Should().Be(network.Stations.ElementAt(0).Broadcasts.ElementAt(1).StringId); responseDocument.Included[0].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_secondary_resource_by_ID_with_include_and_filter_includes_archived() { TelevisionNetwork network = _fakers.TelevisionNetwork.Generate(); network.Stations = _fakers.TelevisionStation.Generate(1).ToHashSet(); network.Stations.ElementAt(0).Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); network.Stations.ElementAt(0).Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Networks.Add(network); await dbContext.SaveChangesAsync(); }); string route = $"/televisionNetworks/{network.StringId}/stations?include=broadcasts&filter[broadcasts]=or(equals(archivedAt,null),not(equals(archivedAt,null)))"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); DateTimeOffset archivedAt0 = network.Stations.ElementAt(0).Broadcasts.ElementAt(0).ArchivedAt.GetValueOrDefault(); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(network.Stations.ElementAt(0).StringId); responseDocument.Included.Should().HaveCount(2); responseDocument.Included[0].Id.Should().Be(network.Stations.ElementAt(0).Broadcasts.ElementAt(0).StringId); responseDocument.Included[0].Attributes["archivedAt"].As<DateTimeOffset?>().Should().BeCloseTo(archivedAt0); responseDocument.Included[1].Id.Should().Be(network.Stations.ElementAt(0).Broadcasts.ElementAt(1).StringId); responseDocument.Included[1].Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Get_ToMany_relationship_excludes_archived() { // Arrange TelevisionStation station = _fakers.TelevisionStation.Generate(); station.Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); station.Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Stations.Add(station); await dbContext.SaveChangesAsync(); }); string route = $"/televisionStations/{station.StringId}/relationships/broadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(station.Broadcasts.ElementAt(1).StringId); } [Fact] public async Task Get_ToMany_relationship_with_filter_includes_archived() { // Arrange TelevisionStation station = _fakers.TelevisionStation.Generate(); station.Broadcasts = _fakers.TelevisionBroadcast.Generate(2).ToHashSet(); station.Broadcasts.ElementAt(1).ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Stations.Add(station); await dbContext.SaveChangesAsync(); }); string route = $"/televisionStations/{station.StringId}/relationships/broadcasts?filter=or(equals(archivedAt,null),not(equals(archivedAt,null)))"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(station.Broadcasts.ElementAt(0).StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(station.Broadcasts.ElementAt(1).StringId); } [Fact] public async Task Can_create_unarchived_resource() { // Arrange TelevisionBroadcast newBroadcast = _fakers.TelevisionBroadcast.Generate(); var requestBody = new { data = new { type = "televisionBroadcasts", attributes = new { title = newBroadcast.Title, airedAt = newBroadcast.AiredAt } } }; const string route = "/televisionBroadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes["title"].Should().Be(newBroadcast.Title); responseDocument.Data.SingleValue.Attributes["airedAt"].As<DateTimeOffset>().Should().BeCloseTo(newBroadcast.AiredAt); responseDocument.Data.SingleValue.Attributes["archivedAt"].Should().BeNull(); } [Fact] public async Task Cannot_create_archived_resource() { // Arrange TelevisionBroadcast newBroadcast = _fakers.TelevisionBroadcast.Generate(); var requestBody = new { data = new { type = "televisionBroadcasts", attributes = new { title = newBroadcast.Title, airedAt = newBroadcast.AiredAt, archivedAt = newBroadcast.ArchivedAt } } }; const string route = "/televisionBroadcasts"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("Television broadcasts cannot be created in archived state."); error.Detail.Should().BeNull(); } [Fact] public async Task Can_archive_resource() { // Arrange TelevisionBroadcast existingBroadcast = _fakers.TelevisionBroadcast.Generate(); existingBroadcast.ArchivedAt = null; DateTimeOffset newArchivedAt = _fakers.TelevisionBroadcast.Generate().ArchivedAt!.Value; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(existingBroadcast); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "televisionBroadcasts", id = existingBroadcast.StringId, attributes = new { archivedAt = newArchivedAt } } }; string route = $"/televisionBroadcasts/{existingBroadcast.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { TelevisionBroadcast broadcastInDatabase = await dbContext.Broadcasts.FirstWithIdAsync(existingBroadcast.Id); broadcastInDatabase.ArchivedAt.Should().BeCloseTo(newArchivedAt); }); } [Fact] public async Task Can_unarchive_resource() { // Arrange TelevisionBroadcast broadcast = _fakers.TelevisionBroadcast.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(broadcast); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "televisionBroadcasts", id = broadcast.StringId, attributes = new { archivedAt = (DateTimeOffset?)null } } }; string route = $"/televisionBroadcasts/{broadcast.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { TelevisionBroadcast broadcastInDatabase = await dbContext.Broadcasts.FirstWithIdAsync(broadcast.Id); broadcastInDatabase.ArchivedAt.Should().BeNull(); }); } [Fact] public async Task Cannot_shift_archive_date() { // Arrange TelevisionBroadcast broadcast = _fakers.TelevisionBroadcast.Generate(); DateTimeOffset? newArchivedAt = _fakers.TelevisionBroadcast.Generate().ArchivedAt; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(broadcast); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "televisionBroadcasts", id = broadcast.StringId, attributes = new { archivedAt = newArchivedAt } } }; string route = $"/televisionBroadcasts/{broadcast.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("Archive date of television broadcasts cannot be shifted. Unarchive it first."); error.Detail.Should().BeNull(); } [Fact] public async Task Can_delete_archived_resource() { // Arrange TelevisionBroadcast broadcast = _fakers.TelevisionBroadcast.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(broadcast); await dbContext.SaveChangesAsync(); }); string route = $"/televisionBroadcasts/{broadcast.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { TelevisionBroadcast broadcastInDatabase = await dbContext.Broadcasts.FirstWithIdOrDefaultAsync(broadcast.Id); broadcastInDatabase.Should().BeNull(); }); } [Fact] public async Task Cannot_delete_unarchived_resource() { // Arrange TelevisionBroadcast broadcast = _fakers.TelevisionBroadcast.Generate(); broadcast.ArchivedAt = null; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Broadcasts.Add(broadcast); await dbContext.SaveChangesAsync(); }); string route = $"/televisionBroadcasts/{broadcast.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Forbidden); error.Title.Should().Be("Television broadcasts must first be archived before they can be deleted."); error.Detail.Should().BeNull(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.ObjectModel; using System.Diagnostics; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Net; using System.Net.Cache; using System.Net.Security; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Security; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Permissions; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Text; using System.Threading; class HttpChannelFactory<TChannel> : TransportChannelFactory<TChannel>, IHttpTransportFactorySettings { static bool httpWebRequestWebPermissionDenied = false; static RequestCachePolicy requestCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); readonly ClientWebSocketFactory clientWebSocketFactory; bool allowCookies; AuthenticationSchemes authenticationScheme; HttpCookieContainerManager httpCookieContainerManager; // Double-checked locking pattern requires volatile for read/write synchronization volatile MruCache<Uri, Uri> credentialCacheUriPrefixCache; bool decompressionEnabled; // Double-checked locking pattern requires volatile for read/write synchronization [Fx.Tag.SecurityNote(Critical = "This cache stores strings that contain domain/user name/password. Must not be settable from PT code.")] [SecurityCritical] volatile MruCache<string, string> credentialHashCache; [Fx.Tag.SecurityNote(Critical = "This hash algorithm takes strings that contain domain/user name/password. Must not be settable from PT code.")] [SecurityCritical] HashAlgorithm hashAlgorithm; bool keepAliveEnabled; int maxBufferSize; IWebProxy proxy; WebProxyFactory proxyFactory; SecurityCredentialsManager channelCredentials; SecurityTokenManager securityTokenManager; TransferMode transferMode; ISecurityCapabilities securityCapabilities; WebSocketTransportSettings webSocketSettings; ConnectionBufferPool bufferPool; Lazy<string> webSocketSoapContentType; internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory()) { // validate setting interactions if (bindingElement.TransferMode == TransferMode.Buffered) { if (bindingElement.MaxReceivedMessageSize > int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", SR.GetString(SR.MaxReceivedMessageSizeMustBeInIntegerRange))); } if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.GetString(SR.MaxBufferSizeMustMatchMaxReceivedMessageSize)); } } else { if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.GetString(SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize)); } } if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) && bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.GetString( SR.HttpAuthDoesNotSupportRequestStreaming)); } this.allowCookies = bindingElement.AllowCookies; #pragma warning disable 618 if (!this.allowCookies) { Collection<HttpCookieContainerBindingElement> httpCookieContainerBindingElements = context.BindingParameters.FindAll<HttpCookieContainerBindingElement>(); if (httpCookieContainerBindingElements.Count > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MultipleCCbesInParameters, typeof(HttpCookieContainerBindingElement)))); } if (httpCookieContainerBindingElements.Count == 1) { this.allowCookies = true; context.BindingParameters.Remove<HttpCookieContainerBindingElement>(); } } #pragma warning restore 618 if (this.allowCookies) { this.httpCookieContainerManager = new HttpCookieContainerManager(); } if (!bindingElement.AuthenticationScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.HttpRequiresSingleAuthScheme, bindingElement.AuthenticationScheme)); } this.authenticationScheme = bindingElement.AuthenticationScheme; this.decompressionEnabled = bindingElement.DecompressionEnabled; this.keepAliveEnabled = bindingElement.KeepAliveEnabled; this.maxBufferSize = bindingElement.MaxBufferSize; this.transferMode = bindingElement.TransferMode; if (bindingElement.Proxy != null) { this.proxy = bindingElement.Proxy; } else if (bindingElement.ProxyAddress != null) { if (bindingElement.UseDefaultWebProxy) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress))); } if (bindingElement.ProxyAuthenticationScheme == AuthenticationSchemes.Anonymous) { this.proxy = new WebProxy(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal); } else { this.proxy = null; this.proxyFactory = new WebProxyFactory(bindingElement.ProxyAddress, bindingElement.BypassProxyOnLocal, bindingElement.ProxyAuthenticationScheme); } } else if (!bindingElement.UseDefaultWebProxy) { this.proxy = new WebProxy(); } this.channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>(); this.securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context); this.webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings); int webSocketBufferSize = WebSocketHelper.ComputeClientBufferSize(this.MaxReceivedMessageSize); this.bufferPool = new ConnectionBufferPool(webSocketBufferSize); Collection<ClientWebSocketFactory> clientWebSocketFactories = context.BindingParameters.FindAll<ClientWebSocketFactory>(); if (clientWebSocketFactories.Count > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument( "context", SR.GetString(SR.MultipleClientWebSocketFactoriesSpecified, typeof(BindingContext).Name, typeof(ClientWebSocketFactory).Name)); } else { this.clientWebSocketFactory = clientWebSocketFactories.Count == 0 ? null : clientWebSocketFactories[0]; } this.webSocketSoapContentType = new Lazy<string>(() => { return this.MessageEncoderFactory.CreateSessionEncoder().ContentType; }, LazyThreadSafetyMode.ExecutionAndPublication); } public bool AllowCookies { get { return this.allowCookies; } } public AuthenticationSchemes AuthenticationScheme { get { return this.authenticationScheme; } } public bool DecompressionEnabled { get { return this.decompressionEnabled; } } public virtual bool IsChannelBindingSupportEnabled { get { return false; } } public bool KeepAliveEnabled { get { return this.keepAliveEnabled; } } public SecurityTokenManager SecurityTokenManager { get { return this.securityTokenManager; } } public int MaxBufferSize { get { return maxBufferSize; } } public IWebProxy Proxy { get { return this.proxy; } } public TransferMode TransferMode { get { return transferMode; } } public override string Scheme { get { return Uri.UriSchemeHttp; } } public WebSocketTransportSettings WebSocketSettings { get { return this.webSocketSettings; } } internal string WebSocketSoapContentType { get { return this.webSocketSoapContentType.Value; } } protected ConnectionBufferPool WebSocketBufferPool { get { return this.bufferPool; } } // must be called under lock (this.credentialHashCache) HashAlgorithm HashAlgorithm { [SecurityCritical] get { if (this.hashAlgorithm == null) { this.hashAlgorithm = CryptoHelper.CreateHashAlgorithm(SecurityAlgorithms.Sha1Digest); } else { this.hashAlgorithm.Initialize(); } return this.hashAlgorithm; } } int IHttpTransportFactorySettings.MaxBufferSize { get { return MaxBufferSize; } } TransferMode IHttpTransportFactorySettings.TransferMode { get { return TransferMode; } } protected ClientWebSocketFactory ClientWebSocketFactory { get { return this.clientWebSocketFactory; } } public override T GetProperty<T>() { if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)this.securityCapabilities; } if (typeof(T) == typeof(IHttpCookieContainerManager)) { return (T)(object)this.GetHttpCookieContainerManager(); } return base.GetProperty<T>(); } [PermissionSet(SecurityAction.Demand, Unrestricted = true), SecuritySafeCritical] [MethodImpl(MethodImplOptions.NoInlining)] private HttpCookieContainerManager GetHttpCookieContainerManager() { return this.httpCookieContainerManager; } internal virtual SecurityMessageProperty CreateReplySecurityProperty(HttpWebRequest request, HttpWebResponse response) { // Don't pull in System.Authorization if we don't need to! if (!response.IsMutuallyAuthenticated) { return null; } return CreateMutuallyAuthenticatedReplySecurityProperty(response); } internal Exception CreateToMustEqualViaException(Uri to, Uri via) { return new ArgumentException(SR.GetString(SR.HttpToMustEqualVia, to, via)); } [MethodImpl(MethodImplOptions.NoInlining)] SecurityMessageProperty CreateMutuallyAuthenticatedReplySecurityProperty(HttpWebResponse response) { string spn = AuthenticationManager.CustomTargetNameDictionary[response.ResponseUri.AbsoluteUri]; if (spn == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.HttpSpnNotFound, response.ResponseUri))); } ReadOnlyCollection<IAuthorizationPolicy> spnPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(spn); SecurityMessageProperty remoteSecurity = new SecurityMessageProperty(); remoteSecurity.TransportToken = new SecurityTokenSpecification(null, spnPolicies); remoteSecurity.ServiceSecurityContext = new ServiceSecurityContext(spnPolicies); return remoteSecurity; } internal override int GetMaxBufferSize() { return MaxBufferSize; } SecurityTokenProviderContainer CreateAndOpenTokenProvider(TimeSpan timeout, AuthenticationSchemes authenticationScheme, EndpointAddress target, Uri via, ChannelParameterCollection channelParameters) { SecurityTokenProvider tokenProvider = null; switch (authenticationScheme) { case AuthenticationSchemes.Anonymous: break; case AuthenticationSchemes.Basic: tokenProvider = TransportSecurityHelpers.GetUserNameTokenProvider(this.SecurityTokenManager, target, via, this.Scheme, authenticationScheme, channelParameters); break; case AuthenticationSchemes.Negotiate: case AuthenticationSchemes.Ntlm: tokenProvider = TransportSecurityHelpers.GetSspiTokenProvider(this.SecurityTokenManager, target, via, this.Scheme, authenticationScheme, channelParameters); break; case AuthenticationSchemes.Digest: tokenProvider = TransportSecurityHelpers.GetDigestTokenProvider(this.SecurityTokenManager, target, via, this.Scheme, authenticationScheme, channelParameters); break; default: // The setter for this property should prevent this. throw Fx.AssertAndThrow("CreateAndOpenTokenProvider: Invalid authentication scheme"); } SecurityTokenProviderContainer result; if (tokenProvider != null) { result = new SecurityTokenProviderContainer(tokenProvider); result.Open(timeout); } else { result = null; } return result; } protected virtual void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via) { base.ValidateScheme(via); if (this.MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via)); } } protected override TChannel OnCreateChannel(EndpointAddress remoteAddress, Uri via) { EndpointAddress httpRemoteAddress = remoteAddress != null && WebSocketHelper.IsWebSocketUri(remoteAddress.Uri) ? new EndpointAddress(WebSocketHelper.NormalizeWsSchemeWithHttpScheme(remoteAddress.Uri), remoteAddress) : remoteAddress; Uri httpVia = WebSocketHelper.IsWebSocketUri(via) ? WebSocketHelper.NormalizeWsSchemeWithHttpScheme(via) : via; return this.OnCreateChannelCore(httpRemoteAddress, httpVia); } protected virtual TChannel OnCreateChannelCore(EndpointAddress remoteAddress, Uri via) { ValidateCreateChannelParameters(remoteAddress, via); this.ValidateWebSocketTransportUsage(); if (typeof(TChannel) == typeof(IRequestChannel)) { return (TChannel)(object)new HttpRequestChannel((HttpChannelFactory<IRequestChannel>)(object)this, remoteAddress, via, ManualAddressing); } else { return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, this.clientWebSocketFactory, remoteAddress, via, this.WebSocketBufferPool); } } protected void ValidateWebSocketTransportUsage() { Type channelType = typeof(TChannel); if (channelType == typeof(IRequestChannel) && this.WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString( SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage, typeof(TChannel), WebSocketTransportSettings.TransportUsageMethodName, typeof(WebSocketTransportSettings).Name, this.WebSocketSettings.TransportUsage))); } else if (channelType == typeof(IDuplexSessionChannel)) { if (this.WebSocketSettings.TransportUsage == WebSocketTransportUsage.Never) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString( SR.WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage, typeof(TChannel), WebSocketTransportSettings.TransportUsageMethodName, typeof(WebSocketTransportSettings).Name, this.WebSocketSettings.TransportUsage))); } else if (!WebSocketHelper.OSSupportsWebSockets() && this.ClientWebSocketFactory == null) { throw FxTrace.Exception.AsError(new PlatformNotSupportedException(SR.GetString(SR.WebSocketsClientSideNotSupported, typeof(ClientWebSocketFactory).FullName))); } } } [MethodImpl(MethodImplOptions.NoInlining)] void InitializeSecurityTokenManager() { if (this.channelCredentials == null) { this.channelCredentials = ClientCredentials.CreateDefaultCredentials(); } this.securityTokenManager = this.channelCredentials.CreateSecurityTokenManager(); } protected virtual bool IsSecurityTokenManagerRequired() { if (this.AuthenticationScheme != AuthenticationSchemes.Anonymous) { return true; } if (this.proxyFactory != null && this.proxyFactory.AuthenticationScheme != AuthenticationSchemes.Anonymous) { return true; } else { return false; } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { this.OnOpen(timeout); return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpen(TimeSpan timeout) { if (IsSecurityTokenManagerRequired()) { this.InitializeSecurityTokenManager(); } if (this.AllowCookies && !this.httpCookieContainerManager.IsInitialized) // We don't want to overwrite the CookieContainer if someone has set it already. { this.httpCookieContainerManager.CookieContainer = new CookieContainer(); } // we need to make sure System.Net will buffer faults (sent as 500 requests) up to our allowed size // Their value is in Kbytes and ours is in bytes. We round up so that the KB value is large enough to // encompass our MaxReceivedMessageSize. See MB#20860 and related for details if (!httpWebRequestWebPermissionDenied && HttpWebRequest.DefaultMaximumErrorResponseLength != -1) { int MaxReceivedMessageSizeKbytes; if (MaxBufferSize >= (int.MaxValue - 1024)) // make sure NCL doesn't overflow { MaxReceivedMessageSizeKbytes = -1; } else { MaxReceivedMessageSizeKbytes = (int)(MaxBufferSize / 1024); if (MaxReceivedMessageSizeKbytes * 1024 < MaxBufferSize) { MaxReceivedMessageSizeKbytes++; } } if (MaxReceivedMessageSizeKbytes == -1 || MaxReceivedMessageSizeKbytes > HttpWebRequest.DefaultMaximumErrorResponseLength) { try { HttpWebRequest.DefaultMaximumErrorResponseLength = MaxReceivedMessageSizeKbytes; } catch (SecurityException exception) { // CSDMain\33725 - setting DefaultMaximumErrorResponseLength should not fail HttpChannelFactory.OnOpen // if the user does not have the permission to do so. httpWebRequestWebPermissionDenied = true; DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning); } } } } protected override void OnClosed() { base.OnClosed(); if (this.bufferPool != null) { this.bufferPool.Close(); } } static internal void TraceResponseReceived(HttpWebResponse response, Message message, object receiver) { if (DiagnosticUtility.ShouldTraceVerbose) { if (response != null && response.ResponseUri != null) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.HttpResponseReceived, SR.GetString(SR.TraceCodeHttpResponseReceived), new StringTraceRecord("ResponseUri", response.ResponseUri.ToString()), receiver, null, message); } else { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.HttpResponseReceived, SR.GetString(SR.TraceCodeHttpResponseReceived), receiver, message); } } } [Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method AppendWindowsAuthenticationInfo to access the credential domain/user name/password.")] [SecurityCritical] [MethodImpl(MethodImplOptions.NoInlining)] string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel) { return SecurityUtils.AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel); } protected virtual string OnGetConnectionGroupPrefix(HttpWebRequest httpWebRequest, SecurityTokenContainer clientCertificateToken) { return string.Empty; } internal static bool IsWindowsAuth(AuthenticationSchemes authScheme) { Fx.Assert(authScheme.IsSingleton(), "authenticationScheme used in an Http(s)ChannelFactory must be a singleton value."); return authScheme == AuthenticationSchemes.Negotiate || authScheme == AuthenticationSchemes.Ntlm; } [Fx.Tag.SecurityNote(Critical = "Uses unsafe critical method AppendWindowsAuthenticationInfo to access the credential domain/user name/password.", Safe = "Uses the domain/user name/password to store and compute a hash. The store is SecurityCritical. The hash leaks but" + "the hash cannot be reversed to the domain/user name/password.")] [SecuritySafeCritical] string GetConnectionGroupName(HttpWebRequest httpWebRequest, NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel, SecurityTokenContainer clientCertificateToken) { if (this.credentialHashCache == null) { lock (ThisLock) { if (this.credentialHashCache == null) { this.credentialHashCache = new MruCache<string, string>(5); } } } // The following line is a work-around for VSWhidbey 558605. In particular, we need to isolate our // connection groups based on whether we are streaming the request. string inputString = TransferModeHelper.IsRequestStreamed(this.TransferMode) ? "streamed" : string.Empty; if (IsWindowsAuth(this.AuthenticationScheme)) { // for NTLM & Negotiate, System.Net doesn't pool connections by default. This is because // IIS doesn't re-authenticate NTLM connections (made for a perf reason), and HttpWebRequest // shared connections among multiple callers. // This causes Indigo a performance problem in turn. We mitigate this by (1) enabling // connection sharing for NTLM connections on our pool, and (2) scoping the pool we use // to be based on the NetworkCredential that is being used to authenticate the connection. // Therefore we're only sharing connections among the same Credential. // Setting this will fail in partial trust, and that's ok since this is an optimization. if (!httpWebRequestWebPermissionDenied) { try { httpWebRequest.UnsafeAuthenticatedConnectionSharing = true; } catch (SecurityException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); httpWebRequestWebPermissionDenied = true; } } inputString = AppendWindowsAuthenticationInfo(inputString, credential, authenticationLevel, impersonationLevel); } string prefix = this.OnGetConnectionGroupPrefix(httpWebRequest, clientCertificateToken); inputString = string.Concat(prefix, inputString); string credentialHash = null; // we have to lock around each call to TryGetValue since the MruCache modifies the // contents of it's mruList in a single-threaded manner underneath TryGetValue if (!string.IsNullOrEmpty(inputString)) { lock (this.credentialHashCache) { if (!this.credentialHashCache.TryGetValue(inputString, out credentialHash)) { byte[] inputBytes = new UTF8Encoding().GetBytes(inputString); byte[] digestBytes = this.HashAlgorithm.ComputeHash(inputBytes); credentialHash = Convert.ToBase64String(digestBytes); this.credentialHashCache.Add(inputString, credentialHash); } } } return credentialHash; } Uri GetCredentialCacheUriPrefix(Uri via) { Uri result; if (this.credentialCacheUriPrefixCache == null) { lock (ThisLock) { if (this.credentialCacheUriPrefixCache == null) { this.credentialCacheUriPrefixCache = new MruCache<Uri, Uri>(10); } } } lock (this.credentialCacheUriPrefixCache) { if (!this.credentialCacheUriPrefixCache.TryGetValue(via, out result)) { result = new UriBuilder(via.Scheme, via.Host, via.Port).Uri; this.credentialCacheUriPrefixCache.Add(via, result); } } return result; } // core code for creating an HttpWebRequest HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, NetworkCredential credential, TokenImpersonationLevel impersonationLevel, AuthenticationLevel authenticationLevel, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout, bool isWebSocketRequest) { Uri httpWebRequestUri = isWebSocketRequest ? WebSocketHelper.GetWebSocketUri(via) : via; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(httpWebRequestUri); Fx.Assert(httpWebRequest.Method.Equals("GET", StringComparison.OrdinalIgnoreCase), "the default HTTP method of HttpWebRequest should be 'Get'."); if (!isWebSocketRequest) { httpWebRequest.Method = "POST"; if (TransferModeHelper.IsRequestStreamed(TransferMode)) { httpWebRequest.SendChunked = true; httpWebRequest.AllowWriteStreamBuffering = false; } else { httpWebRequest.AllowWriteStreamBuffering = true; } } httpWebRequest.CachePolicy = requestCachePolicy; httpWebRequest.KeepAlive = this.keepAliveEnabled; if (this.decompressionEnabled) { httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } else { httpWebRequest.AutomaticDecompression = DecompressionMethods.None; } if (credential != null) { CredentialCache credentials = new CredentialCache(); credentials.Add(this.GetCredentialCacheUriPrefix(via), AuthenticationSchemesHelper.ToString(this.authenticationScheme), credential); httpWebRequest.Credentials = credentials; } httpWebRequest.AuthenticationLevel = authenticationLevel; httpWebRequest.ImpersonationLevel = impersonationLevel; string connectionGroupName = GetConnectionGroupName(httpWebRequest, credential, authenticationLevel, impersonationLevel, clientCertificateToken); X509CertificateEndpointIdentity remoteCertificateIdentity = to.Identity as X509CertificateEndpointIdentity; if (remoteCertificateIdentity != null) { connectionGroupName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}[{1}]", connectionGroupName, remoteCertificateIdentity.Certificates[0].Thumbprint); } if (!string.IsNullOrEmpty(connectionGroupName)) { httpWebRequest.ConnectionGroupName = connectionGroupName; } if (AuthenticationScheme == AuthenticationSchemes.Basic) { httpWebRequest.PreAuthenticate = true; } if (this.proxy != null) { httpWebRequest.Proxy = this.proxy; } else if (this.proxyFactory != null) { httpWebRequest.Proxy = this.proxyFactory.CreateWebProxy(httpWebRequest, proxyTokenProvider, timeout); } if (this.AllowCookies) { httpWebRequest.CookieContainer = this.httpCookieContainerManager.CookieContainer; } // we do this at the end so that we access the correct ServicePoint httpWebRequest.ServicePoint.UseNagleAlgorithm = false; return httpWebRequest; } void ApplyManualAddressing(ref EndpointAddress to, ref Uri via, Message message) { if (ManualAddressing) { Uri toHeader = message.Headers.To; if (toHeader == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ManualAddressingRequiresAddressedMessages)), message); } to = new EndpointAddress(toHeader); if (this.MessageVersion.Addressing == AddressingVersion.None) { via = toHeader; } } // now apply query string property object property; if (message.Properties.TryGetValue(HttpRequestMessageProperty.Name, out property)) { HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)property; if (!string.IsNullOrEmpty(requestProperty.QueryString)) { UriBuilder uriBuilder = new UriBuilder(via); if (requestProperty.QueryString.StartsWith("?", StringComparison.Ordinal)) { uriBuilder.Query = requestProperty.QueryString.Substring(1); } else { uriBuilder.Query = requestProperty.QueryString; } via = uriBuilder.Uri; } } } [MethodImpl(MethodImplOptions.NoInlining)] void CreateAndOpenTokenProvidersCore(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); tokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), this.AuthenticationScheme, to, via, channelParameters); if (this.proxyFactory != null) { proxyTokenProvider = CreateAndOpenTokenProvider(timeoutHelper.RemainingTime(), this.proxyFactory.AuthenticationScheme, to, via, channelParameters); } else { proxyTokenProvider = null; } } internal void CreateAndOpenTokenProviders(EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout, out SecurityTokenProviderContainer tokenProvider, out SecurityTokenProviderContainer proxyTokenProvider) { if (!IsSecurityTokenManagerRequired()) { tokenProvider = null; proxyTokenProvider = null; } else { CreateAndOpenTokenProvidersCore(to, via, channelParameters, timeout, out tokenProvider, out proxyTokenProvider); } } internal HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, SecurityTokenProviderContainer tokenProvider, SecurityTokenProviderContainer proxyTokenProvider, SecurityTokenContainer clientCertificateToken, TimeSpan timeout, bool isWebSocketRequest) { TokenImpersonationLevel impersonationLevel; AuthenticationLevel authenticationLevel; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); NetworkCredential credential = HttpChannelUtilities.GetCredential(this.authenticationScheme, tokenProvider, timeoutHelper.RemainingTime(), out impersonationLevel, out authenticationLevel); return GetWebRequest(to, via, credential, impersonationLevel, authenticationLevel, proxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime(), isWebSocketRequest); } internal static bool MapIdentity(EndpointAddress target, AuthenticationSchemes authenticationScheme) { if ((target.Identity == null) || (target.Identity is X509CertificateEndpointIdentity)) { return false; } return IsWindowsAuth(authenticationScheme); } bool MapIdentity(EndpointAddress target) { return MapIdentity(target, this.AuthenticationScheme); } protected class HttpRequestChannel : RequestChannel { // Double-checked locking pattern requires volatile for read/write synchronization volatile bool cleanupIdentity; HttpChannelFactory<IRequestChannel> factory; SecurityTokenProviderContainer tokenProvider; SecurityTokenProviderContainer proxyTokenProvider; ServiceModelActivity activity = null; ChannelParameterCollection channelParameters; public HttpRequestChannel(HttpChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing) : base(factory, to, via, manualAddressing) { this.factory = factory; } public HttpChannelFactory<IRequestChannel> Factory { get { return this.factory; } } internal ServiceModelActivity Activity { get { return this.activity; } } protected ChannelParameterCollection ChannelParameters { get { return this.channelParameters; } } public override T GetProperty<T>() { if (typeof(T) == typeof(ChannelParameterCollection)) { if (this.State == CommunicationState.Created) { lock (ThisLock) { if (this.channelParameters == null) { this.channelParameters = new ChannelParameterCollection(); } } } return (T)(object)this.channelParameters; } else { return base.GetProperty<T>(); } } void PrepareOpen() { if (Factory.MapIdentity(RemoteAddress)) { lock (ThisLock) { cleanupIdentity = HttpTransportSecurityHelpers.AddIdentityMapping(Via, RemoteAddress); } } } void CreateAndOpenTokenProviders(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!ManualAddressing) { Factory.CreateAndOpenTokenProviders(this.RemoteAddress, this.Via, this.channelParameters, timeoutHelper.RemainingTime(), out this.tokenProvider, out this.proxyTokenProvider); } } void CloseTokenProviders(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (this.tokenProvider != null) { tokenProvider.Close(timeoutHelper.RemainingTime()); } if (this.proxyTokenProvider != null) { proxyTokenProvider.Close(timeoutHelper.RemainingTime()); } } void AbortTokenProviders() { if (this.tokenProvider != null) { tokenProvider.Abort(); } if (this.proxyTokenProvider != null) { proxyTokenProvider.Abort(); } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { PrepareOpen(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); CreateAndOpenTokenProviders(timeoutHelper.RemainingTime()); return new CompletedAsyncResult(callback, state); } protected override void OnOpen(TimeSpan timeout) { PrepareOpen(); CreateAndOpenTokenProviders(timeout); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } void PrepareClose(bool aborting) { if (cleanupIdentity) { lock (ThisLock) { if (cleanupIdentity) { cleanupIdentity = false; HttpTransportSecurityHelpers.RemoveIdentityMapping(Via, RemoteAddress, !aborting); } } } } protected override void OnAbort() { PrepareClose(true); AbortTokenProviders(); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { IAsyncResult retval = null; using (ServiceModelActivity.BoundOperation(this.activity)) { PrepareClose(false); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); CloseTokenProviders(timeoutHelper.RemainingTime()); retval = base.BeginWaitForPendingRequests(timeoutHelper.RemainingTime(), callback, state); } ServiceModelActivity.Stop(this.activity); return retval; } protected override void OnEndClose(IAsyncResult result) { using (ServiceModelActivity.BoundOperation(this.activity)) { base.EndWaitForPendingRequests(result); } ServiceModelActivity.Stop(this.activity); } protected override void OnClose(TimeSpan timeout) { using (ServiceModelActivity.BoundOperation(this.activity)) { PrepareClose(false); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); CloseTokenProviders(timeoutHelper.RemainingTime()); base.WaitForPendingRequests(timeoutHelper.RemainingTime()); } ServiceModelActivity.Stop(this.activity); } protected override IAsyncRequest CreateAsyncRequest(Message message, AsyncCallback callback, object state) { if (DiagnosticUtility.ShouldUseActivity && this.activity == null) { this.activity = ServiceModelActivity.CreateActivity(); if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(this.activity.Id); } ServiceModelActivity.Start(this.activity, SR.GetString(SR.ActivityReceiveBytes, this.RemoteAddress.Uri.ToString()), ActivityType.ReceiveBytes); } return new HttpChannelAsyncRequest(this, callback, state); } protected override IRequest CreateRequest(Message message) { return new HttpChannelRequest(this, Factory); } public virtual HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper) { return GetWebRequest(to, via, null, ref timeoutHelper); } protected HttpWebRequest GetWebRequest(EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper) { SecurityTokenProviderContainer webRequestTokenProvider; SecurityTokenProviderContainer webRequestProxyTokenProvider; if (this.ManualAddressing) { this.Factory.CreateAndOpenTokenProviders(to, via, this.channelParameters, timeoutHelper.RemainingTime(), out webRequestTokenProvider, out webRequestProxyTokenProvider); } else { webRequestTokenProvider = this.tokenProvider; webRequestProxyTokenProvider = this.proxyTokenProvider; } try { return this.Factory.GetWebRequest(to, via, webRequestTokenProvider, webRequestProxyTokenProvider, clientCertificateToken, timeoutHelper.RemainingTime(), false); } finally { if (this.ManualAddressing) { if (webRequestTokenProvider != null) { webRequestTokenProvider.Abort(); } if (webRequestProxyTokenProvider != null) { webRequestProxyTokenProvider.Abort(); } } } } protected IAsyncResult BeginGetWebRequest( EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state) { return new GetWebRequestAsyncResult(this, to, via, clientCertificateToken, ref timeoutHelper, callback, state); } public virtual IAsyncResult BeginGetWebRequest( EndpointAddress to, Uri via, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state) { return BeginGetWebRequest(to, via, null, ref timeoutHelper, callback, state); } public virtual HttpWebRequest EndGetWebRequest(IAsyncResult result) { return GetWebRequestAsyncResult.End(result); } public virtual bool WillGetWebRequestCompleteSynchronously() { return ((this.tokenProvider == null) && !Factory.ManualAddressing); } internal virtual void OnWebRequestCompleted(HttpWebRequest request) { // empty } class HttpChannelRequest : IRequest { HttpRequestChannel channel; HttpChannelFactory<IRequestChannel> factory; EndpointAddress to; Uri via; HttpWebRequest webRequest; HttpAbortReason abortReason; ChannelBinding channelBinding; int webRequestCompleted; EventTraceActivity eventTraceActivity; public HttpChannelRequest(HttpRequestChannel channel, HttpChannelFactory<IRequestChannel> factory) { this.channel = channel; this.to = channel.RemoteAddress; this.via = channel.Via; this.factory = factory; } public void SendRequest(Message message, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); factory.ApplyManualAddressing(ref this.to, ref this.via, message); this.webRequest = channel.GetWebRequest(this.to, this.via, ref timeoutHelper); Message request = message; try { if (channel.State != CommunicationState.Opened) { // if we were aborted while getting our request or doing correlation, // we need to abort the web request and bail Cleanup(); channel.ThrowIfDisposedOrNotOpen(); } HttpChannelUtilities.SetRequestTimeout(this.webRequest, timeoutHelper.RemainingTime()); HttpOutput httpOutput = HttpOutput.CreateHttpOutput(this.webRequest, this.factory, request, this.factory.IsChannelBindingSupportEnabled); bool success = false; try { httpOutput.Send(timeoutHelper.RemainingTime()); this.channelBinding = httpOutput.TakeChannelBinding(); httpOutput.Close(); success = true; if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled) { this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); if (TD.MessageSentByTransportIsEnabled()) { TD.MessageSentByTransport(eventTraceActivity, this.to.Uri.AbsoluteUri); } } } finally { if (!success) { httpOutput.Abort(HttpAbortReason.Aborted); } } } finally { if (!object.ReferenceEquals(request, message)) { request.Close(); } } } void Cleanup() { if (this.webRequest != null) { HttpChannelUtilities.AbortRequest(this.webRequest); this.TryCompleteWebRequest(this.webRequest); } ChannelBindingUtility.Dispose(ref this.channelBinding); } public void Abort(RequestChannel channel) { Cleanup(); abortReason = HttpAbortReason.Aborted; } public void Fault(RequestChannel channel) { Cleanup(); } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104", Justification = "This is an old method from previous release.")] public Message WaitForReply(TimeSpan timeout) { if (TD.HttpResponseReceiveStartIsEnabled()) { TD.HttpResponseReceiveStart(this.eventTraceActivity); } HttpWebResponse response = null; WebException responseException = null; try { try { response = (HttpWebResponse)webRequest.GetResponse(); } catch (NullReferenceException nullReferenceException) { // workaround for Whidbey bug #558605 - only happens in streamed case. if (TransferModeHelper.IsRequestStreamed(this.factory.transferMode)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( HttpChannelUtilities.CreateNullReferenceResponseException(nullReferenceException)); } throw; } if (TD.MessageReceivedByTransportIsEnabled()) { TD.MessageReceivedByTransport(this.eventTraceActivity ?? EventTraceActivity.Empty, response.ResponseUri != null ? response.ResponseUri.AbsoluteUri : string.Empty, EventTraceActivity.GetActivityIdFromThread()); } if (DiagnosticUtility.ShouldTraceVerbose) { HttpChannelFactory<TChannel>.TraceResponseReceived(response, null, this); } } catch (WebException webException) { responseException = webException; response = HttpChannelUtilities.ProcessGetResponseWebException(webException, this.webRequest, abortReason); } HttpInput httpInput = HttpChannelUtilities.ValidateRequestReplyResponse(this.webRequest, response, this.factory, responseException, this.channelBinding); this.channelBinding = null; Message replyMessage = null; if (httpInput != null) { Exception exception = null; replyMessage = httpInput.ParseIncomingMessage(out exception); Fx.Assert(exception == null, "ParseIncomingMessage should not set an exception after parsing a response message."); if (replyMessage != null) { HttpChannelUtilities.AddReplySecurityProperty(this.factory, this.webRequest, response, replyMessage); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled && (eventTraceActivity != null)) { EventTraceActivityHelper.TryAttachActivity(replyMessage, eventTraceActivity); } } } this.TryCompleteWebRequest(this.webRequest); return replyMessage; } public void OnReleaseRequest() { this.TryCompleteWebRequest(this.webRequest); } void TryCompleteWebRequest(HttpWebRequest request) { if (request == null) { return; } if (Interlocked.CompareExchange(ref this.webRequestCompleted, 1, 0) == 0) { this.channel.OnWebRequestCompleted(request); } } } class HttpChannelAsyncRequest : TraceAsyncResult, IAsyncRequest { static AsyncCallback onProcessIncomingMessage = Fx.ThunkCallback(new AsyncCallback(OnParseIncomingMessage)); static AsyncCallback onGetResponse = Fx.ThunkCallback(new AsyncCallback(OnGetResponse)); static AsyncCallback onGetWebRequestCompleted; static AsyncCallback onSend = Fx.ThunkCallback(new AsyncCallback(OnSend)); static Action<object> onSendTimeout; ChannelBinding channelBinding; HttpChannelFactory<IRequestChannel> factory; HttpRequestChannel channel; HttpOutput httpOutput; HttpInput httpInput; Message message; Message requestMessage; Message replyMessage; HttpWebResponse response; HttpWebRequest request; object sendLock = new object(); IOThreadTimer sendTimer; TimeoutHelper timeoutHelper; EndpointAddress to; Uri via; HttpAbortReason abortReason; int webRequestCompleted; EventTraceActivity eventTraceActivity; public HttpChannelAsyncRequest(HttpRequestChannel channel, AsyncCallback callback, object state) : base(callback, state) { this.channel = channel; this.to = channel.RemoteAddress; this.via = channel.Via; this.factory = channel.Factory; } IOThreadTimer SendTimer { get { if (this.sendTimer == null) { if (onSendTimeout == null) { onSendTimeout = new Action<object>(OnSendTimeout); } this.sendTimer = new IOThreadTimer(onSendTimeout, this, false); } return this.sendTimer; } } public static void End(IAsyncResult result) { AsyncResult.End<HttpChannelAsyncRequest>(result); } public void BeginSendRequest(Message message, TimeSpan timeout) { this.message = this.requestMessage = message; this.timeoutHelper = new TimeoutHelper(timeout); if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled) { this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); } factory.ApplyManualAddressing(ref this.to, ref this.via, this.requestMessage); if (this.channel.WillGetWebRequestCompleteSynchronously()) { SetWebRequest(channel.GetWebRequest(this.to, this.via, ref this.timeoutHelper)); if (this.SendWebRequest()) { base.Complete(true); } } else { if (onGetWebRequestCompleted == null) { onGetWebRequestCompleted = Fx.ThunkCallback( new AsyncCallback(OnGetWebRequestCompletedCallback)); } IAsyncResult result = channel.BeginGetWebRequest( to, via, ref this.timeoutHelper, onGetWebRequestCompleted, this); if (result.CompletedSynchronously) { if (TD.MessageSentByTransportIsEnabled()) { TD.MessageSentByTransport(this.eventTraceActivity, this.to.Uri.AbsoluteUri); } if (this.OnGetWebRequestCompleted(result)) { base.Complete(true); } } } } static void OnGetWebRequestCompletedCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState; Exception completionException = null; bool completeSelf; try { completeSelf = thisPtr.OnGetWebRequestCompleted(result); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completeSelf = true; completionException = e; } if (completeSelf) { thisPtr.Complete(false, completionException); } } void AbortSend() { CancelSendTimer(); if (this.request != null) { this.TryCompleteWebRequest(this.request); this.abortReason = HttpAbortReason.TimedOut; httpOutput.Abort(this.abortReason); } } void CancelSendTimer() { lock (sendLock) { if (this.sendTimer != null) { this.sendTimer.Cancel(); this.sendTimer = null; } } } bool OnGetWebRequestCompleted(IAsyncResult result) { SetWebRequest(this.channel.EndGetWebRequest(result)); return this.SendWebRequest(); } bool SendWebRequest() { this.httpOutput = HttpOutput.CreateHttpOutput(this.request, this.factory, this.requestMessage, this.factory.IsChannelBindingSupportEnabled); bool success = false; try { bool result = false; SetSendTimeout(timeoutHelper.RemainingTime()); IAsyncResult asyncResult = httpOutput.BeginSend(timeoutHelper.RemainingTime(), onSend, this); success = true; if (asyncResult.CompletedSynchronously) { result = CompleteSend(asyncResult); } return result; } finally { if (!success) { this.httpOutput.Abort(HttpAbortReason.Aborted); if (!object.ReferenceEquals(this.message, this.requestMessage)) { this.requestMessage.Close(); } } } } bool CompleteSend(IAsyncResult result) { bool success = false; try { httpOutput.EndSend(result); this.channelBinding = httpOutput.TakeChannelBinding(); httpOutput.Close(); success = true; if (TD.MessageSentByTransportIsEnabled()) { TD.MessageSentByTransport(this.eventTraceActivity, this.to.Uri.AbsoluteUri); } } finally { if (!success) { httpOutput.Abort(HttpAbortReason.Aborted); } if (!object.ReferenceEquals(this.message, this.requestMessage)) { this.requestMessage.Close(); } } try { IAsyncResult getResponseResult; try { getResponseResult = request.BeginGetResponse(onGetResponse, this); } catch (NullReferenceException nullReferenceException) { // workaround for Whidbey bug #558605 - only happens in streamed case. if (TransferModeHelper.IsRequestStreamed(this.factory.transferMode)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( HttpChannelUtilities.CreateNullReferenceResponseException(nullReferenceException)); } throw; } if (getResponseResult.CompletedSynchronously) { return CompleteGetResponse(getResponseResult); } return false; } catch (IOException ioException) { throw TraceUtility.ThrowHelperError(new CommunicationException(ioException.Message, ioException), this.requestMessage); } catch (WebException webException) { throw TraceUtility.ThrowHelperError(new CommunicationException(webException.Message, webException), this.requestMessage); } catch (ObjectDisposedException objectDisposedException) { if (abortReason == HttpAbortReason.Aborted) { throw TraceUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.GetString(SR.HttpRequestAborted, to.Uri), objectDisposedException), this.requestMessage); } throw TraceUtility.ThrowHelperError(new TimeoutException(SR.GetString(SR.HttpRequestTimedOut, to.Uri, this.timeoutHelper.OriginalTimeout), objectDisposedException), this.requestMessage); } } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104", Justification = "This is an old method from previous release.")] bool CompleteGetResponse(IAsyncResult result) { using (ServiceModelActivity.BoundOperation(this.channel.Activity)) { HttpWebResponse response = null; WebException responseException = null; try { try { CancelSendTimer(); response = (HttpWebResponse)request.EndGetResponse(result); } catch (NullReferenceException nullReferenceException) { // workaround for Whidbey bug #558605 - only happens in streamed case. if (TransferModeHelper.IsRequestStreamed(this.factory.transferMode)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( HttpChannelUtilities.CreateNullReferenceResponseException(nullReferenceException)); } throw; } if (TD.MessageReceivedByTransportIsEnabled()) { TD.MessageReceivedByTransport( this.eventTraceActivity ?? EventTraceActivity.Empty, this.to.Uri.AbsoluteUri, EventTraceActivity.GetActivityIdFromThread()); } if (DiagnosticUtility.ShouldTraceVerbose) { HttpChannelFactory<TChannel>.TraceResponseReceived(response, this.message, this); } } catch (WebException webException) { responseException = webException; response = HttpChannelUtilities.ProcessGetResponseWebException(webException, request, abortReason); } return ProcessResponse(response, responseException); } } void Cleanup() { if (this.request != null) { HttpChannelUtilities.AbortRequest(this.request); this.TryCompleteWebRequest(this.request); } ChannelBindingUtility.Dispose(ref this.channelBinding); } void SetSendTimeout(TimeSpan timeout) { // We also set the timeout on the HttpWebRequest so that we can subsequently use it in the // exception message in the event of a timeout. HttpChannelUtilities.SetRequestTimeout(this.request, timeout); if (timeout == TimeSpan.MaxValue) { CancelSendTimer(); } else { SendTimer.Set(timeout); } } public void Abort(RequestChannel channel) { Cleanup(); abortReason = HttpAbortReason.Aborted; } public void Fault(RequestChannel channel) { Cleanup(); } void SetWebRequest(HttpWebRequest webRequest) { this.request = webRequest; if (channel.State != CommunicationState.Opened) { // if we were aborted while getting our request, we need to abort the web request and bail Cleanup(); channel.ThrowIfDisposedOrNotOpen(); } } public Message End() { HttpChannelAsyncRequest.End(this); return replyMessage; } bool ProcessResponse(HttpWebResponse response, WebException responseException) { this.httpInput = HttpChannelUtilities.ValidateRequestReplyResponse(this.request, response, this.factory, responseException, this.channelBinding); this.channelBinding = null; if (httpInput != null) { this.response = response; IAsyncResult result = httpInput.BeginParseIncomingMessage(onProcessIncomingMessage, this); if (!result.CompletedSynchronously) { return false; } CompleteParseIncomingMessage(result); } else { this.replyMessage = null; } this.TryCompleteWebRequest(this.request); return true; } void CompleteParseIncomingMessage(IAsyncResult result) { Exception exception = null; this.replyMessage = this.httpInput.EndParseIncomingMessage(result, out exception); Fx.Assert(exception == null, "ParseIncomingMessage should not set an exception after parsing a response message."); if (this.replyMessage != null) { HttpChannelUtilities.AddReplySecurityProperty(this.factory, this.request, this.response, this.replyMessage); } } static void OnParseIncomingMessage(IAsyncResult result) { if (result.CompletedSynchronously) { return; } HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState; Exception completionException = null; try { thisPtr.CompleteParseIncomingMessage(result); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisPtr.Complete(false, completionException); } static void OnSend(IAsyncResult result) { if (result.CompletedSynchronously) { return; } HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState; Exception completionException = null; bool completeSelf; try { completeSelf = thisPtr.CompleteSend(result); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completeSelf = true; completionException = e; } if (completeSelf) { thisPtr.Complete(false, completionException); } } static void OnSendTimeout(object state) { HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)state; thisPtr.AbortSend(); } [System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104", Justification = "This is an old method from previous release.")] static void OnGetResponse(IAsyncResult result) { if (result.CompletedSynchronously) { return; } HttpChannelAsyncRequest thisPtr = (HttpChannelAsyncRequest)result.AsyncState; Exception completionException = null; bool completeSelf; try { completeSelf = thisPtr.CompleteGetResponse(result); } catch (WebException webException) { completeSelf = true; completionException = new CommunicationException(webException.Message, webException); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completeSelf = true; completionException = e; } if (completeSelf) { thisPtr.Complete(false, completionException); } } public void OnReleaseRequest() { this.TryCompleteWebRequest(this.request); } void TryCompleteWebRequest(HttpWebRequest request) { if (request == null) { return; } if (Interlocked.CompareExchange(ref this.webRequestCompleted, 1, 0) == 0) { this.channel.OnWebRequestCompleted(request); } } } class GetWebRequestAsyncResult : AsyncResult { static AsyncCallback onGetSspiCredential; static AsyncCallback onGetUserNameCredential; SecurityTokenContainer clientCertificateToken; HttpChannelFactory<IRequestChannel> factory; SecurityTokenProviderContainer proxyTokenProvider; HttpWebRequest request; EndpointAddress to; TimeoutHelper timeoutHelper; SecurityTokenProviderContainer tokenProvider; Uri via; public GetWebRequestAsyncResult(HttpRequestChannel channel, EndpointAddress to, Uri via, SecurityTokenContainer clientCertificateToken, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state) : base(callback, state) { this.to = to; this.via = via; this.clientCertificateToken = clientCertificateToken; this.timeoutHelper = timeoutHelper; this.factory = channel.Factory; this.tokenProvider = channel.tokenProvider; this.proxyTokenProvider = channel.proxyTokenProvider; if (factory.ManualAddressing) { this.factory.CreateAndOpenTokenProviders(to, via, channel.channelParameters, timeoutHelper.RemainingTime(), out this.tokenProvider, out this.proxyTokenProvider); } bool completeSelf = false; IAsyncResult result = null; if (factory.AuthenticationScheme == AuthenticationSchemes.Anonymous) { SetupWebRequest(AuthenticationLevel.None, TokenImpersonationLevel.None, null); completeSelf = true; } else if (factory.AuthenticationScheme == AuthenticationSchemes.Basic) { if (onGetUserNameCredential == null) { onGetUserNameCredential = Fx.ThunkCallback(new AsyncCallback(OnGetUserNameCredential)); } result = TransportSecurityHelpers.BeginGetUserNameCredential( tokenProvider, timeoutHelper.RemainingTime(), onGetUserNameCredential, this); if (result.CompletedSynchronously) { CompleteGetUserNameCredential(result); completeSelf = true; } } else { if (onGetSspiCredential == null) { onGetSspiCredential = Fx.ThunkCallback(new AsyncCallback(OnGetSspiCredential)); } result = TransportSecurityHelpers.BeginGetSspiCredential( tokenProvider, timeoutHelper.RemainingTime(), onGetSspiCredential, this); if (result.CompletedSynchronously) { CompleteGetSspiCredential(result); completeSelf = true; } } if (completeSelf) { CloseTokenProvidersIfRequired(); base.Complete(true); } } public static HttpWebRequest End(IAsyncResult result) { GetWebRequestAsyncResult thisPtr = AsyncResult.End<GetWebRequestAsyncResult>(result); return thisPtr.request; } void CompleteGetUserNameCredential(IAsyncResult result) { NetworkCredential credential = TransportSecurityHelpers.EndGetUserNameCredential(result); SetupWebRequest(AuthenticationLevel.None, TokenImpersonationLevel.None, credential); } void CompleteGetSspiCredential(IAsyncResult result) { AuthenticationLevel authenticationLevel; TokenImpersonationLevel impersonationLevel; NetworkCredential credential = TransportSecurityHelpers.EndGetSspiCredential(result, out impersonationLevel, out authenticationLevel); if (factory.AuthenticationScheme == AuthenticationSchemes.Digest) { HttpChannelUtilities.ValidateDigestCredential(ref credential, impersonationLevel); } else if (factory.AuthenticationScheme == AuthenticationSchemes.Ntlm) { if (authenticationLevel == AuthenticationLevel.MutualAuthRequired) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.CredentialDisallowsNtlm))); } } SetupWebRequest(authenticationLevel, impersonationLevel, credential); } void SetupWebRequest(AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel, NetworkCredential credential) { this.request = factory.GetWebRequest(to, via, credential, impersonationLevel, authenticationLevel, this.proxyTokenProvider, this.clientCertificateToken, timeoutHelper.RemainingTime(), false); } void CloseTokenProvidersIfRequired() { if (this.factory.ManualAddressing) { if (this.tokenProvider != null) { tokenProvider.Abort(); } if (this.proxyTokenProvider != null) { proxyTokenProvider.Abort(); } } } static void OnGetSspiCredential(IAsyncResult result) { if (result.CompletedSynchronously) { return; } GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState; Exception completionException = null; try { thisPtr.CompleteGetSspiCredential(result); thisPtr.CloseTokenProvidersIfRequired(); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisPtr.Complete(false, completionException); } static void OnGetUserNameCredential(IAsyncResult result) { if (result.CompletedSynchronously) { return; } GetWebRequestAsyncResult thisPtr = (GetWebRequestAsyncResult)result.AsyncState; Exception completionException = null; try { thisPtr.CompleteGetUserNameCredential(result); thisPtr.CloseTokenProvidersIfRequired(); } #pragma warning suppress 56500 // [....], transferring exception to another thread catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisPtr.Complete(false, completionException); } } } class WebProxyFactory { Uri address; bool bypassOnLocal; AuthenticationSchemes authenticationScheme; public WebProxyFactory(Uri address, bool bypassOnLocal, AuthenticationSchemes authenticationScheme) { this.address = address; this.bypassOnLocal = bypassOnLocal; if (!authenticationScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.GetString(SR.HttpRequiresSingleAuthScheme, authenticationScheme)); } this.authenticationScheme = authenticationScheme; } internal AuthenticationSchemes AuthenticationScheme { get { return authenticationScheme; } } public IWebProxy CreateWebProxy(HttpWebRequest request, SecurityTokenProviderContainer tokenProvider, TimeSpan timeout) { WebProxy result = new WebProxy(this.address, this.bypassOnLocal); if (this.authenticationScheme != AuthenticationSchemes.Anonymous) { TokenImpersonationLevel impersonationLevel; AuthenticationLevel authenticationLevel; NetworkCredential credential = HttpChannelUtilities.GetCredential(this.authenticationScheme, tokenProvider, timeout, out impersonationLevel, out authenticationLevel); // The impersonation level for target auth is also used for proxy auth (by System.Net). Therefore, // fail if the level stipulated for proxy auth is more restrictive than that for target auth. if (!TokenImpersonationLevelHelper.IsGreaterOrEqual(impersonationLevel, request.ImpersonationLevel)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( SR.ProxyImpersonationLevelMismatch, impersonationLevel, request.ImpersonationLevel))); } // The authentication level for target auth is also used for proxy auth (by System.Net). // Therefore, fail if proxy auth requires mutual authentication but target auth does not. if ((authenticationLevel == AuthenticationLevel.MutualAuthRequired) && (request.AuthenticationLevel != AuthenticationLevel.MutualAuthRequired)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString( SR.ProxyAuthenticationLevelMismatch, authenticationLevel, request.AuthenticationLevel))); } CredentialCache credentials = new CredentialCache(); credentials.Add(this.address, AuthenticationSchemesHelper.ToString(this.authenticationScheme), credential); result.Credentials = credentials; } return result; } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using ASC.Files.Core; using ASC.Web.Core.Client.Bundling; using ASC.Web.Core.Files; using ASC.Web.Files.Classes; using ASC.Web.Files.Controls; using ASC.Web.Files.Resources; using ASC.Web.Studio; namespace ASC.Web.Files { public partial class FileChoice : MainPage, IStaticBundle { public static string Location { get { return FilesLinkUtility.FilesBaseAbsolutePath + "FileChoice.aspx"; } } public static string GetUrlForEditor { get { return Location + string.Format("?{0}=true&{1}={{{1}}}&{2}={{{2}}}", FromEditorParam, FilterExtParam, FileTypeParam); } } public static string GetUrl(string ext = null, bool fromEditor = false, FolderType? root = null, bool? thirdParty = null, FilterType? filterType = null, bool multiple = false, string successButton = null) { var args = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(ext = (ext ?? "").Trim().ToLower())) args.Add(FilterExtParam, ext); if (fromEditor) args.Add(FromEditorParam, "true"); if (root.HasValue) args.Add(RootParam, root.ToString()); if (thirdParty.HasValue) args.Add(ThirdPartyParam, thirdParty.Value.ToString().ToLower()); if (filterType.HasValue) args.Add(FileTypeParam, filterType.Value.ToString()); if (multiple) args.Add(MultiSelectParam, "true"); if (!string.IsNullOrEmpty(successButton = (successButton ?? "").Trim())) args.Add(SuccessButtonParam, successButton); return Location + "?" + string.Join("&", args.Select(arg => HttpUtility.HtmlEncode(arg.Key) + "=" + HttpUtility.HtmlEncode(arg.Value))); } public const string FilterExtParam = "fileExt"; public const string FromEditorParam = "editor"; public const string RootParam = "root"; public const string ThirdPartyParam = "thirdParty"; public const string FileTypeParam = "documentType"; public const string MultiSelectParam = "multiple"; public const string SuccessButtonParam = "ok"; protected string RequestExt { get { return (Request[FilterExtParam] ?? "").Trim().ToLower(); } } protected FilterType RequestType { get { FilterType filter; return Enum.TryParse(Request[FileTypeParam], out filter) ? filter : FilterType.None; } } protected bool FromEditor { get { return !string.IsNullOrEmpty(Request[FromEditorParam]); } } private bool OnlyFolder { get { return !string.IsNullOrEmpty(Request["onlyFolder"]); } } protected void Page_Load(object sender, EventArgs e) { Master.Master.DisabledSidePanel = true; Master.Master.DisabledTopStudioPanel = true; Master.Master .AddStaticStyles(GetStaticStyleSheet()) .AddStaticBodyScripts(GetStaticJavaScript()); var fileSelector = (FileSelector)LoadControl(FileSelector.Location); fileSelector.IsFlat = true; fileSelector.OnlyFolder = OnlyFolder; fileSelector.Multiple = (Request[MultiSelectParam] ?? "").Trim().ToLower() == "true"; var successButton = (Request[SuccessButtonParam] ?? "").Trim(); if (!string.IsNullOrEmpty(successButton)) fileSelector.SuccessButton = successButton; CommonContainerHolder.Controls.Add(fileSelector); InitScript(); } private void InitScript() { var script = new StringBuilder(); FolderType folderType; if (Enum.TryParse(Request[RootParam], true, out folderType)) { object rootId = null; switch (folderType) { case FolderType.COMMON: rootId = Classes.Global.FolderCommon; break; case FolderType.USER: rootId = Classes.Global.FolderMy; break; case FolderType.Projects: rootId = Classes.Global.FolderProjects; break; } if (rootId != null) script.AppendFormat("jq(\"#fileSelectorTree > ul > li.tree-node:not([data-id=\\\"{0}\\\"])\").remove();", rootId); } if (!string.IsNullOrEmpty(RequestExt)) { script.AppendFormat(";ASC.Files.FileSelector.filesFilter = ASC.Files.Constants.FilterType.ByExtension;" + "ASC.Files.FileSelector.filesFilterText = \"{0}\";", RequestExt.Replace("\"", "\\\"")); } if (RequestType != FilterType.None) { script.AppendFormat("ASC.Files.FileSelector.filesFilter = ASC.Files.Constants.FilterType[\"{0}\"] || ASC.Files.Constants.FilterType.None;", RequestType); } var originForPost = "*"; if (FromEditor && !FilesLinkUtility.DocServiceApiUrl.StartsWith("/")) { var origin = new Uri(FilesLinkUtility.DocServiceApiUrl ?? ""); originForPost = origin.Scheme + "://" + origin.Host + ":" + origin.Port; } script.AppendFormat("ASC.Files.FileChoice.init(\"{0}\", ({1} == true), \"{2}\", ({3} == true), \"{4}\");", (Request[FilesLinkUtility.FolderId] ?? "").Replace("\"", "\\\""), OnlyFolder.ToString().ToLower(), (Request[ThirdPartyParam] ?? "").ToLower().Replace("\"", "\\\""), FromEditor.ToString().ToLower(), originForPost); Page.RegisterInlineScript(script.ToString()); } public ScriptBundleData GetStaticJavaScript() { return (ScriptBundleData) new ScriptBundleData("fileschoice", "files") .AddSource(PathProvider.GetFileStaticRelativePath, "common.js", "templatemanager.js", "servicemanager.js", "ui.js", "eventhandler.js", "anchormanager.js", "filechoice.js" ) .AddSource(r => FilesLinkUtility.FilesBaseAbsolutePath + r, "Controls/EmptyFolder/emptyfolder.js", "Controls/FileSelector/fileselector.js", "Controls/Tree/tree.js" ); } public StyleBundleData GetStaticStyleSheet() { return (StyleBundleData) new StyleBundleData("fileschoice", "files") .AddSource(PathProvider.GetFileStaticRelativePath, "filechoice.css") .AddSource(r => FilesLinkUtility.FilesBaseAbsolutePath + r, "Controls/FileSelector/fileselector.css", "Controls/ThirdParty/thirdparty.css", "Controls/ContentList/contentlist.css", "Controls/EmptyFolder/emptyfolder.css", "Controls/Tree/tree.css" ); } public string GetTypeString(FilterType filterType) { switch (filterType) { case FilterType.ArchiveOnly: return FilesUCResource.ButtonFilterArchive; case FilterType.DocumentsOnly: return FilesUCResource.ButtonFilterDocument; case FilterType.ImagesOnly: return FilesUCResource.ButtonFilterImage; case FilterType.PresentationsOnly: return FilesUCResource.ButtonFilterPresentation; case FilterType.SpreadsheetsOnly: return FilesUCResource.ButtonFilterSpreadsheet; case FilterType.MediaOnly: return FilesUCResource.ButtonFilterMedia; } return string.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** Class: CollectionBase ** ** Purpose: Provides the abstract base class for a strongly typed collection. ** =============================================================================*/ using System; using System.Diagnostics.Contracts; namespace System.Collections { // Useful base class for typed read/write collections where items derive from object public abstract class CollectionBase : IList { private 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; } } 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", SR.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", SR.ArgumentOutOfRange_Index); Contract.EndContractBlock(); return InnerList[index]; } set { if (index < 0 || index >= Count) throw new ArgumentOutOfRangeException("index", SR.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(SR.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", SR.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) { } } }
#region License //L // 2007 - 2013 Copyright Northwestern University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. //L #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Text; using ClearCanvas.Common; using ClearCanvas.Common.Utilities; namespace AIM.Annotation.Tools { internal class AimHtmlFormatter { private static string AimHtmlDoc = ""; private static string PlusImagePathName; private static string MinusImagePathName; private int _aeCount; private int _aecCount; private int _aecsCount; private int _ioCount; private int _iocCount; private int _iocsCount; private int _charqCount; private int _charqsCount; public static string GetAimHtml(aim_dotnet.Annotation annotation) { if (annotation == null) return GetEmptyHtml(); switch (annotation.AnnotationKind) { case aim_dotnet.AnnotationKind.AK_ImageAnnotation: return GetImageAnnotationHtml(annotation as aim_dotnet.ImageAnnotation); case aim_dotnet.AnnotationKind.AK_AnnotationOfAnnotation: return GetAnnotationOfAnnotationHtml(annotation as aim_dotnet.AnnotationOfAnnotation); } Debug.Assert(false, "Uknown Annotation Type"); Platform.Log(LogLevel.Error, "Annotation Display Formatting (HTML): unknown annotation type"); return "Unknown Annotation Type"; } private static string GetImageAnnotationHtml(aim_dotnet.ImageAnnotation imageAnnotation) { var sb = new StringBuilder(); var htmlFormatter = new AimHtmlFormatter(); var ctrlColor = Color.FromKnownColor(KnownColor.Control); sb.Append(HtmlDocHeader); sb.AppendFormat("<body style=\"background-color: #{0}{1}{2};\" onload=\"setupPaths(['{3}', '{4}'])\">", ctrlColor.R.ToString("X2"), ctrlColor.G.ToString("X2"), ctrlColor.B.ToString("X2"), MinusImagePathName, PlusImagePathName); sb.Append("<div id=\"main_content\">"); sb.Append(htmlFormatter.GetAnatomicEntitiesHtml(imageAnnotation.AnatomyEntityCollection)); sb.Append(htmlFormatter.GetImagingObservationHtml(imageAnnotation.ImagingObservationCollection)); sb.Append("</div>"); sb.Append("</body>"); sb.Append("</html>"); return sb.ToString(); } private static string GetAnnotationOfAnnotationHtml(aim_dotnet.AnnotationOfAnnotation annotationOfAnnotation) { throw new NotImplementedException(); } private static string GetEmptyHtml() { var sb = new StringBuilder(); var ctrlColor = Color.FromKnownColor(KnownColor.Control); sb.Append(HtmlDocHeader); sb.AppendFormat("<body style=\"background-color: #{0}{1}{2};\">", ctrlColor.R.ToString("X2"), ctrlColor.G.ToString("X2"), ctrlColor.B.ToString("X2")); sb.Append("</body>"); sb.Append("</html>"); return sb.ToString(); } private static string HtmlDocHeader { get { if (string.IsNullOrEmpty(AimHtmlDoc)) { lock (AimHtmlDoc) { if (string.IsNullOrEmpty(AimHtmlDoc)) { var resolver = new ResourceResolver(typeof(AimHtmlFormatter).Assembly); try { using (var stream = resolver.OpenResource("Tools.AimHtmlDoc.html")) { using (var reader = new StreamReader(stream)) { AimHtmlDoc = reader.ReadToEnd(); } } using (var stream = resolver.OpenResource("Tools.minus_13x13.gif")) { using (var img = Image.FromStream(stream)) { MinusImagePathName = Path.GetTempFileName().Replace("\\", "/"); img.Save(MinusImagePathName, System.Drawing.Imaging.ImageFormat.Gif); } } using (var stream = resolver.OpenResource("Tools.plus_13x13.gif")) { using (var img = Image.FromStream(stream)) { PlusImagePathName = Path.GetTempFileName().Replace("\\", "/"); img.Save(PlusImagePathName, System.Drawing.Imaging.ImageFormat.Gif); } } } catch(Exception ex) { Platform.Log(LogLevel.Error, ex); } } } } return AimHtmlDoc ?? "<html><body>"; } } private string GetAnatomicEntitiesHtml(List<aim_dotnet.AnatomicEntity> anatomicEntities) { var sb = new StringBuilder(); if (anatomicEntities != null) { foreach (var anatomicEntity in anatomicEntities) { sb.Append(GetExpandableItemHtml( anatomicEntity.CodeMeaning, null, "ae_header", null, "ae_content", "ae", _aeCount++, GetAnatomicEntityCharacteristicsHtml(anatomicEntity.AnatomicEntityCharacteristicCollection))); } } return GetExpandableItemHtml( "Anatomic Entities", string.Format("({0})", anatomicEntities == null ? 0 : anatomicEntities.Count), "aes_header", "aes_summary", "aes_content", "aes", 0, sb.ToString()); } private string GetAnatomicEntityCharacteristicsHtml(List<aim_dotnet.AnatomicEntityCharacteristic> aeCharacteristics) { var sb = new StringBuilder(); if (aeCharacteristics != null) { foreach (var aeCharacteristic in aeCharacteristics) { sb.Append(GetExpandableItemHtml( aeCharacteristic.CodeMeaning, null, "aec_header", null, "aec_content", "aec", _aecCount++, GetCharacteristicQuantificationsHtml(aeCharacteristic.CharacteristicQuantificationCollection))); } } return GetExpandableItemHtml( "Anatomic Entity Characteristics", string.Format("({0})", aeCharacteristics == null ? 0 : aeCharacteristics.Count), "aecs_header", "aecs_summary", "aecs_content", "aecs", _aecsCount++, sb.ToString()); } private string GetImagingObservationHtml(List<aim_dotnet.ImagingObservation> imagingObservations) { var sb = new StringBuilder(); if (imagingObservations != null) { foreach (var imagingObservation in imagingObservations) { sb.Append(GetExpandableItemHtml( imagingObservation.CodeMeaning, null, "io_header", null, "io_content", "io", _ioCount++, GetImagingObservationCharacteristicsHtml(imagingObservation.ImagingObservationCharacteristicCollection))); } } return GetExpandableItemHtml( "Imaging Observations", string.Format("({0})", imagingObservations == null ? 0 : imagingObservations.Count), "ios_header", "ios_summary", "ios_content", "ios", 0, sb.ToString()); } private string GetImagingObservationCharacteristicsHtml(List<aim_dotnet.ImagingObservationCharacteristic> ioCharacteristics) { var sb = new StringBuilder(); if (ioCharacteristics != null) { foreach (var ioCharacteristic in ioCharacteristics) { sb.Append(GetExpandableItemHtml( ioCharacteristic.CodeMeaning, null, "ioc_header", null, "ioc_content", "ioc", _iocCount++, GetCharacteristicQuantificationsHtml(ioCharacteristic.CharacteristicQuantificationCollection))); } } return GetExpandableItemHtml( "Imaging Observation Characteristics", string.Format("({0})", ioCharacteristics == null ? 0 : ioCharacteristics.Count), "iocs_header", "iocs_summary", "iocs_content", "iocs", _iocsCount++, sb.ToString()); } private string GetCharacteristicQuantificationsHtml(List<aim_dotnet.ICharacteristicQuantification> characteristicQuantificationCollection) { var sb = new StringBuilder(); if (characteristicQuantificationCollection != null) { foreach (var characteristicQuantification in characteristicQuantificationCollection) { sb.Append(GetExpandableItemHtml( characteristicQuantification.Name, null, "charq_header", null, "charq_content", "charq", _charqCount++, GetCharacteristicQuantificationHtml(characteristicQuantification))); } } return GetExpandableItemHtml( "Characteristic Quantifications", string.Format("({0})", characteristicQuantificationCollection == null ? 0 : characteristicQuantificationCollection.Count), "charqs_header", "charqs_summary", "charqs_content", "charqs", _charqsCount++, sb.ToString()); } private string GetCharacteristicQuantificationHtml(aim_dotnet.ICharacteristicQuantification characteristicQuantification) { if (characteristicQuantification == null) return ""; switch (characteristicQuantification.QuantificationType) { case aim_dotnet.CharacteristicQuantificationType.Numerical: var numerical = (aim_dotnet.Numerical) characteristicQuantification; return numerical.Operator == aim_dotnet.ComparisonOperatorIdentifier.InvalidComparisonOperator || numerical.Operator == aim_dotnet.ComparisonOperatorIdentifier.None ? string.Format("{0} {1}", numerical.Value, numerical.UcumString) : string.Format("{0} {1} {2}", OperatorToString(numerical.Operator, true), numerical.Value, numerical.UcumString); case aim_dotnet.CharacteristicQuantificationType.Quantile: var quantile = (aim_dotnet.Quantile) characteristicQuantification; return string.Format("Quantile [{0}]", quantile.Bin); case aim_dotnet.CharacteristicQuantificationType.NonQuantifiable: var nonQuantifiable = (aim_dotnet.NonQuantifiable) characteristicQuantification; return nonQuantifiable.CodeMeaning ?? ""; case aim_dotnet.CharacteristicQuantificationType.Scale: var scale = (aim_dotnet.Scale) characteristicQuantification; return scale.Value ?? ""; case aim_dotnet.CharacteristicQuantificationType.Interval: var interval = (aim_dotnet.Interval) characteristicQuantification; { var left = CombineOperatorAndValue(interval.MinOperator, interval.MinValue == double.MinValue ? "" : interval.MinValue.ToString(), true); var right = CombineOperatorAndValue(interval.MaxOperator, interval.MaxValue == double.MaxValue ? "" : interval.MaxValue.ToString(), string.IsNullOrEmpty(left)); var sb = new StringBuilder(); sb.Append(left); if (!string.IsNullOrEmpty(left) && !string.IsNullOrEmpty(right)) sb.Append(" and "); sb.Append(right); return sb.ToString(); } default: Debug.Assert(false, "Unknown characteristic quantification type"); break; } return ""; } private string GetExpandableItemHtml(string headerText, string headerSummary, string headerClass, string headerSummaryClass, string contentClass, string idPrefix, int idCounter, string contentHtml) { if (string.IsNullOrEmpty(headerText) && string.IsNullOrEmpty(headerSummary) && string.IsNullOrEmpty(headerClass) && string.IsNullOrEmpty(contentClass) && string.IsNullOrEmpty(contentHtml)) return string.Empty; var sb = new StringBuilder(); var hasContentData = !string.IsNullOrEmpty(contentHtml); var hasIdPrefix = !string.IsNullOrEmpty(idPrefix); sb.Append("<div"); if(hasIdPrefix) sb.AppendFormat(" id=\"{0}{1}_header\"", idPrefix, idCounter); if (!string.IsNullOrEmpty(headerClass)) sb.AppendFormat(" class=\"{0}\"", headerClass); sb.Append(">"); if(hasContentData && hasIdPrefix && (!string.IsNullOrEmpty(headerText) || !string.IsNullOrEmpty(headerSummary))) sb.AppendFormat( "<a><img class=\"expando\" src=\"{0}\" alt=\"-\" onmousedown=\"toggleDiv(this, '{1}{2}_content');\" title=\"Toggle\" /></a>", MinusImagePathName, idPrefix, idCounter); if (!string.IsNullOrEmpty(headerText)) sb.Append(headerText); if (!string.IsNullOrEmpty(headerSummary)) { sb.Append(" <span"); if (!string.IsNullOrEmpty(headerSummaryClass)) sb.AppendFormat(" class=\"{0}\"", headerSummaryClass); sb.AppendFormat(">{0}</span>", headerSummary); } sb.Append("</div>"); if (hasContentData) { sb.AppendFormat("<div"); if (hasIdPrefix) sb.AppendFormat(" id=\"{0}{1}_content\"", idPrefix, idCounter); if (!string.IsNullOrEmpty(contentClass)) sb.AppendFormat(" class=\"{0}\"", contentClass); sb.Append(">"); sb.Append(contentHtml); sb.Append("</div>"); } return sb.ToString(); } private static string OperatorToString(aim_dotnet.ComparisonOperatorIdentifier operatorIdentifier, bool capFirst) { switch(operatorIdentifier) { case aim_dotnet.ComparisonOperatorIdentifier.Equal: return capFirst ? "Equal to" : "equal to"; case aim_dotnet.ComparisonOperatorIdentifier.NotEqual: return capFirst ? "Not equal to" : "not equal to"; case aim_dotnet.ComparisonOperatorIdentifier.LessThan: return capFirst ? "Less than" : "less than"; case aim_dotnet.ComparisonOperatorIdentifier.LessThanEqual: return capFirst ? "Less than or equal" : "less than or equal"; case aim_dotnet.ComparisonOperatorIdentifier.GreaterThan: return capFirst ? "Greater than" : "greater than"; case aim_dotnet.ComparisonOperatorIdentifier.GreaterThanEqual: return capFirst ? "Greater than or equal" : "greater than or equal"; case aim_dotnet.ComparisonOperatorIdentifier.None: return capFirst ? "None" : "none"; case aim_dotnet.ComparisonOperatorIdentifier.InvalidComparisonOperator: return capFirst ? "Invalid" : "invalid"; } return string.Empty; } private static string CombineOperatorAndValue(aim_dotnet.ComparisonOperatorIdentifier operatorIdentifier, string aValue, bool capFirst) { aValue = aValue.Trim(); if (operatorIdentifier == aim_dotnet.ComparisonOperatorIdentifier.None || operatorIdentifier == aim_dotnet.ComparisonOperatorIdentifier.InvalidComparisonOperator) return string.IsNullOrEmpty(aValue) ? "" : aValue; if (string.IsNullOrEmpty(aValue)) return OperatorToString(operatorIdentifier, capFirst); return string.Format("{0} {1}", OperatorToString(operatorIdentifier, capFirst), aValue); } } }
// ZlibBaseStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 15:45:15> // // ------------------------------------------------------------------ // // This module defines the ZlibBaseStream class, which is an intnernal // base class for DeflateStream, ZlibStream and GZipStream. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic.Zlib { internal enum ZlibStreamFlavor { ZLIB = 1950, DEFLATE = 1951, GZIP = 1952 } internal class ZlibBaseStream : System.IO.Stream { protected internal ZlibCodec _z = null; // deferred init... new ZlibCodec(); protected internal StreamMode _streamMode = StreamMode.Undefined; protected internal FlushType _flushMode; protected internal ZlibStreamFlavor _flavor; protected internal CompressionMode _compressionMode; protected internal CompressionLevel _level; protected internal bool _leaveOpen; protected internal byte[] _workingBuffer; protected internal int _bufferSize = ZlibConstants.WorkingBufferSizeDefault; protected internal byte[] _buf1 = new byte[1]; protected internal System.IO.Stream _stream; protected internal CompressionStrategy Strategy = CompressionStrategy.Default; // workitem 7159 Ionic.Zlib.CRC32 crc; protected internal string _GzipFileName; protected internal string _GzipComment; protected internal DateTime _GzipMtime; protected internal int _gzipHeaderByteCount; internal int Crc32 { get { if (crc == null) return 0; return crc.Crc32Result; } } public ZlibBaseStream(System.IO.Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, bool leaveOpen) : base() { this._flushMode = FlushType.None; //this._workingBuffer = new byte[WORKING_BUFFER_SIZE_DEFAULT]; this._stream = stream; this._leaveOpen = leaveOpen; this._compressionMode = compressionMode; this._flavor = flavor; this._level = level; // workitem 7159 if (flavor == ZlibStreamFlavor.GZIP) { crc = new CRC32(); } } protected internal bool _wantCompress { get { return (this._compressionMode == CompressionMode.Compress); } } private ZlibCodec z { get { if (_z == null) { bool wantRfc1950Header = (this._flavor == ZlibStreamFlavor.ZLIB); _z = new ZlibCodec(); if (this._compressionMode == CompressionMode.Decompress) { _z.InitializeInflate(wantRfc1950Header); } else { _z.Strategy = Strategy; _z.InitializeDeflate(this._level, wantRfc1950Header); } } return _z; } } private byte[] workingBuffer { get { if (_workingBuffer == null) _workingBuffer = new byte[_bufferSize]; return _workingBuffer; } } public override void Write(System.Byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) crc.SlurpBlock(buffer, offset, count); if (_streamMode == StreamMode.Undefined) _streamMode = StreamMode.Writer; else if (_streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); } private void finish() { if (_z == null) return; if (_streamMode == StreamMode.Writer) { bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(FlushType.Finish) : _z.Inflate(FlushType.Finish); if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK) { string verb = (_wantCompress ? "de" : "in") + "flating"; if (_z.Message == null) throw new ZlibException(String.Format("{0}: (rc = {1})", verb, rc)); else throw new ZlibException(verb + ": " + _z.Message); } if (_workingBuffer.Length - _z.AvailableBytesOut > 0) { _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); } done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); Flush(); // workitem 7159 if (_flavor == ZlibStreamFlavor.GZIP) { if (_wantCompress) { // Emit the GZIP trailer: CRC32 and size mod 2^32 int c1 = crc.Crc32Result; _stream.Write(BitConverter.GetBytes(c1), 0, 4); int c2 = (Int32)(crc.TotalBytesRead & 0x00000000FFFFFFFF); _stream.Write(BitConverter.GetBytes(c2), 0, 4); } else { throw new ZlibException("Writing with decompression is not supported."); } } } // workitem 7159 else if (_streamMode == StreamMode.Reader) { if (_flavor == ZlibStreamFlavor.GZIP) { if (!_wantCompress) { // workitem 8501: handle edge case (decompress empty stream) if (_z.TotalBytesOut == 0L) return; // Read and potentially verify the GZIP trailer: CRC32 and size mod 2^32 byte[] trailer = new byte[8]; // workitem 8679 if (_z.AvailableBytesIn != 8) { // Make sure we have read to the end of the stream Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, _z.AvailableBytesIn); int bytesNeeded = 8 - _z.AvailableBytesIn; int bytesRead = _stream.Read(trailer, _z.AvailableBytesIn, bytesNeeded); if (bytesNeeded != bytesRead) { throw new ZlibException(String.Format("Protocol error. AvailableBytesIn={0}, expected 8", _z.AvailableBytesIn + bytesRead)); } } else { Array.Copy(_z.InputBuffer, _z.NextIn, trailer, 0, trailer.Length); } Int32 crc32_expected = BitConverter.ToInt32(trailer, 0); Int32 crc32_actual = crc.Crc32Result; Int32 isize_expected = BitConverter.ToInt32(trailer, 4); Int32 isize_actual = (Int32)(_z.TotalBytesOut & 0x00000000FFFFFFFF); if (crc32_actual != crc32_expected) throw new ZlibException(String.Format("Bad CRC32 in GZIP stream. (actual({0:X8})!=expected({1:X8}))", crc32_actual, crc32_expected)); if (isize_actual != isize_expected) throw new ZlibException(String.Format("Bad size in GZIP stream. (actual({0})!=expected({1}))", isize_actual, isize_expected)); } else { throw new ZlibException("Reading with compression is not supported."); } } } } private void end() { if (z == null) return; if (_wantCompress) { _z.EndDeflate(); } else { _z.EndInflate(); } _z = null; } public override void Close() { if (_stream == null) return; try { finish(); } finally { end(); if (!_leaveOpen) _stream.Close(); _stream = null; } } public override void Flush() { _stream.Flush(); } public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); //_outStream.Seek(offset, origin); } public override void SetLength(System.Int64 value) { _stream.SetLength(value); } #if NOT public int Read() { if (Read(_buf1, 0, 1) == 0) return 0; // calculate CRC after reading if (crc!=null) crc.SlurpBlock(_buf1,0,1); return (_buf1[0] & 0xFF); } #endif private bool nomoreinput = false; private string ReadZeroTerminatedString() { var list = new System.Collections.Generic.List<byte>(); bool done = false; do { // workitem 7740 int n = _stream.Read(_buf1, 0, 1); if (n != 1) throw new ZlibException("Unexpected EOF reading GZIP header."); else { if (_buf1[0] == 0) done = true; else list.Add(_buf1[0]); } } while (!done); byte[] a = list.ToArray(); return GZipStream.iso8859dash1.GetString(a, 0, a.Length); } private int _ReadAndValidateGzipHeader() { int totalBytesRead = 0; // read the header on the first read byte[] header = new byte[10]; int n = _stream.Read(header, 0, header.Length); // workitem 8501: handle edge case (decompress empty stream) if (n == 0) return 0; if (n != 10) throw new ZlibException("Not a valid GZIP stream."); if (header[0] != 0x1F || header[1] != 0x8B || header[2] != 8) throw new ZlibException("Bad GZIP header."); Int32 timet = BitConverter.ToInt32(header, 4); _GzipMtime = GZipStream._unixEpoch.AddSeconds(timet); totalBytesRead += n; if ((header[3] & 0x04) == 0x04) { // read and discard extra field n = _stream.Read(header, 0, 2); // 2-byte length field totalBytesRead += n; Int16 extraLength = (Int16)(header[0] + header[1] * 256); byte[] extra = new byte[extraLength]; n = _stream.Read(extra, 0, extra.Length); if (n != extraLength) throw new ZlibException("Unexpected end-of-file reading GZIP header."); totalBytesRead += n; } if ((header[3] & 0x08) == 0x08) _GzipFileName = ReadZeroTerminatedString(); if ((header[3] & 0x10) == 0x010) _GzipComment = ReadZeroTerminatedString(); if ((header[3] & 0x02) == 0x02) Read(_buf1, 0, 1); // CRC16, ignore return totalBytesRead; } public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) return 0; } } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) break; // nothing more to read } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) crc.SlurpBlock(buffer, offset, rc); return rc; } public override System.Boolean CanRead { get { return this._stream.CanRead; } } public override System.Boolean CanSeek { get { return this._stream.CanSeek; } } public override System.Boolean CanWrite { get { return this._stream.CanWrite; } } public override System.Int64 Length { get { return _stream.Length; } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } internal enum StreamMode { Writer, Reader, Undefined, } public static void CompressString(String s, Stream compressor) { byte[] uncompressed = System.Text.Encoding.UTF8.GetBytes(s); using (compressor) { compressor.Write(uncompressed, 0, uncompressed.Length); } } public static void CompressBuffer(byte[] b, Stream compressor) { // workitem 8460 using (compressor) { compressor.Write(b, 0, b.Length); } } public static String UncompressString(byte[] compressed, Stream decompressor) { // workitem 8460 byte[] working = new byte[1024]; var encoding = System.Text.Encoding.UTF8; using (var output = new MemoryStream()) { using (decompressor) { int n; while ((n = decompressor.Read(working, 0, working.Length)) != 0) { output.Write(working, 0, n); } } // reset to allow read from start output.Seek(0, SeekOrigin.Begin); var sr = new StreamReader(output, encoding); return sr.ReadToEnd(); } } public static byte[] UncompressBuffer(byte[] compressed, Stream decompressor) { // workitem 8460 byte[] working = new byte[1024]; using (var output = new MemoryStream()) { using (decompressor) { int n; while ((n = decompressor.Read(working, 0, working.Length)) != 0) { output.Write(working, 0, n); } } return output.ToArray(); } } } }
using EPiServer.Commerce.Catalog.ContentTypes; using EPiServer.Commerce.Catalog.Linking; using EPiServer.Commerce.SpecializedProperties; using EPiServer.Core; using EPiServer.Filters; using EPiServer.Reference.Commerce.Site.Features.Market.Services; using EPiServer.Reference.Commerce.Site.Features.Product.Controllers; using EPiServer.Reference.Commerce.Site.Features.Product.Models; using EPiServer.Reference.Commerce.Site.Features.Product.ViewModels; using EPiServer.Reference.Commerce.Site.Features.Shared.Services; using EPiServer.Reference.Commerce.Site.Infrastructure.Facades; using EPiServer.Web.Routing; using FluentAssertions; using Mediachase.Commerce; using Mediachase.Commerce.Catalog; using Mediachase.Commerce.Pricing; using Moq; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using EPiServer.Globalization; using Xunit; using EPiServer.Reference.Social.Reviews.Services; namespace EPiServer.Reference.Commerce.Site.Tests.Features.Product.Controllers { public class ProductControllerTests : IDisposable { [Fact] public void Index_WhenVariationIdIsNull_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); SetRelation(fashionProduct, Enumerable.Empty<ProductVariation>()); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, null); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenVariationIdIsEmpty_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); SetRelation(fashionProduct, Enumerable.Empty<ProductVariation>()); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, string.Empty); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenNoVariationExists_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); SetRelation(fashionProduct, Enumerable.Empty<ProductVariation>()); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, "something"); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenSelectedVariationDontExist_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); var fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, "doNotExist"); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenSelectedVariationExist_ShouldSetVariationToSelectedVariation() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); productController = CreateController(); } // execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<FashionVariant>(fashionVariant, model.Variation); } } [Fact] public void Index_WhenSelectedVariationExist_ShouldSetProductToRoutedProduct() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<FashionProduct>(fashionProduct, model.Product); } } [Fact] public void Index_WhenSelectedVariationExist_ShouldSetOriginalPriceToDefaultPrice() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; Mock<IPriceValue> mockDefaultPrice = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); mockDefaultPrice = CreatePriceValueMock(25); SetDefaultPriceService(mockDefaultPrice.Object); var mockDiscountPrice = CreatePriceValueMock(20); SetDiscountPriceService(mockDiscountPrice.Object); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<Money>(mockDefaultPrice.Object.UnitPrice, model.ListingPrice); } } [Fact] public void Index_WhenSelectedVariationExist_ShouldSetPriceToDiscountPrice() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; Mock<IPriceValue> mockDiscountPrice = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); var mockDefaultPrice = CreatePriceValueMock(25); SetDefaultPriceService(mockDefaultPrice.Object); mockDiscountPrice = CreatePriceValueMock(20); SetDiscountPriceService(mockDiscountPrice.Object); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<Money>(mockDiscountPrice.Object.UnitPrice, model.DiscountedPrice.Value); } } [Fact] public void Index_WhenSelectedVariationExist_ShouldSetColorToSelectedVariationColor() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; string color = null; ActionResult actionResult = null; // Setup { color = "green"; fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetColor(fashionVariant, color); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<string>(color, model.Color); } } [Fact] public void Index_WhenSelectedVariationExist_ShouldSetSizeToSelectedVariationSize() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; string size = null; ActionResult actionResult = null; // Setup { size = "small"; fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetSize(fashionVariant, size); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<string>(size, model.Size); } } [Fact] public void Index_WhenSelectedVariationDontHaveAssets_ShouldSetImagesToOneItemWithEmptyLink() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<string>(string.Empty, model.Images.Single()); } } [Fact] public void Index_WhenSelectedVariationHasImageAssets_ShouldSetImagesToLinkFromImage() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; string imageLink = null; ActionResult actionResult = null; // Setup { imageLink = "http://www.episerver.com"; fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); var imageMedia = CreateImageMedia(new ContentReference(237), imageLink); SetMediaCollection(fashionVariant, imageMedia); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<string>(imageLink, model.Images.Single()); } } [Fact] public void Index_WhenAvailableColorsAreEmptyForVariation_ShouldSetColorsToEmpty() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant(); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; Assert.Equal<int>(0, model.Colors.Count()); } } [Fact] public void Index_WhenAvailableColorsContainsItems_ShouldSetTextToItemValue() { FashionProduct fashionProduct = null; FashionVariant fashionVariant1 = null; FashionVariant fashionVariant2 = null; FashionVariant fashionVariant3 = null; ProductController productController = null; ItemCollection<string> colors = null; ActionResult actionResult = null; // Setup { colors = new ItemCollection<string>() { "green", "red" }; fashionProduct = CreateFashionProduct(); SetAvailableColors(fashionProduct, colors); SetAvailableSizes(fashionProduct, new ItemCollection<string> { "small", "medium" }); fashionVariant1 = CreateFashionVariant("small", "green"); fashionVariant2 = CreateFashionVariant("medium", "red"); fashionVariant3 = CreateFashionVariant("medium", "green"); SetRelation(fashionProduct, new[] { fashionVariant1, fashionVariant2, fashionVariant3 }); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant1.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedColors = String.Join(";", colors); var modelColorTexts = String.Join(";", model.Colors.Select(x => x.Text)); Assert.Equal<string>(expectedColors, modelColorTexts); } } [Fact] public void Index_WhenAvailableColorsContainsItems_ShouldSetValueToItemValue() { FashionProduct fashionProduct = null; FashionVariant fashionVariant1 = null; FashionVariant fashionVariant2 = null; FashionVariant fashionVariant3 = null; ProductController productController = null; ItemCollection<string> colors = null; ActionResult actionResult = null; // Setup { colors = new ItemCollection<string>() { "green", "red" }; fashionProduct = CreateFashionProduct(); SetAvailableColors(fashionProduct, colors); SetAvailableSizes(fashionProduct, new ItemCollection<string> { "small", "medium" }); fashionVariant1 = CreateFashionVariant("small", "green"); fashionVariant2 = CreateFashionVariant("medium", "red"); fashionVariant3 = CreateFashionVariant("medium", "green"); SetRelation(fashionProduct, new[] { fashionVariant1, fashionVariant2, fashionVariant3 }); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant1.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedColors = String.Join(";", colors); var modelColorValues = String.Join(";", model.Colors.Select(x => x.Value)); Assert.Equal<string>(expectedColors, modelColorValues); } } [Fact] public void Index_WhenAvailableColorsContainsItems_ShouldSetSelectedToFalse() { FashionProduct fashionProduct = null; FashionVariant fashionVariant1 = null; FashionVariant fashionVariant2 = null; FashionVariant fashionVariant3 = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); SetAvailableColors(fashionProduct, new ItemCollection<string>() { "green", "red" }); SetAvailableSizes(fashionProduct, new ItemCollection<string> { "small", "medium" }); fashionVariant1 = CreateFashionVariant("small", "green"); fashionVariant2 = CreateFashionVariant("medium", "red"); fashionVariant3 = CreateFashionVariant("medium", "green"); SetRelation(fashionProduct, new[] { fashionVariant1, fashionVariant2, fashionVariant3 }); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant1.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedColors = String.Join(";", new[] { false, false }); var modelColorsSelected = String.Join(";", model.Colors.Select(x => x.Selected)); Assert.Equal<string>(expectedColors, modelColorsSelected); } } [Fact] public void Index_WhenAvailableSizesContainsItems_ShouldSetTextToItemValue() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ItemCollection<string> sizes = null; ActionResult actionResult = null; // Setup { sizes = new ItemCollection<string>() { "medium" }; fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant("medium", "red"); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedSizes = String.Join(";", sizes); var modelSizeTexts = String.Join(";", model.Sizes.Select(x => x.Text)); Assert.Equal<string>(expectedSizes, modelSizeTexts); } } [Fact] public void Index_WhenAvailableSizesContainsItems_ShouldSetValueToItemValue() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ItemCollection<string> sizes = null; ActionResult actionResult = null; // Setup { sizes = new ItemCollection<string>() { "medium" }; fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant("medium", "red"); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedSizes = String.Join(";", sizes); var modelSizeValues = String.Join(";", model.Sizes.Select(x => x.Value)); Assert.Equal<string>(expectedSizes, modelSizeValues); } } [Fact] public void Index_WhenAvailableSizesContainsItems_ShouldSetSelectedToFalse() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { fashionProduct = CreateFashionProduct(); fashionVariant = CreateFashionVariant("medium", "red"); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedSizes = String.Join(";", new[] { false }); var modelSizesSelected = String.Join(";", model.Sizes.Select(x => x.Selected)); Assert.Equal<string>(expectedSizes, modelSizesSelected); } } [Fact] public void Index_WhenAvailableSizesContainsDelayPublishItems_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); // setup variant with publish date in future fashionVariant = CreateFashionVariant(); fashionVariant.StartPublish = DateTime.UtcNow.AddDays(7); // pulish date is future fashionVariant.StopPublish = DateTime.UtcNow.AddDays(17); fashionVariant.Status = VersionStatus.DelayedPublish; SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenAvailableSizesContainsExpiredItems_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); // setup variant was expired. fashionVariant = CreateFashionVariant(); fashionVariant.StartPublish = DateTime.UtcNow.AddDays(-17); fashionVariant.StopPublish = DateTime.UtcNow.AddDays(-7); SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenAvailableSizesContainsUnpublishItems_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); // setup variant with inactive fashionVariant = CreateFashionVariant(); fashionVariant.IsPendingPublish = true; fashionVariant.Status = VersionStatus.CheckedIn; SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenAvailableSizesContainsItemUnavailabelInCurrentMarket_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; FashionVariant fashionVariant = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); // setup variant unavailable in default market fashionVariant = CreateFashionVariant(); fashionVariant.MarketFilter = new ItemCollection<string>() { "Default" }; SetRelation(fashionProduct, fashionVariant); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariant.Code); } // Assert { Assert.IsType(typeof(HttpNotFoundResult), actionResult); } } [Fact] public void Index_WhenIsInEditModeAndHasNoVariation_ShouldReturnProductWithoutVariationView() { FashionProduct fashionProduct = null; ProductController productController = null; ActionResult actionResult = null; // Setup { _isInEditMode = true; fashionProduct = CreateFashionProduct(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, "notexist"); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; model.Product.ShouldBeEquivalentTo(fashionProduct); } } [Fact] public void Index_WhenVariationCodeHasValue_ShouldSetColorsToTheAvailableColorsForTheVariationSize() { const string variationColorBlue = "blue"; const string variationColorWhite = "white"; FashionProduct fashionProduct = null; FashionVariant fashionVariantSmallBlue = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; var colors = new ItemCollection<string>() { "red", variationColorBlue, "yellow", variationColorWhite, "green" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); SetAvailableColors(fashionProduct, colors); fashionVariantSmallBlue = CreateFashionVariant("small", variationColorBlue); var fashionVariantSmallWhite = CreateFashionVariant("small", variationColorWhite); SetRelation(fashionProduct, new[] { fashionVariantSmallBlue, fashionVariantSmallWhite }); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariantSmallBlue.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedColors = String.Join(";", new[] { variationColorBlue, variationColorWhite }); var modelColors = String.Join(";", model.Colors.Select(x => x.Value)); Assert.Equal<string>(expectedColors, modelColors); } } [Fact] public void Index_WhenVariationCodeHasValue_ShouldSetSizesToTheAvailableSizesForTheVariationColor() { const string variationSizeMedium = "medium"; const string variationSizeXlarge = "x-large"; FashionProduct fashionProduct = null; FashionVariant fashionVariantMediumRed = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", variationSizeMedium, "large", variationSizeXlarge, "xx-large" }; var colors = new ItemCollection<string>() { "red" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); SetAvailableColors(fashionProduct, colors); fashionVariantMediumRed = CreateFashionVariant(variationSizeMedium, "red"); var fashionVariantXlargeRed = CreateFashionVariant(variationSizeXlarge, "red"); SetRelation(fashionProduct, new[] { fashionVariantMediumRed, fashionVariantXlargeRed }); MockPrices(); productController = CreateController(); } // Execute { actionResult = productController.Index(fashionProduct, fashionVariantMediumRed.Code); } // Assert { var model = (FashionProductViewModel)((ViewResultBase)actionResult).Model; var expectedSizes = String.Join(";", new[] { variationSizeMedium, variationSizeXlarge }); var modelSizes = String.Join(";", model.Sizes.Select(x => x.Value)); Assert.Equal<string>(expectedSizes, modelSizes); } } [Fact] public void SelectVariant_WhenColorAndSizeHasValues_ShouldGetVariantWithSelectedColorAndSize() { FashionProduct fashionProduct = null; FashionVariant fashionVariantSmallGreen = null; FashionVariant fashionVariantSmallRed = null; FashionVariant fashionVariantMediumGreen = null; FashionVariant fashionVariantMediumRed = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; var colors = new ItemCollection<string>() { "green", "red" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); SetAvailableColors(fashionProduct, colors); fashionVariantSmallGreen = CreateFashionVariant("small", "green"); fashionVariantSmallRed = CreateFashionVariant("small", "red"); fashionVariantMediumGreen = CreateFashionVariant("medium", "green"); fashionVariantMediumRed = CreateFashionVariant("medium", "red"); SetRelation(fashionProduct, new[] { fashionVariantSmallGreen, fashionVariantSmallRed, fashionVariantMediumGreen, fashionVariantMediumRed, }); productController = CreateController(); } // Execute { actionResult = productController.SelectVariant(fashionProduct, "red", "small"); } // Assert { var selectedCode = ((RedirectToRouteResult)actionResult).RouteValues["variationCode"] as string; Assert.Equal<string>("redsmall", selectedCode); } } [Fact] public void SelectVariant_WhenCanNotFoundBySize_ShouldTryGetVariantWithSelectedColorOnly() { FashionProduct fashionProduct = null; FashionVariant fashionVariantSmallGreen = null; FashionVariant fashionVariantMediumRed = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; var colors = new ItemCollection<string>() { "green", "red" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); SetAvailableColors(fashionProduct, colors); fashionVariantSmallGreen = CreateFashionVariant("small", "green"); fashionVariantMediumRed = CreateFashionVariant("medium", "red"); SetRelation(fashionProduct, new[] { fashionVariantSmallGreen, fashionVariantMediumRed, }); productController = CreateController(); } // Execute { actionResult = productController.SelectVariant(fashionProduct, "red", "small"); } // Assert { var selectedCode = ((RedirectToRouteResult)actionResult).RouteValues["variationCode"] as string; Assert.Equal<string>("redmedium", selectedCode); } } [Fact] public void SelectVariant_WhenCanNotFoundBySizeOrColor_ShouldReturnHttpNotFoundResult() { FashionProduct fashionProduct = null; FashionVariant fashionVariantSmallGreen = null; FashionVariant fashionVariantMediumRed = null; ProductController productController = null; ActionResult actionResult = null; // Setup { var sizes = new ItemCollection<string>() { "small", "medium" }; var colors = new ItemCollection<string>() { "green", "red" }; fashionProduct = CreateFashionProduct(); SetAvailableSizes(fashionProduct, sizes); SetAvailableColors(fashionProduct, colors); fashionVariantSmallGreen = CreateFashionVariant("small", "green"); fashionVariantMediumRed = CreateFashionVariant("medium", "red"); SetRelation(fashionProduct, new[] { fashionVariantSmallGreen, fashionVariantMediumRed, }); productController = CreateController(); } // Execute { actionResult = productController.SelectVariant(fashionProduct, "yellow", "small"); } // Assert { Assert.IsType<HttpNotFoundResult>(actionResult); } } private readonly Mock<IPromotionService> _promotionServiceMock; private readonly Mock<IContentLoader> _contentLoaderMock; private readonly Mock<IPriceService> _priceServiceMock; private readonly Mock<ICurrentMarket> _currentMarketMock; private readonly FilterPublished _filterPublished; private readonly Mock<CurrencyService> _currencyserviceMock; private readonly Mock<IRelationRepository> _relationRepositoryMock; private readonly Mock<CookieService> _cookieServiceMock; private readonly Mock<UrlResolver> _urlResolverMock; private readonly Mock<HttpContextBase> _httpContextBaseMock; private readonly Mock<IMarket> _marketMock; private readonly Mock<AppContextFacade> _appContextFacadeMock; private readonly Mock<LanguageResolver> _languageResolverMock; private readonly Currency _defaultCurrency; private bool _isInEditMode; public ProductControllerTests() { _defaultCurrency = Currency.USD; _urlResolverMock = new Mock<UrlResolver>(); _contentLoaderMock = new Mock<IContentLoader>(); _cookieServiceMock = new Mock<CookieService>(); _priceServiceMock = new Mock<IPriceService>(); _relationRepositoryMock = new Mock<IRelationRepository>(); _promotionServiceMock = new Mock<IPromotionService>(); var mockPublishedStateAssessor = new Mock<IPublishedStateAssessor>(); mockPublishedStateAssessor.Setup(x => x.IsPublished(It.IsAny<IContent>(), It.IsAny<PublishedStateCondition>())) .Returns((IContent content, PublishedStateCondition condition) => { var contentVersionable = content as IVersionable; if (contentVersionable != null) { if (contentVersionable.Status == VersionStatus.Published && contentVersionable.StartPublish < DateTime.UtcNow && contentVersionable.StopPublish > DateTime.UtcNow) { return true; } } return false; } ); _filterPublished = new FilterPublished(mockPublishedStateAssessor.Object); _marketMock = new Mock<IMarket>(); _marketMock.Setup(x => x.DefaultCurrency).Returns(_defaultCurrency); _marketMock.Setup(x => x.MarketId).Returns(new MarketId("Default")); _marketMock.Setup(x => x.MarketName).Returns("Default"); _marketMock.Setup(x => x.IsEnabled).Returns(true); _marketMock.Setup(x => x.DefaultLanguage).Returns(new CultureInfo("en")); _currentMarketMock = new Mock<ICurrentMarket>(); _currentMarketMock.Setup(x => x.GetCurrentMarket()).Returns(_marketMock.Object); _currencyserviceMock = new Mock<CurrencyService>(_currentMarketMock.Object, _cookieServiceMock.Object); _currencyserviceMock.Setup(x => x.GetCurrentCurrency()).Returns(_defaultCurrency); _appContextFacadeMock = new Mock<AppContextFacade>(); _appContextFacadeMock.Setup(x => x.ApplicationId).Returns(Guid.NewGuid); var request = new Mock<HttpRequestBase>(); request.SetupGet(x => x.Headers).Returns( new System.Net.WebHeaderCollection { {"X-Requested-With", "XMLHttpRequest"} }); _httpContextBaseMock = new Mock<HttpContextBase>(); _httpContextBaseMock.SetupGet(x => x.Request).Returns(request.Object); _languageResolverMock = new Mock<LanguageResolver>(); _languageResolverMock.Setup(x => x.GetPreferredCulture()).Returns(CultureInfo.GetCultureInfo("en")); SetGetItems(Enumerable.Empty<ContentReference>(), Enumerable.Empty<IContent>()); SetDefaultCurrency(null); } public void Dispose() { _isInEditMode = false; } private ProductController CreateController() { var controller = new ProductController( _promotionServiceMock.Object, _contentLoaderMock.Object, _priceServiceMock.Object, _currentMarketMock.Object, _currencyserviceMock.Object, _relationRepositoryMock.Object, _appContextFacadeMock.Object, _urlResolverMock.Object, _filterPublished, _languageResolverMock.Object, () => _isInEditMode, Mock.Of<IReviewService>()); controller.ControllerContext = new ControllerContext(_httpContextBaseMock.Object, new RouteData(), controller); return controller; } private static FashionVariant CreateFashionVariant(string size, string color) { var fashionVariant = CreateFashionVariant(color + size); SetSize(fashionVariant, size); SetColor(fashionVariant, color); return fashionVariant; } private static FashionVariant CreateFashionVariant(string code = "myVariant") { var fashionVariant = new FashionVariant { ContentLink = new ContentReference(740), Code = code, IsDeleted = false, IsPendingPublish = false, Status = VersionStatus.Published, StartPublish = DateTime.UtcNow.AddDays(-7), StopPublish = DateTime.UtcNow.AddDays(7), MarketFilter = new ItemCollection<string>() { "USA" } }; return fashionVariant; } private static FashionProduct CreateFashionProduct() { var fashionProduct = new FashionProduct { ContentLink = new ContentReference(741), Code = "myProduct", IsDeleted = false, IsPendingPublish = false, Status = VersionStatus.Published, StartPublish = DateTime.UtcNow.AddDays(-7), StopPublish = DateTime.UtcNow.AddDays(7), MarketFilter = new ItemCollection<string>() { "USA" } }; SetAvailableColors(fashionProduct, new ItemCollection<string>()); SetAvailableSizes(fashionProduct, new ItemCollection<string>()); return fashionProduct; } private static void SetAvailableColors(FashionProduct product, ItemCollection<string> colors) { product.AvailableColors = colors; } private static void SetAvailableSizes(FashionProduct product, ItemCollection<string> sizes) { product.AvailableSizes = sizes; } private static void SetColor(FashionVariant fashionVariant, string color) { fashionVariant.Color = color; } private static void SetSize(FashionVariant fashionVariant, string size) { fashionVariant.Size = size; } private void SetRelation(IContent source, IContent target) { SetRelation(source, new[] { target }); } private void SetRelation(IContent source, IEnumerable<IContent> targets) { SetRelation(source, targets.Select(x => new ProductVariation() { Source = source.ContentLink, Target = x.ContentLink })); SetGetItems(new[] { source.ContentLink }, new[] { source }); SetGetItems(targets.Select(x => x.ContentLink), targets); } private void SetRelation(IContent setup, IEnumerable<ProductVariation> result) { _relationRepositoryMock.Setup(x => x.GetRelationsBySource<ProductVariation>(setup.ContentLink)).Returns(result); } private void SetGetItems(IEnumerable<ContentReference> setup, IEnumerable<IContent> result) { _contentLoaderMock.Setup(x => x.GetItems(setup, CultureInfo.GetCultureInfo("en"))).Returns(result); } private void SetDefaultCurrency(string currency) { _cookieServiceMock.Setup(x => x.Get("Currency")).Returns(currency); } private void SetDefaultPriceService(IPriceValue returnedPrice) { _priceServiceMock .Setup(x => x.GetDefaultPrice(It.IsAny<MarketId>(), It.IsAny<DateTime>(), It.IsAny<CatalogKey>(), _defaultCurrency)) .Returns(returnedPrice); } private void SetDiscountPriceService(IPriceValue returnedPrice) { _promotionServiceMock .Setup(x => x.GetDiscountPrice(It.IsAny<CatalogKey>(), It.IsAny<MarketId>(), _defaultCurrency)) .Returns(returnedPrice); } private Mock<IPriceValue> CreatePriceValueMock(decimal amount) { var mockPriceValue = new Mock<IPriceValue>(); mockPriceValue.Setup(x => x.ValidFrom).Returns(DateTime.MinValue); mockPriceValue.Setup(x => x.ValidUntil).Returns(DateTime.MaxValue); mockPriceValue.Setup(x => x.UnitPrice).Returns(new Money(amount, _defaultCurrency)); return mockPriceValue; } private void MockPrices() { var mockDefaultPrice = CreatePriceValueMock(25); SetDefaultPriceService(mockDefaultPrice.Object); var mockDiscountPrice = CreatePriceValueMock(20); SetDiscountPriceService(mockDiscountPrice.Object); } private CommerceMedia CreateImageMedia(ContentReference contentLink, string imageLink) { IContentImage contentImage; var imageMedia = new CommerceMedia { AssetLink = contentLink }; _contentLoaderMock.Setup(x => x.TryGet(imageMedia.AssetLink, out contentImage)).Returns(true); _urlResolverMock.Setup(x => x.GetUrl(imageMedia.AssetLink)).Returns(imageLink); return imageMedia; } private static void SetMediaCollection(IAssetContainer assetContainer, CommerceMedia media) { assetContainer.CommerceMediaCollection = new ItemCollection<CommerceMedia>() { media }; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D01_ContinentColl (editable root list).<br/> /// This is a generated base class of <see cref="D01_ContinentColl"/> business object. /// </summary> /// <remarks> /// The items of the collection are <see cref="D02_Continent"/> objects. /// </remarks> [Serializable] public partial class D01_ContinentColl : BusinessListBase<D01_ContinentColl, D02_Continent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="D02_Continent"/> item from the collection. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to be removed.</param> public void Remove(int continent_ID) { foreach (var d02_Continent in this) { if (d02_Continent.Continent_ID == continent_ID) { Remove(d02_Continent); break; } } } /// <summary> /// Determines whether a <see cref="D02_Continent"/> item is in the collection. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to search for.</param> /// <returns><c>true</c> if the D02_Continent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int continent_ID) { foreach (var d02_Continent in this) { if (d02_Continent.Continent_ID == continent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="D02_Continent"/> item is in the collection's DeletedList. /// </summary> /// <param name="continent_ID">The Continent_ID of the item to search for.</param> /// <returns><c>true</c> if the D02_Continent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int continent_ID) { foreach (var d02_Continent in DeletedList) { if (d02_Continent.Continent_ID == continent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="D02_Continent"/> item of the <see cref="D01_ContinentColl"/> collection, based on a given Continent_ID. /// </summary> /// <param name="continent_ID">The Continent_ID.</param> /// <returns>A <see cref="D02_Continent"/> object.</returns> public D02_Continent FindD02_ContinentByContinent_ID(int continent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Continent_ID.Equals(continent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D01_ContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="D01_ContinentColl"/> collection.</returns> public static D01_ContinentColl NewD01_ContinentColl() { return DataPortal.Create<D01_ContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="D01_ContinentColl"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="D01_ContinentColl"/> collection.</returns> public static D01_ContinentColl GetD01_ContinentColl() { return DataPortal.Fetch<D01_ContinentColl>(); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D01_ContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D01_ContinentColl() { // Use factory methods and do not use direct creation. var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="D01_ContinentColl"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetD01_ContinentColl", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="D01_ContinentColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(D02_Continent.GetD02_Continent(dr)); } RaiseListChangedEvents = rlce; } /// <summary> /// Updates in the database all changes made to the <see cref="D01_ContinentColl"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { base.Child_Update(); } } #endregion #region DataPortal Hooks /// <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); #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; using System.IO; using Mono.Cecil; using Mono.Cecil.Cil; namespace Microsoft.SPOT.Debugger { public class CorDebugAssembly:IDisposable { CorDebugAppDomain m_appDomain; CorDebugProcess m_process; Hashtable m_htTokenCLRToPdbx; Hashtable m_htTokenTinyCLRToPdbx; Pdbx.PdbxFile m_pdbxFile; Pdbx.Assembly m_pdbxAssembly; uint m_idx; string m_name; string m_path; CorDebugAssembly m_primaryAssembly; bool m_isFrameworkAssembly; public CorDebugAssembly (CorDebugProcess process, string name, Pdbx.PdbxFile pdbxFile, uint idx) { m_process = process; m_appDomain = null; m_name = name; m_pdbxFile = pdbxFile; m_pdbxAssembly = (pdbxFile != null) ? pdbxFile.Assembly : null; m_htTokenCLRToPdbx = new Hashtable (); m_htTokenTinyCLRToPdbx = new Hashtable (); m_idx = idx; m_primaryAssembly = null; m_isFrameworkAssembly = false; if (m_pdbxAssembly != null) { if (!string.IsNullOrEmpty (pdbxFile.PdbxPath)) { string pth = pdbxFile.PdbxPath.ToLower (); if (pth.Contains (@"\buildoutput\")) { #region V4_1_FRAMEWORK_ASSEMBLIES List<string> frameworkAssemblies = new List<string> { "mfdpwsclient", "mfdpwsdevice", "mfdpwsextensions", "mfwsstack", "microsoft.spot.graphics", "microsoft.spot.hardware", "microsoft.spot.hardware.serialport", "microsoft.spot.hardware.usb", "microsoft.spot.ink", "microsoft.spot.io", "microsoft.spot.native", "microsoft.spot.net", "microsoft.spot.net.security", "microsoft.spot.time", "microsoft.spot.tinycore", "microsoft.spot.touch", "mscorlib", "system.http", "system.io", "system.net.security", "system", "system.xml.legacy", "system.xml", }; #endregion // V4_1_FRAMEWORK_ASSEMBLIES m_isFrameworkAssembly = (frameworkAssemblies.Contains (name.ToLower ())); } else { m_isFrameworkAssembly = pdbxFile.PdbxPath.ToLower().Contains(Path.PathSeparator + ".net micro framework" + Path.PathSeparator); } } m_pdbxAssembly.CorDebugAssembly = this; foreach (Pdbx.Class c in m_pdbxAssembly.Classes) { AddTokenToHashtables (c.Token, c); foreach (Pdbx.Field field in c.Fields) { AddTokenToHashtables (field.Token, field); } foreach (Pdbx.Method method in c.Methods) { AddTokenToHashtables (method.Token, method); } } if (File.Exists (Path.ChangeExtension (m_pdbxFile.PdbxPath, ".dll"))) MetaData = ModuleDefinition.ReadModule (Path.ChangeExtension (m_pdbxFile.PdbxPath, ".dll")); else if (File.Exists (Path.ChangeExtension (m_pdbxFile.PdbxPath, ".exe"))) MetaData = ModuleDefinition.ReadModule (Path.ChangeExtension (m_pdbxFile.PdbxPath, ".exe")); if (MetaData != null && File.Exists (Path.ChangeExtension (m_pdbxFile.PdbxPath, ".exe.mdb"))) { DebugData = new Mono.Cecil.Mdb.MdbReaderProvider ().GetSymbolReader (MetaData, Path.ChangeExtension (m_pdbxFile.PdbxPath, ".exe")); MetaData.ReadSymbols (DebugData); } else if (MetaData != null && File.Exists (Path.ChangeExtension (m_pdbxFile.PdbxPath, ".dll.mdb"))) { DebugData = new Mono.Cecil.Mdb.MdbReaderProvider ().GetSymbolReader (MetaData, Path.ChangeExtension (m_pdbxFile.PdbxPath, ".dll")); MetaData.ReadSymbols (DebugData); } } } private bool IsPrimaryAssembly { get { return m_primaryAssembly == null; } } public bool IsFrameworkAssembly { get { return m_isFrameworkAssembly; } } public CorDebugAssembly CreateAssemblyInstance (CorDebugAppDomain appDomain) { CorDebugAssembly assm = (CorDebugAssembly)MemberwiseClone (); assm.m_appDomain = appDomain; assm.m_primaryAssembly = this; return assm; } public static CorDebugAssembly AssemblyFromIdx (uint idx, ArrayList assemblies) { foreach (CorDebugAssembly assembly in assemblies) { if (assembly.Idx == idx) return assembly; } return null; } public static CorDebugAssembly AssemblyFromIndex (uint index, ArrayList assemblies) { return AssemblyFromIdx (TinyCLR_TypeSystem.IdxAssemblyFromIndex (index), assemblies); } public string Name { get { return m_name; } } public bool HasSymbols { get { return m_pdbxAssembly != null; } } private void AddTokenToHashtables (Pdbx.Token token, object o) { m_htTokenCLRToPdbx [token.CLR] = o; m_htTokenTinyCLRToPdbx [token.TinyCLR] = o; } private string FindAssemblyOnDisk () { if (m_path == null && m_pdbxAssembly != null) { string[] pathsToTry = new string[] { // Look next to pdbx file Path.Combine (Path.GetDirectoryName (m_pdbxFile.PdbxPath), m_pdbxAssembly.FileName), // look next to the dll for the SDK (C:\Program Files\Microsoft .NET Micro Framework\<version>\Assemblies\le|be) Path.Combine (Path.GetDirectoryName (m_pdbxFile.PdbxPath), @"..\" + m_pdbxAssembly.FileName), // look next to the dll for the PK (SPOCLIENT\buildoutput\public\<buildtype>\client\pe\le|be) Path.Combine (Path.GetDirectoryName (m_pdbxFile.PdbxPath), @"..\..\dll\" + m_pdbxAssembly.FileName), }; for (int iPath = 0; iPath < pathsToTry.Length; iPath++) { string path = pathsToTry [iPath]; if (File.Exists (path)) { //is this the right file? m_path = path; break; } } } return m_path; } public ModuleDefinition MetaData { get; set; } public CorDebugProcess Process { [System.Diagnostics.DebuggerHidden] get { return m_process; } } public CorDebugAppDomain AppDomain { [System.Diagnostics.DebuggerHidden] get { return m_appDomain; } } public uint Idx { [System.Diagnostics.DebuggerHidden] get { return m_idx; } } private CorDebugFunction GetFunctionFromToken (uint tk, Hashtable ht) { CorDebugFunction function = null; Pdbx.Method method = ht [tk] as Pdbx.Method; if (method != null) { CorDebugClass c = new CorDebugClass (this, method.Class); function = new CorDebugFunction (c, method); } Debug.Assert (function != null); return function; } public CorDebugFunction GetFunctionFromTokenCLR (uint tk) { return GetFunctionFromToken (tk, m_htTokenCLRToPdbx); } public CorDebugFunction GetFunctionFromTokenTinyCLR (uint tk) { if (HasSymbols) { return GetFunctionFromToken (tk, m_htTokenTinyCLRToPdbx); } else { uint index = TinyCLR_TypeSystem.ClassMemberIndexFromTinyCLRToken (tk, this); WireProtocol.Commands.Debugging_Resolve_Method.Result resolvedMethod = this.Process.Engine.ResolveMethod (index); Debug.Assert (TinyCLR_TypeSystem.IdxAssemblyFromIndex (resolvedMethod.m_td) == this.Idx); uint tkMethod = TinyCLR_TypeSystem.SymbollessSupport.MethodDefTokenFromTinyCLRToken (tk); uint tkClass = TinyCLR_TypeSystem.TinyCLRTokenFromTypeIndex (resolvedMethod.m_td); CorDebugClass c = GetClassFromTokenTinyCLR (tkClass); return new CorDebugFunction (c, tkMethod); } } public Pdbx.ClassMember GetPdbxClassMemberFromTokenCLR (uint tk) { return m_htTokenCLRToPdbx [tk] as Pdbx.ClassMember; } private CorDebugClass GetClassFromToken (uint tk, Hashtable ht) { CorDebugClass cls = null; Pdbx.Class c = ht [tk] as Pdbx.Class; if (c != null) { cls = new CorDebugClass (this, c); } return cls; } public CorDebugClass GetClassFromTokenCLR (uint tk) { return GetClassFromToken (tk, m_htTokenCLRToPdbx); } public CorDebugClass GetClassFromTokenTinyCLR (uint tk) { if (HasSymbols) return GetClassFromToken (tk, m_htTokenTinyCLRToPdbx); else return new CorDebugClass (this, TinyCLR_TypeSystem.SymbollessSupport.TypeDefTokenFromTinyCLRToken (tk)); } public void SetJmcStatus (bool fJMC) { if (this.HasSymbols) { if (this.Process.Engine.Info_SetJMC (fJMC, ReflectionDefinition.Kind.REFLECTION_ASSEMBLY, TinyCLR_TypeSystem.IndexFromIdxAssemblyIdx (this.Idx))) { if (!this.m_isFrameworkAssembly) { //now update the debugger JMC state... foreach (Pdbx.Class c in this.m_pdbxAssembly.Classes) { foreach (Pdbx.Method m in c.Methods) { m.IsJMC = fJMC; } } } } } } public ISymbolReader DebugData { get; set; } #region IDisposable implementation public void Dispose () { if (DebugData != null) { DebugData.Dispose (); DebugData = null; } } #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 Internal.Cryptography.Pal; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate2Collection : X509CertificateCollection { public X509Certificate2Collection() { } public X509Certificate2Collection(X509Certificate2 certificate) { Add(certificate); } public X509Certificate2Collection(X509Certificate2[] certificates) { AddRange(certificates); } public X509Certificate2Collection(X509Certificate2Collection certificates) { AddRange(certificates); } public new X509Certificate2 this[int index] { get { return (X509Certificate2)(base[index]); } set { base[index] = value; } } public int Add(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); return base.Add(certificate); } public void AddRange(X509Certificate2[] certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Length; i++) { Add(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Remove(certificates[j]); } throw; } } public void AddRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Count; i++) { Add(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Remove(certificates[j]); } throw; } } public bool Contains(X509Certificate2 certificate) { // This method used to throw ArgumentNullException, but it has been deliberately changed // to no longer throw to match the behavior of X509CertificateCollection.Contains and the // IList.Contains implementation, which do not throw. return base.Contains(certificate); } public byte[] Export(X509ContentType contentType) { return Export(contentType, password: null); } public byte[] Export(X509ContentType contentType, string password) { using (IExportPal storePal = StorePal.LinkFromCertificateCollection(this)) { return storePal.Export(contentType, password); } } public X509Certificate2Collection Find(X509FindType findType, object findValue, bool validOnly) { if (findValue == null) throw new ArgumentNullException(nameof(findValue)); return FindPal.FindFromCollection(this, findType, findValue, validOnly); } public new X509Certificate2Enumerator GetEnumerator() { return new X509Certificate2Enumerator(this); } public void Import(byte[] rawData) { Import(rawData, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet); } public void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null) throw new ArgumentNullException(nameof(rawData)); using (ILoaderPal storePal = StorePal.FromBlob(rawData, password, keyStorageFlags)) { storePal.MoveTo(this); } } public void Import(string fileName) { Import(fileName, password: null, keyStorageFlags: X509KeyStorageFlags.DefaultKeySet); } public void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); using (ILoaderPal storePal = StorePal.FromFile(fileName, password, keyStorageFlags)) { storePal.MoveTo(this); } } public void Insert(int index, X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); base.Insert(index, certificate); } public void Remove(X509Certificate2 certificate) { if (certificate == null) throw new ArgumentNullException(nameof(certificate)); base.Remove(certificate); } public void RemoveRange(X509Certificate2[] certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Length; i++) { Remove(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Add(certificates[j]); } throw; } } public void RemoveRange(X509Certificate2Collection certificates) { if (certificates == null) throw new ArgumentNullException(nameof(certificates)); int i = 0; try { for (; i < certificates.Count; i++) { Remove(certificates[i]); } } catch { for (int j = 0; j < i; j++) { Add(certificates[j]); } throw; } } } }
/* * Uri.cs - Implementation of "System.Uri" class * * Copyright (C) 2002 Free Software Foundation, Inc. * * Contributed by Stephen Compall <rushing@sigecom.net> * Contributions by Gerard Toonstra <toonstra@ntlworld.com> * Contributions by Rich Baumann <biochem333@nyc.rr.com> * Contributions by Gopal V <gopalv82@symonds.net> * Contributions by Rhys Weatherley <rweather@southern-storm.com.au> * * 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 */ using System; using System.IO; using System.Net; using System.Text; using System.Private; using System.Net.Sockets; using System.Collections; using System.Runtime.Serialization; namespace System { #if CONFIG_SERIALIZATION [Serializable] public class Uri : MarshalByRefObject, ISerializable #else public class Uri : MarshalByRefObject #endif { public static readonly String SchemeDelimiter = "://"; public static readonly String UriSchemeFile = "file"; public static readonly String UriSchemeFtp = "ftp"; public static readonly String UriSchemeGopher = "gopher"; public static readonly String UriSchemeHttp = "http"; public static readonly String UriSchemeHttps = "https"; public static readonly String UriSchemeMailto = "mailto"; public static readonly String UriSchemeNews = "news"; public static readonly String UriSchemeNntp = "nntp"; /* Fast Regex based URI parser */ private static Regex uriRegex = null; private static bool hasFastRegex = false; private static readonly String hexChars = "0123456789ABCDEF"; private static Hashtable schemes=new Hashtable(10); // avoid expanding of hashtable /* State specific fields */ private bool userEscaped = false ; private UriHostNameType hostNameType = UriHostNameType.Unknown; private String scheme = null; private String delim = null; private String userinfo = null; private String host = null; private int port = -1; private String portString = null; private String path = null; private String query = null; private String fragment = null; static Uri() { /* RFC2396 : Appendix B As described in Section 4.3, the generic URI syntax is not sufficient to disambiguate the components of some forms of URI. Since the "greedy algorithm" described in that section is identical to the disambiguation method used by POSIX regular expressions, it is natural and commonplace to use a regular expression for parsing ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? 12 3 4 5 6 7 8 9 (Modified to support mailto: syntax as well) */ String regularexpression= "^(([^:/?#]+):)?"+ // scheme "(" + "(//)?"+ // delim "(([^@]+)@)?" + // userinfo "([^/?#:]*)?" + // host "(:([^/?#]+))?"+ // port ")"+ "([^?#]*)"+ // path "(\\?([^#]*))?"+ // query "(#(.*))?$"; // fragment /* Indexing 0 --> full 2 --> scheme 4 --> delim 6 --> userinfo 7 --> host 9 --> port 10 --> path 11 --> query 13 --> fragment */ /* Insert grouping symbols */ regularexpression=regularexpression.Replace("(","\\("); regularexpression=regularexpression.Replace(")","\\)"); try { uriRegex = new Regex(regularexpression, RegexSyntax.PosixCommon); /* Really test this expression on each start-up, use the * backup SlowParse() if this library fails to work */ String input= "https://gnu:gnu@www.gnu.org:443/free/software?id=for#all"; RegexMatch[] matches = uriRegex.Match( input, RegexMatchOptions.Default, 16); hasFastRegex = true; int [][] expected = new int[][] { new int[]{0,56}, new int[]{0,6}, new int[]{0,5}, new int[]{6,31}, new int[]{6,8}, new int[]{8,16}, new int[]{8,15}, new int[]{16,27}, new int[]{27,31}, new int[]{28,31}, new int[]{31,45}, new int[]{45,52}, new int[]{46,52}, new int[]{52,56}, new int[]{53,56}, }; for(int i=0;i< matches.Length && hasFastRegex ; i++) { hasFastRegex = hasFastRegex && (matches[i].start == expected[i][0]) && (matches[i].end == expected[i][1]) ; } } catch { if(uriRegex!=null) { uriRegex.Dispose(); uriRegex = null; } hasFastRegex = false; } schemes.Add(UriSchemeFile, new UriScheme(-1, "://")); schemes.Add(UriSchemeFtp, new UriScheme(23, "://")); schemes.Add(UriSchemeGopher, new UriScheme(70, "://")); schemes.Add(UriSchemeHttp, new UriScheme(80, "://")); schemes.Add(UriSchemeHttps, new UriScheme(443, "://")); schemes.Add(UriSchemeNntp, new UriScheme(119, "://")); schemes.Add(UriSchemeMailto, new UriScheme(25, ":")); schemes.Add(UriSchemeNews, new UriScheme(-1, ":")); } public Uri(String uriString) : this(uriString, false) { } public Uri(String uriString, bool dontEscape) { userEscaped = dontEscape; ParseString(uriString,true); Escape(); Canonicalize(); } #if CONFIG_SERIALIZATION protected Uri(SerializationInfo info, StreamingContext context) : this(info.GetString("AbsoluteUri"), true) { // Nothing to do here. } #endif private Uri() { /* Be warned , using this is kinda ugly in the end */ } public Uri(Uri baseUri, String relativeUri) : this(baseUri, relativeUri, false) { } public Uri(Uri baseUri, String relativeUri, bool dontEscape) { if(relativeUri == null) { throw new ArgumentNullException("relativeUri"); } userEscaped = dontEscape; this.scheme = baseUri.scheme; this.delim = baseUri.delim; this.host = baseUri.host; this.port = baseUri.port; this.userinfo = baseUri.userinfo; if(relativeUri == String.Empty) { this.path = baseUri.path; this.query = baseUri.query; this.fragment = baseUri.fragment; return; } Uri uri=new Uri(); uri.ParseString(relativeUri,false); if(uri.scheme == null) { this.path = this.path + uri.path; this.query = uri.query; this.fragment = uri.fragment; } else if(uri.scheme == this.scheme && uri.delim == ":") { this.path = this.path + uri.Authority + uri.path; this.query = uri.query; this.fragment = uri.fragment; } else if(uri.scheme == this.scheme && uri.delim == "://") { ParseString(relativeUri,true); } else if(uri.scheme != this.scheme) { ParseString(relativeUri,true); } Escape(); Canonicalize(); } protected virtual void Canonicalize() { if(this.path!=null) { this.path = this.path.Replace('\\', '/'); while (this.path.IndexOf("//") >= 0) // double-slashes to strip { this.path = this.path.Replace("//", "/"); } path = StripMetaDirectories(path); } } private String StripMetaDirectories(String oldpath) { int toBeRemoved = 0; String[] dirs = oldpath.Split('/'); for (int curDir = dirs.Length - 1; curDir > 0 ; curDir--) { if (dirs[curDir] == "..") { toBeRemoved++; dirs[curDir] = null; } else if (dirs[curDir] == ".") { dirs[curDir] = null; } else if (toBeRemoved > 0) // remove this one { toBeRemoved--; dirs[curDir] = null; } } if(dirs[0].Length==0) // leading slash { dirs[0]=null; } if (toBeRemoved > 0) // wants to delete root throw new UriFormatException (S._("Arg_UriPathAbs")); StringBuilder newpath = new StringBuilder(oldpath.Length); foreach (String dir in dirs) { if (dir!=null) { newpath.Append('/').Append(dir); } } // we always must have at least a slash // general assumption that path based systems use "://" instead // of the ":" only delimiter if (delim=="://") { if(newpath.Length == 0) { newpath.Append('/'); } } return newpath.ToString(); } private static bool IsDnsName(String name) { foreach(String tok in name.Split('.')) { if(tok.Length==0 || !Char.IsLetter(tok[0])) return false; for(int i=1; i< tok.Length ; i++) { if(!Char.IsLetterOrDigit(tok[i]) && tok[i]!='-' && tok[i]!='_') { return false; } } } return true; } public static UriHostNameType CheckHostName(String name) { if (name == null || name.Length == 0) return UriHostNameType.Unknown; if(IsDnsName(name)) { return UriHostNameType.Dns; } try { switch(IPAddress.Parse(name).AddressFamily) { case AddressFamily.InterNetwork: return UriHostNameType.IPv4; case AddressFamily.InterNetworkV6: return UriHostNameType.IPv6; } } catch (FormatException) { } return UriHostNameType.Unknown; } public static bool CheckSchemeName(String schemeName) { if (schemeName == null || schemeName.Length == 0) return false; if (!Char.IsLetter(schemeName[0])) { return false; } for (int i = 1; i < schemeName.Length ; i++) { if((!Char.IsLetterOrDigit(schemeName[i])) && ("+.-".IndexOf(schemeName[i]) == -1)) { return false; } } return true; } protected virtual void CheckSecurity() { // Nothing to do here. } public override bool Equals(Object comparand) { if(comparand == null) { return false; } Uri uri = (comparand as Uri); if(uri == null) { String s = (comparand as String); if(s==null) return false; try { uri = new Uri(s); } catch { return false; } } return ((this.Authority == uri.Authority) && (this.path == uri.path) && (this.scheme == uri.scheme) && (this.delim == uri.delim)); } protected virtual void Escape() { if(!userEscaped) { if(this.host!=null) { this.host = EscapeStringInternal(this.host, true, false); } if(this.path!=null) { this.path = EscapeStringInternal(this.path, true, true); } if(this.query!=null) { this.query = EscapeStringInternal(this.query, true, true); } if(this.fragment!=null) { this.fragment = EscapeStringInternal(this.fragment, false, true); } } } protected static String EscapeString(String str) { if (str == null || str.Length == 0) return String.Empty; return EscapeStringInternal(str,true, true); } internal static String EscapeStringInternal (String str, bool escapeHex, bool escapeBrackets) { StringBuilder sb = new StringBuilder(); for(int i=0; i < str.Length; i++) { char c = str[i]; if((c <= 0x20 || c>=0x7f) || /* non-ascii */ (("<>%\"{}|\\^`").IndexOf(c) != -1) || (escapeHex && c=='#') || (escapeBrackets && (c=='[' || c==']'))) { sb.Append(HexEscape(c)); } else { sb.Append(c); } } return sb.ToString(); } public static int FromHex(char digit) { if (digit >= '0' && digit <= '9') return digit - '0'; else if (digit >= 'A' && digit <= 'F') return digit - 55; else if (digit >= 'a' && digit <= 'f') return digit - 87; else throw new ArgumentException(S._("Arg_HexDigit"), "digit"); } public override int GetHashCode() { String full = this.ToString(); int hash = full.IndexOf('#'); if (hash == -1) return full.GetHashCode(); else return full.Substring(0, hash).GetHashCode(); } public String GetLeftPart(UriPartial part) { switch (part) { case UriPartial.Path: return String.Concat(this.scheme , this.delim, this.Authority, this.path); case UriPartial.Authority: return String.Concat(this.scheme, this.delim, this.Authority); case UriPartial.Scheme: return String.Concat(this.scheme, this.delim); default: throw new ArgumentException(S._("Arg_UriPartial")); } } public static String HexEscape(char character) { if (character > 255) throw new ArgumentOutOfRangeException("character"); String retval="%"; retval += hexChars[(character >> 4) & 0x0F]; retval += hexChars[(character) & 0x0F]; return retval; } private static char BinHexToChar(char hex1, char hex2) { hex1=Char.ToUpper(hex1); hex2=Char.ToUpper(hex2); return (char)((hexChars.IndexOf(hex1) << 4) | (hexChars.IndexOf(hex2))); } public static char HexUnescape(String pattern, ref int index) { if(pattern == null) { throw new ArgumentNullException("pattern"); } if(pattern.Length == 0) { throw new ArgumentException("pattern"); } if(((pattern.Length < index) || (index < 0))) { throw new ArgumentOutOfRangeException("index"); } if(pattern.Length >= (index+3) && pattern[index] == '%') { if(IsHexDigit(pattern[index+1]) && IsHexDigit(pattern[index+2])) { index+=3; return BinHexToChar(pattern[index-2],pattern[index-1]); } } index++; return pattern[index-1]; } protected virtual bool IsBadFileSystemCharacter(char character) { return ("\"<>|\r\n".IndexOf(character) != -1); } protected static bool IsExcludedCharacter(char character) { return ((character < 0x20 || character > 0x7F) /* non-ascii */ || ("<>#%\"{}|\\^[]`".IndexOf(character) != -1)); /* excluded ascii */ } public static bool IsHexDigit(char character) { return ( (character >= '0' && character <= '9') || (character >= 'A' && character <= 'F') || (character >= 'a' && character <= 'f') ); } public static bool IsHexEncoding(String pattern, int index) { if (index >= 0 && pattern.Length - index >= 3) return ((pattern[index] == '%') && IsHexDigit(pattern[index+1]) && IsHexDigit(pattern[index+2])); else return false; } protected virtual bool IsReservedCharacter(char character) { return (";/:@&=+$,".IndexOf(character) != -1); } public String MakeRelative(Uri toUri) { if((this.Scheme != toUri.Scheme) || (this.Authority != this.Authority)) { return toUri.ToString(); } if(this.path == toUri.path) { return String.Empty; } String []seg1 = this.Segments; String []seg2 = toUri.Segments; int k; int min = seg1.Length; if(min > seg2.Length) min = seg2.Length; for(k=0;k < min ; k++) { if(seg1[k] != seg2[k]) { break; } } StringBuilder sb = new StringBuilder(); for(int i = k ; i < seg1.Length ; i++) { if(seg1[i].EndsWith("/")) { sb.Append("../"); } } for(int i = k ; i < seg2.Length ; i++) { sb.Append(seg2[i]); } return sb.ToString(); } protected virtual void Parse() { } private void ParseString(String uriString,bool reportErrors) { if(hasFastRegex) { FastParse(uriString); } else { SlowParse(uriString); } if(reportErrors) { CheckParsed(); } } private void CheckParsed() { if((this.host==null || this.host=="") && (this.scheme=="file" || this.scheme==null)) { this.scheme=UriSchemeFile; this.delim="://"; } else { this.hostNameType = CheckHostName(this.host); if(hostNameType==UriHostNameType.Unknown) { throw new UriFormatException(S._("Arg_UriHostName")); } } if(!CheckSchemeName(this.scheme)) { throw new UriFormatException(S._("Arg_UriScheme")); } if(portString!= null) { try { int value=Int32.Parse(portString); port = value; } catch(FormatException) { this.port = -1; } catch(OverflowException) { throw new UriFormatException (S._("Arg_UriPort")); } } else { this.port = DefaultPortForScheme(this.scheme); } } private static String MatchToString(String str, RegexMatch[] matches, int index) { if(matches==null || matches.Length <= index) return null; if(matches[index].start == -1) return null; return str.Substring(matches[index].start, matches[index].end - matches[index].start); } private void FastParse(String uriString) { RegexMatch[] matches = uriRegex.Match( uriString, RegexMatchOptions.Default, 16); if(matches == null) { throw new UriFormatException(); } /* 0 --> full 2 --> scheme 4 --> delim 6 --> userinfo 7 --> host 9 --> port 10 --> path 11 --> query 13 --> fragment */ this.scheme = MatchToString(uriString, matches,2); this.delim = ":"+MatchToString(uriString, matches, 4); this.userinfo = MatchToString(uriString, matches, 6); this.host = MatchToString(uriString, matches,7); this.portString = MatchToString(uriString, matches,9); this.path = MatchToString(uriString, matches, 10); this.query = MatchToString(uriString, matches, 11); this.fragment = MatchToString(uriString, matches,13); } private void SlowParse(String uriString) { throw new NotImplementedException("SlowParse"); } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append(this.scheme); sb.Append(this.delim); sb.Append(Authority); sb.Append(PathAndQuery); sb.Append(this.fragment); if(this.userEscaped) { return sb.ToString(); } else { return Unescape(sb.ToString()); } } protected virtual String Unescape(String str) { if(str == null || str.Length==0) return String.Empty; StringBuilder sb = new StringBuilder(str.Length); for(int i=0; i < str.Length;) { sb.Append(HexUnescape(str, ref i)); } return sb.ToString(); } public String AbsolutePath { get { if(path == null) return "/"; return path; } } public String AbsoluteUri { get { return this.ToString(); } } public String Authority { get { StringBuilder sb=new StringBuilder(); if(this.userinfo!=null) { sb.Append(this.userinfo); sb.Append('@'); } if(this.host!=null) { sb.Append(this.host); } if(this.port!=-1 && this.port!=DefaultPortForScheme(this.scheme)) { sb.Append(':'); sb.Append(this.port); } return sb.ToString(); } } public String Fragment { get { return fragment; } } public String Host { get { return host; } } public UriHostNameType HostNameType { get { return hostNameType; } } public bool IsDefaultPort { get { if(port == DefaultPortForScheme(scheme)) { return true; } return false; } } public bool IsFile { get { return String.Equals(this.scheme, Uri.UriSchemeFile); } } public bool IsLoopback { get { try { IPAddress ip=IPAddress.Parse(this.host); return IPAddress.IsLoopback(ip); } catch(FormatException) // should be a name { try { IPHostEntry iph = Dns.GetHostByName(this.host); foreach(IPAddress ip in iph.AddressList) { if(IPAddress.IsLoopback(ip))return true; } } catch(SocketException) // cannot resolve name either { return false; } } return false; // no way out now } } public String LocalPath { get { String retval = this.AbsolutePath; if (this.IsFile) { if (Path.DirectorySeparatorChar != '/') retval = retval.Replace('/', Path.DirectorySeparatorChar); retval = this.Unescape(retval); } return retval; } } public String PathAndQuery { get { String abspath = this.AbsolutePath; if (String.Equals(abspath, "")) return this.Query; else if (String.Equals(this.query, "")) return abspath; else return String.Concat(this.path, this.query); } } public int Port { get { return port; } } public String Query { get { return this.query; } } public String Scheme { get { return this.scheme; } } #if !ECMA_COMPAT public #else private #endif String [] Segments { get { if(path == null || path == String.Empty) { return new String[0]; } if(path == "/") { return new String[]{"/"}; } String [] toks = path.Split('/'); bool endSlash = path.EndsWith("/"); for(int i=0;i<toks.Length-1; i++) { toks[i]+="/"; } String [] segments = new String[toks.Length - (endSlash ? 1 : 0)]; Array.Copy(toks, segments, toks.Length - (endSlash ? 1 :0)); return segments; } } public bool UserEscaped { get { return this.userEscaped; } } public String UserInfo { get { return this.userinfo; } } private class UriScheme { public String delim; public int port; public UriScheme(int port, String delim) { this.port = port; this.delim = delim; } } internal static int DefaultPortForScheme(String name) { UriScheme entry=(UriScheme) schemes[name]; if((entry=(UriScheme)schemes[name])!=null) { return entry.port; } return -1; } internal static String DefaultDelimiterForScheme (String name) { UriScheme entry; if((entry=(UriScheme)schemes[name])!=null) { return entry.delim; } return "://"; } // Determine if this URI is a prefix of a specified URI. internal bool IsPrefix(Uri uri) { String strhost = this.Host; String specifiedstrhost = uri.Host; String strpath = this.LocalPath; String specifiedstrpath=uri.LocalPath; String strscheme = this.Scheme; String specifiedstrscheme = uri.Scheme; if(String.Compare(strscheme, specifiedstrscheme, true) == 0 && String.Compare(strhost, specifiedstrhost, true) == 0) { if(String.CompareOrdinal(strpath, specifiedstrpath) == 0) { //if paths exactly the same, return true return true; } else if(String.CompareOrdinal(strpath, strpath.Length, "/", 0, 1) == 0 ) { //path string has / at the end of it, so direct comparison can be made. if (String.CompareOrdinal(strpath, 0, specifiedstrpath, 0, strpath.Length) == 0) { return true; } else { return false; } } else { // a / must be appended to this.LocalPath to do comparison strpath = strpath + "/"; if (String.CompareOrdinal(strpath, 0, specifiedstrpath, 0, strpath.Length) == 0) { return true; } else { return false; } } } else { return false; } } // Determine if this is an UNC path. public bool IsUnc { get { // We don't support UNC paths at present. return false; } } #if CONFIG_SERIALIZATION // Serialize this URI object. void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { serializationInfo.AddValue("AbsoluteUri", AbsoluteUri); } #endif } }//namespace
using System; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets; using System.IO; using InTheHand.Net; using InTheHand.Net.Sockets; using InTheHand.Net.Bluetooth; using InTheHand.Windows.Forms; namespace ObjectPushApplication { /// <summary> /// Used to push objects. /// </summary> public class ObjectPushForm : System.Windows.Forms.Form { private System.Windows.Forms.ComboBox cbDevices; private System.Windows.Forms.Button btnBeam; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.Button btnIr; private BluetoothClient bc; private System.Windows.Forms.Button btnBluetooth; private System.Windows.Forms.OpenFileDialog ofdFileToBeam; private System.Windows.Forms.SaveFileDialog sfdReceivedFile; private Button button1; private IrDAClient ic; public ObjectPushForm() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // //InTheHand.Net.Bluetooth.Broadcom.BtIf i = new InTheHand.Net.Bluetooth.Broadcom.BtIf(); BluetoothRadio br = BluetoothRadio.PrimaryRadio; if(br!=null) { if (br.Mode == RadioMode.PowerOff) { br.Mode = RadioMode.Connectable; } } else { MessageBox.Show("Your device uses an unsupported Bluetooth software stack"); btnBluetooth.Enabled = false; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.cbDevices = new System.Windows.Forms.ComboBox(); this.btnBeam = new System.Windows.Forms.Button(); this.btnBluetooth = new System.Windows.Forms.Button(); this.btnIr = new System.Windows.Forms.Button(); this.ofdFileToBeam = new System.Windows.Forms.OpenFileDialog(); this.sfdReceivedFile = new System.Windows.Forms.SaveFileDialog(); this.button1 = new System.Windows.Forms.Button(); // // cbDevices // this.cbDevices.Location = new System.Drawing.Point(56, 160); this.cbDevices.Size = new System.Drawing.Size(120, 22); // // btnBeam // this.btnBeam.Location = new System.Drawing.Point(184, 160); this.btnBeam.Size = new System.Drawing.Size(48, 24); this.btnBeam.Text = "Beam"; this.btnBeam.Click += new System.EventHandler(this.btnBeam_Click); // // btnBluetooth // this.btnBluetooth.Location = new System.Drawing.Point(8, 128); this.btnBluetooth.Size = new System.Drawing.Size(168, 24); this.btnBluetooth.Text = "Beam object via Bluetooth"; this.btnBluetooth.Click += new System.EventHandler(this.btnBluetooth_Click); // // btnIr // this.btnIr.Location = new System.Drawing.Point(8, 160); this.btnIr.Size = new System.Drawing.Size(40, 24); this.btnIr.Text = "IR"; this.btnIr.Click += new System.EventHandler(this.btnIr_Click); // // ofdFileToBeam // this.ofdFileToBeam.Filter = "All Files|*.*"; // // button1 // this.button1.Enabled = false; this.button1.Location = new System.Drawing.Point(184, 128); this.button1.Size = new System.Drawing.Size(48, 20); this.button1.Text = "button1"; this.button1.Visible = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // ObjectPushForm // this.ClientSize = new System.Drawing.Size(240, 192); this.Controls.Add(this.button1); this.Controls.Add(this.btnIr); this.Controls.Add(this.btnBluetooth); this.Controls.Add(this.btnBeam); this.Controls.Add(this.cbDevices); this.Menu = this.mainMenu1; this.MinimizeBox = false; this.Text = "Object Push"; this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing); } #endregion /// <summary> /// The main entry point for the application. /// </summary> static void Main() { Application.Run(new ObjectPushForm()); } protected override void OnLoad(EventArgs e) { try { bc = new BluetoothClient(); } catch { btnBluetooth.Enabled = false; } try { ic = new IrDAClient(); } catch { btnIr.Enabled = false; } base.OnLoad (e); } private Image backgroundImage = null; protected override void OnPaint(PaintEventArgs e) { if (backgroundImage == null) { System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ThirtyTwoFeet.32feet.128.png"); backgroundImage = new Bitmap(s); } e.Graphics.DrawImage(backgroundImage, 0,0); base.OnPaint (e); } private void btnBeam_Click(object sender, System.EventArgs e) { if(cbDevices.SelectedIndex > -1) { IrDADeviceInfo idi = (IrDADeviceInfo)cbDevices.SelectedItem; if(ofdFileToBeam.ShowDialog()==DialogResult.OK) { Cursor.Current = Cursors.WaitCursor; System.Uri uri = new Uri("obex://" + idi.DeviceAddress.ToString() + "/" + System.IO.Path.GetFileName(ofdFileToBeam.FileName)); ObexWebRequest request = new ObexWebRequest(uri); Stream requestStream = request.GetRequestStream(); FileStream fs = File.OpenRead(ofdFileToBeam.FileName); byte[] buffer = new byte[1024]; int readBytes = 1; while (readBytes != 0) { readBytes = fs.Read(buffer, 0, buffer.Length); requestStream.Write(buffer, 0, readBytes); } requestStream.Close(); ObexWebResponse response = (ObexWebResponse)request.GetResponse(); MessageBox.Show(response.StatusCode.ToString()); response.Close(); Cursor.Current = Cursors.Default; } } } private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { bc.Dispose(); } private void btnBluetooth_Click(object sender, System.EventArgs e) { // use the new select bluetooth device dialog SelectBluetoothDeviceDialog sbdd = new SelectBluetoothDeviceDialog(); sbdd.ShowAuthenticated = true; sbdd.ShowRemembered = true; sbdd.ShowUnknown = true; if(sbdd.ShowDialog()==DialogResult.OK) { if(ofdFileToBeam.ShowDialog()==DialogResult.OK) { Cursor.Current = Cursors.WaitCursor; System.Uri uri = new Uri("obex://" + sbdd.SelectedDevice.DeviceAddress.ToString() + "/" + System.IO.Path.GetFileName(ofdFileToBeam.FileName)); ObexWebRequest request = new ObexWebRequest(uri); request.ReadFile(ofdFileToBeam.FileName); ObexWebResponse response = (ObexWebResponse)request.GetResponse(); MessageBox.Show(response.StatusCode.ToString()); response.Close(); Cursor.Current = Cursors.Default; } } } private void btnIr_Click(object sender, System.EventArgs e) { Cursor.Current = Cursors.WaitCursor; cbDevices.DisplayMember = "DeviceName"; cbDevices.ValueMember = "DeviceAddress"; cbDevices.DataSource = ic.DiscoverDevices(); Cursor.Current = Cursors.Default; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("ObexWebRequest does not support GET."); // // SelectBluetoothDeviceDialog sbdd = new SelectBluetoothDeviceDialog(); sbdd.ShowAuthenticated = true; sbdd.ShowRemembered = true; sbdd.ShowUnknown = true; if (sbdd.ShowDialog() == DialogResult.OK) { Cursor.Current = Cursors.WaitCursor; System.Uri uri = new Uri("obex://" + sbdd.SelectedDevice.DeviceAddress.ToString()); ObexWebRequest request = new ObexWebRequest(uri); request.Method = "GET"; request.ContentType = InTheHand.Net.Mime.MediaTypeNames.ObjectExchange.Capabilities; //request.ReadFile("C:\\t4s.log"); //request.ContentType = InTheHand.Net.Mime.MediaTypeNames.Text.Plain; ObexWebResponse response = (ObexWebResponse)request.GetResponse(); response.Close(); Cursor.Current = Cursors.Default; } } } }
#region License // Copyright 2013-2014 Matthew Ducker // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Threading.Tasks; using BitManipulator; using Nessos.LinqOptimizer.CSharp; using Obscur.Core.Cryptography; using Obscur.Core.Cryptography.Authentication; using Obscur.Core.Cryptography.Ciphers; using Obscur.Core.Cryptography.KeyAgreement.Primitives; using Obscur.Core.Cryptography.KeyConfirmation; using Obscur.Core.Cryptography.KeyDerivation; using Obscur.Core.DTO; using Obscur.Core.Packaging.Multiplexing; using Obscur.Core.Packaging.Parsing; namespace Obscur.Core.Packaging { /// <summary> /// Reads and extracts ObscurCore packages. /// </summary> public sealed class PackageReader : IDisposable { #region Instance variables private readonly Dictionary<Guid, byte[]> _itemPreKeys = new Dictionary<Guid, byte[]>(); private readonly Manifest _manifest; /// <summary> /// Configuration of the manifest cipher. Must be serialised into ManifestHeader when writing package. /// </summary> private readonly IManifestCryptographySchemeConfiguration _manifestCryptoConfig; private readonly ManifestHeader _manifestHeader; /// <summary> /// Stream that package is being read from. /// </summary> private readonly Stream _readingStream; private bool _closeOnDispose; /// <summary> /// Offset at which the payload starts. /// </summary> private long _readingPayloadStreamOffset; #endregion #region Properties /// <summary> /// Format version specification of the data transfer objects and logic used in the package. /// </summary> public int FormatVersion { get { return _manifestHeader.FormatVersion; } } /// <summary> /// Cryptographic scheme used for the manifest. /// </summary> public ManifestCryptographyScheme ManifestCryptoScheme { get { return _manifestHeader.CryptographyScheme; } } /// <summary> /// Configuration of symmetric cipher used for encryption of the manifest. /// </summary> public ICipherConfiguration ManifestCipher { get { return _manifestCryptoConfig.SymmetricCipher; } } /// <summary> /// Configuration of function used in verifying the authenticity/integrity of the manifest. /// </summary> public IAuthenticationConfiguration ManifestAuthentication { get { return _manifestCryptoConfig.Authentication; } } /// <summary> /// Configuration of key derivation used to derive encryption and authentication keys from prior key material. /// These keys are used in those functions of manifest encryption/authentication, respectively. /// </summary> public IKeyDerivationConfiguration ManifestKeyDerivation { get { return _manifestCryptoConfig.KeyDerivation; } } /// <summary> /// Configuration of key confirmation used for confirming the cryptographic key /// to be used as the basis for key derivation. /// </summary> public IAuthenticationConfiguration ManifestKeyConfirmation { get { return _manifestCryptoConfig.KeyConfirmation; } } /// <summary> /// Layout scheme configuration of the items in the payload. /// </summary> public PayloadLayoutScheme PayloadLayout { get { return _manifest.PayloadConfiguration.SchemeName.ToEnum<PayloadLayoutScheme>(); } } /// <summary> /// Items in the package payload. /// </summary> public IEnumerable<IPayloadItem> PayloadItems { get { return _manifest.PayloadItems.Select(item => item as IPayloadItem); } } #endregion #region Constructors (including static methods that return a PackageReader) /// <summary> /// Creates a package reader configured to read from a provided stream (containing the package). /// </summary> /// <remarks> /// Immediately reads package manifest header and manifest. /// </remarks> /// <param name="stream">Stream to read the package from.</param> /// <param name="keyProvider">Service that supplies possible cryptographic keys.</param> /// <param name="closeOnDispose"> /// If <c>true</c>, <paramref name="stream" /> will be closed when the reader is disposed. /// </param> internal PackageReader(Stream stream, IKeyProvider keyProvider, bool closeOnDispose = false) { _readingStream = stream; _closeOnDispose = closeOnDispose; ManifestCryptographyScheme mCryptoScheme; _manifestHeader = ReadManifestHeader(_readingStream, out mCryptoScheme, out _manifestCryptoConfig); _manifest = ReadManifest(keyProvider, mCryptoScheme); } /// <summary> /// Creates a package reader configured to read from a file. /// </summary> /// <param name="filePath">Path of the file containing a package.</param> /// <param name="keyProvider">Service that supplies possible cryptographic keys.</param> /// <returns>Package ready for reading.</returns> /// <exception cref="ArgumentException">File does not exist at the path specified.</exception> public static PackageReader FromFile(string filePath, IKeyProvider keyProvider) { var file = new FileInfo(filePath); if (file.Exists == false) { throw new ArgumentException(); } return FromStream(file.OpenRead(), keyProvider); } /// <summary> /// Creates a package reader configured to read from a provided stream (containing the package). /// </summary> /// <remarks> /// Immediately reads package manifest header and manifest. /// </remarks> /// <param name="stream">Stream to read the package from.</param> /// <param name="keyProvider">Service that supplies possible cryptographic keys.</param> /// <returns>Package ready for reading.</returns> public static PackageReader FromStream(Stream stream, IKeyProvider keyProvider) { return new PackageReader(stream, keyProvider); } #endregion #region Methods /// <summary> /// Exposes the payload items in the manifest as a tree, to facilitate treating it as a filesystem. /// </summary> public PayloadTree InspectPayloadAsFilesystem() { var tree = new PayloadTree(); foreach (var payloadItem in _manifest.PayloadItems) { tree.AddItem(payloadItem, payloadItem.Path); } return tree; } /// <summary> /// Performs key confirmation and derivation on each payload item. /// </summary> /// <param name="payloadKeysSymmetric">Potential symmetric keys for payload items.</param> /// <exception cref="AggregateException"> /// Consisting of ItemKeyMissingException, indicating items missing cryptographic keys. /// </exception> private void ConfirmItemPreKeys(IEnumerable<SymmetricKey> payloadKeysSymmetric = null) { List<SymmetricKey> keys = payloadKeysSymmetric != null ? payloadKeysSymmetric.ToList() : new List<SymmetricKey>(); var keylessItems = new List<PayloadItem>(); IEnumerable<PayloadItem> itemsToConfirm = _manifest.PayloadItems.AsQueryExpr() .Where(item => item.SymmetricCipherKey.IsNullOrZeroLength() || item.AuthenticationKey.IsNullOrZeroLength()) .Run(); Parallel.ForEach(itemsToConfirm, item => { if (item.KeyConfirmation != null && item.KeyDerivation != null) { // We will derive the key from one supplied as a potential SymmetricKey symmetricKey; try { symmetricKey = ConfirmationUtility.ConfirmKeyFromCanary( ((SymmetricManifestCryptographyConfiguration) _manifestCryptoConfig).KeyConfirmation, _manifestCryptoConfig.KeyConfirmationVerifiedOutput, keys); } catch (Exception e) { throw new KeyConfirmationException("Key confirmation failed in an unexpected way.", e); } if (symmetricKey != null) { if (symmetricKey.Key.IsNullOrZeroLength()) { throw new ArgumentException("Supplied symmetric key is null or zero-length.", "payloadKeysSymmetric"); } _itemPreKeys.Add(item.Identifier, symmetricKey.Key); } else { keylessItems.Add(item); } } else { keylessItems.Add(item); } }); if (keylessItems.Count > 0) { throw new AggregateException(keylessItems.Select(item => new ItemKeyMissingException(item))); } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { if (_closeOnDispose && _readingStream != null) { _readingStream.Close(); } } } #endregion /// <summary> /// Reads a package manifest header from a stream. /// </summary> /// <param name="sourceStream">Stream to read the header from.</param> /// <param name="cryptoScheme">Manifest cryptography scheme parsed from the header.</param> /// <param name="cryptoConfig">Manifest cryptography configuration deserialised from the header.</param> /// <returns>Package manifest header.</returns> /// <exception cref="DataLengthException">End of stream encountered unexpectedly (contents truncated).</exception> /// <exception cref="InvalidDataException">Package data structure is out of specification or otherwise malformed.</exception> /// <exception cref="NotSupportedException">Version format specified is unknown to the local version.</exception> private static ManifestHeader ReadManifestHeader(Stream sourceStream, out ManifestCryptographyScheme cryptoScheme, out IManifestCryptographySchemeConfiguration cryptoConfig) { Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifestHeader", "[* PACKAGE START* ] Header offset (absolute)", sourceStream.Position)); byte[] referenceHeaderTag = Athena.Packaging.GetPackageHeaderTag(); var readHeaderTag = new byte[referenceHeaderTag.Length]; int headerTagBytesRead = sourceStream.Read(readHeaderTag, 0, readHeaderTag.Length); if (readHeaderTag.SequenceEqualShortCircuiting(referenceHeaderTag) == false) { if (headerTagBytesRead != referenceHeaderTag.Length) { throw new DataLengthException("Insufficient data to read package header tag."); } throw new InvalidDataException( "Package is malformed. Expected header tag is either absent or malformed."); } Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifestHeader", "Manifest header offset (absolute)", sourceStream.Position)); var manifestHeader = StratCom.DeserialiseDataTransferObject<ManifestHeader>(sourceStream, true); if (manifestHeader.FormatVersion <= 0) { throw new InvalidDataException("Package format descriptor is 0 or less (must be 1 or more)."); } if (manifestHeader.FormatVersion > Athena.Packaging.PackageFormatVersion) { throw new NotSupportedException( String.Format("Package version {0} as specified by the manifest header is unsupported/unknown.\n" + "The local version of ObscurCore supports up to version {1}.", manifestHeader.FormatVersion, Athena.Packaging.PackageFormatVersion)); // In later versions, can redirect to diff. behaviour (and DTO objects) for diff. versions. } cryptoScheme = manifestHeader.CryptographyScheme; switch (cryptoScheme) { case ManifestCryptographyScheme.SymmetricOnly: cryptoConfig = manifestHeader.CryptographySchemeConfiguration .DeserialiseDto<SymmetricManifestCryptographyConfiguration>(); break; case ManifestCryptographyScheme.Um1Hybrid: cryptoConfig = manifestHeader.CryptographySchemeConfiguration .DeserialiseDto<Um1HybridManifestCryptographyConfiguration>(); break; default: throw new NotSupportedException(String.Format( "Package manifest cryptography scheme \"{0}\" as specified by the manifest header is unsupported.", manifestHeader.CryptographyScheme)); } return manifestHeader; } /// <summary> /// Reads the manifest from the package. /// </summary> /// <remarks> /// Call method, supplying (all of) only the keys associated with the sender and the context. /// This maximises the chance that: <br /> /// <list type="number"> /// <item> /// <description> /// The package will be successfully decrypted if multiple /// keys are in use by both parties. /// </description> /// </item> /// <item> /// <description> /// Minimises the time spent validating potential key pairs. /// </description> /// </item> /// </list> /// </remarks> /// <param name="keyProvider">Provider to get possible keys for the manifest from.</param> /// <param name="manifestScheme">Cryptography scheme used in the manifest.</param> /// <returns>Package manifest object.</returns> /// <exception cref="ArgumentException">Key provider absent or could not supply any keys.</exception> /// <exception cref="NotSupportedException">Manifest cryptography scheme unsupported/unknown or missing.</exception> /// <exception cref="CryptoException"> /// A cryptographic operation failed (additional data maybe available in <see cref="CryptoException.InnerException" /> /// ). /// </exception> /// <exception cref="KeyConfirmationException"> /// Key confirmation failed to determine a key, or failed unexpectedly /// (additional data maybe available in <see cref="KeyConfirmationException.InnerException" />) /// </exception> /// <exception cref="InvalidDataException"> /// Deserialisation of manifest failed unexpectedly (manifest malformed, or incorrect key). /// </exception> /// <exception cref="CiphertextAuthenticationException">Manifest not authenticated.</exception> private Manifest ReadManifest(IKeyProvider keyProvider, ManifestCryptographyScheme manifestScheme) { // Determine the pre-key for the package manifest decryption (different schemes use different approaches) byte[] preMKey = null; switch (manifestScheme) { case ManifestCryptographyScheme.SymmetricOnly: { if (keyProvider.SymmetricKeys.Any() == false) { throw new ArgumentException("No symmetric keys available for decryption of this manifest.", "keyProvider"); } SymmetricKey symmetricKey = null; if (_manifestCryptoConfig.KeyConfirmation != null) { try { symmetricKey = ConfirmationUtility.ConfirmKeyFromCanary( ((SymmetricManifestCryptographyConfiguration) _manifestCryptoConfig).KeyConfirmation, _manifestCryptoConfig.KeyConfirmationVerifiedOutput, keyProvider.SymmetricKeys); } catch (Exception e) { throw new KeyConfirmationException("Key confirmation failed in an unexpected way.", e); } } else { if (keyProvider.SymmetricKeys.Count() > 1) { // Possibly allow to proceed anyway and just look for a serialisation failure? (not implemented) throw new ArgumentException( "Multiple symmetric keys are available, but confirmation is unavailable.", "keyProvider", new ConfigurationInvalidException("Package manifest includes no key confirmation data.")); } preMKey = keyProvider.SymmetricKeys.First().Key; } if (symmetricKey != null) { preMKey = symmetricKey.Key; } break; } case ManifestCryptographyScheme.Um1Hybrid: { ECKey um1SenderKey; ECKeypair um1RecipientKeypair; ECKey um1EphemeralKey = ((Um1HybridManifestCryptographyConfiguration) _manifestCryptoConfig).EphemeralKey; if (_manifestCryptoConfig.KeyConfirmation != null) { try { ConfirmationUtility.ConfirmKeyFromCanary(_manifestCryptoConfig.KeyConfirmation, _manifestCryptoConfig.KeyConfirmationVerifiedOutput, keyProvider.ForeignEcKeys, um1EphemeralKey, keyProvider.EcKeypairs, out um1SenderKey, out um1RecipientKeypair); } catch (Exception e) { throw new KeyConfirmationException("Key confirmation failed in an unexpected way.", e); } } else { // No key confirmation capability available if (keyProvider.ForeignEcKeys.Count() > 1 || keyProvider.EcKeypairs.Count() > 1) { throw new KeyConfirmationException( "Multiple EC keys have been provided where the package provides no key confirmation capability."); } um1SenderKey = keyProvider.ForeignEcKeys.First(); um1RecipientKeypair = keyProvider.EcKeypairs.First(); } // Perform the UM1 key agreement try { preMKey = Um1Exchange.Respond(um1SenderKey, um1RecipientKeypair.GetPrivateKey(), um1EphemeralKey); } catch (Exception e) { throw new CryptoException("Unexpected error in UM1 key agreement.", e); } break; } default: throw new NotSupportedException( String.Format("Manifest cryptography scheme \"{0}\" is unsupported/unknown.", manifestScheme)); } if (preMKey.IsNullOrZeroLength()) { throw new KeyConfirmationException(String.Format( "None of the keys provided to decrypt the manifest (cryptographic scheme: {0}) were confirmed as being able to do so.", manifestScheme)); } Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifest", "Manifest pre-key", preMKey.ToHexString())); // Derive working manifest encryption & authentication keys from the manifest pre-key byte[] workingManifestCipherKey, workingManifestMacKey; try { int cipherKeySizeBytes = _manifestCryptoConfig.SymmetricCipher.KeySizeBits.BitsToBytes(); if (_manifestCryptoConfig.Authentication.KeySizeBits.HasValue == false) { throw new ConfigurationInvalidException("Manifest authentication key size is missing."); } int macKeySizeBytes = _manifestCryptoConfig.Authentication.KeySizeBits.Value.BitsToBytes(); // Derive working cipher and MAC keys from the pre-key KeyStretchingUtility.DeriveWorkingKeys( preMKey, cipherKeySizeBytes, macKeySizeBytes, _manifestCryptoConfig.KeyDerivation, out workingManifestCipherKey, out workingManifestMacKey); } catch (Exception e) { throw new CryptoException("Unexpected error in manifest key derivation.", e); // TODO: make a specialised exception to communicate the failure type } // Clear the manifest pre-key preMKey.SecureWipe(); Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifest", "Manifest MAC working key", workingManifestMacKey.ToHexString())); Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifest", "Manifest cipher working key", workingManifestCipherKey.ToHexString())); Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifest", "Manifest length prefix offset (absolute)", _readingStream.Position)); // Read manifest length prefix var manifestLengthLe = new byte[sizeof(UInt32)]; // in little-endian form int manifestLengthBytesRead = _readingStream.Read(manifestLengthLe, 0, sizeof(UInt32)); if (manifestLengthBytesRead != sizeof(UInt32)) { throw new DataLengthException("Manifest length prefix could not be read. Insufficient data."); } manifestLengthLe.XorInPlaceInternal(0, workingManifestMacKey, 0, sizeof(UInt32)); // deobfuscate length UInt32 mlUInt = manifestLengthLe.LittleEndianToUInt32(); var manifestLength = (int) mlUInt; Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifest", "Manifest length", manifestLength)); Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadManifest", "Manifest offset (absolute)", _readingStream.Position)); /* Read manifest */ Manifest manifest; using (var decryptedManifestStream = new MemoryStream(manifestLength)) { byte[] manifestMac; try { using ( var authenticator = new MacStream(_readingStream, false, _manifestCryptoConfig.Authentication, out manifestMac, workingManifestMacKey, false)) { using (var cs = new CipherStream(authenticator, false, _manifestCryptoConfig.SymmetricCipher, workingManifestCipherKey, false)) { cs.ReadExactly(decryptedManifestStream, manifestLength, true); } // Authenticate manifest length tag authenticator.Update(manifestLengthLe, 0, manifestLengthLe.Length); Contract.Assert(authenticator.BytesIn == manifestLength); byte[] manifestCryptoDtoForAuth; switch (manifestScheme) { case ManifestCryptographyScheme.SymmetricOnly: manifestCryptoDtoForAuth = ((SymmetricManifestCryptographyConfiguration) _manifestCryptoConfig) .CreateAuthenticatibleClone().SerialiseDto(); break; case ManifestCryptographyScheme.Um1Hybrid: manifestCryptoDtoForAuth = ((Um1HybridManifestCryptographyConfiguration) _manifestCryptoConfig) .CreateAuthenticatibleClone().SerialiseDto(); break; default: throw new NotSupportedException(); } // Authenticate manifest cryptography configuration (from manifest header) authenticator.Update(manifestCryptoDtoForAuth, 0, manifestCryptoDtoForAuth.Length); } } catch (Exception e) { throw new CryptoException("Unexpected error in manifest decrypt-then-MAC operation.", e); } // Verify that manifest authenticated successfully if (manifestMac.SequenceEqual_ConstantTime(_manifestCryptoConfig.AuthenticationVerifiedOutput) == false) { throw new CiphertextAuthenticationException("Manifest failed authentication."); } decryptedManifestStream.Seek(0, SeekOrigin.Begin); try { manifest = decryptedManifestStream.DeserialiseDto<Manifest>(false); } catch (Exception e) { throw new InvalidDataException("Manifest failed to deserialise.", e); } } _readingPayloadStreamOffset = _readingStream.Position; // Clear the manifest encryption & authentication keys workingManifestCipherKey.SecureWipe(); workingManifestMacKey.SecureWipe(); return manifest; } /// <summary> /// Unpacks/extracts the payload items into a directory. /// </summary> /// <param name="path">Path to write items to.</param> /// <param name="overwrite"></param> /// <param name="payloadKeys">Potential symmetric keys for payload items.</param> /// <exception cref="ConfigurationInvalidException">Package item path includes a relative-up specifier (security risk).</exception> /// <exception cref="NotSupportedException">Package includes a KeyAction payload item type (not implemented).</exception> /// <exception cref="IOException">File already exists and overwrite is not allowed.</exception> public void ReadToDirectory(string path, bool overwrite, IEnumerable<SymmetricKey> payloadKeys = null) { if (path == null) { throw new ArgumentNullException("path"); } try { Directory.CreateDirectory(path); } catch (IOException) { throw new ArgumentException( "Could not create package output directory: Supplied path is a file, not a directory.", "path"); } catch (ArgumentException) { throw new ArgumentException( "Could not create package output directory: Path contains invalid characters.", "path"); } catch (NotSupportedException e) { throw new ArgumentException( "Could not create package output directory: Path contains invalid character.", "path", e); } foreach (PayloadItem item in _manifest.PayloadItems) { if (item.Path == String.Empty) { throw new ConfigurationInvalidException("A payload item has no path/name."); } else if (item.Type != PayloadItemType.KeyAction && item.Path.Contains(Athena.Packaging.PathRelativeUp)) { throw new ConfigurationInvalidException("A payload item specifies a relative path outside that of the package root. " + "This is a potentially dangerous condition."); } // First we correct the directory symbol to match local OS string relativePath = item.Path.Replace(Athena.Packaging.PathDirectorySeperator, Path.DirectorySeparatorChar); string absolutePath = Path.Combine(path, relativePath); switch (item.Type) { case PayloadItemType.Message: if (Path.HasExtension(absolutePath) == false) { absolutePath += ".txt"; } break; case PayloadItemType.KeyAction: throw new NotSupportedException("Key actions not implemented."); } if (File.Exists(absolutePath) && overwrite == false) { throw new IOException("File already exists: " + absolutePath); } PayloadItem itemClosureVar = item; item.SetStreamBinding(() => { try { string directory = Path.GetDirectoryName(absolutePath); Directory.CreateDirectory(directory); const int fileBufferSize = 81920; // 80 KB (Microsoft default) var stream = new FileStream(absolutePath, FileMode.Create, FileAccess.Write, FileShare.None, fileBufferSize, true); stream.SetLength(itemClosureVar.ExternalLength); return stream; } catch (ArgumentException e) { throw new ConfigurationInvalidException( "Could not create payload item output stream: path contains invalid characters.", e); } catch (NotSupportedException e) { throw new ConfigurationInvalidException( "Could not create payload item output stream: path is invalid.", e); } }); } ReadPayload(payloadKeys); } /// <summary> /// Read the payload. /// </summary> /// <remarks> /// All payload items to be read must have have valid stream bindings /// (<see cref="PayloadItem.StreamBinding" />) prior to calling this. /// </remarks> /// <param name="payloadKeys">Potential keys for payload items (optional).</param> /// <exception cref="KeyConfirmationException">Key confirmation for payload items failed.</exception> /// <exception cref="ConfigurationInvalidException">Payload layout scheme malformed/missing.</exception> /// <exception cref="InvalidDataException">Package data structure malformed.</exception> /// <exception cref="EndOfStreamException">Package is truncated or otherwise shorter than expected.</exception> private void ReadPayload(IEnumerable<SymmetricKey> payloadKeys = null) { if (_readingPayloadStreamOffset != 0 && _readingStream.Position != _readingPayloadStreamOffset) { _readingStream.Seek(_readingPayloadStreamOffset, SeekOrigin.Begin); } Debug.Print(DebugUtility.CreateReportString("PackageReader", "Read", "Payload offset (absolute)", _readingStream.Position)); // Check that all payload items have decryption keys - if they do not, confirm them from potentials try { ConfirmItemPreKeys(payloadKeys); } catch (Exception e) { throw new KeyConfirmationException("Error in key confirmation of payload items.", e); } // Read the payload PayloadMux mux; try { var payloadScheme = _manifest.PayloadConfiguration.SchemeName.ToEnum<PayloadLayoutScheme>(); mux = PayloadMuxFactory.CreatePayloadMultiplexer(payloadScheme, false, _readingStream, _manifest.PayloadItems, _itemPreKeys, _manifest.PayloadConfiguration); } catch (EnumerationParsingException e) { throw new ConfigurationInvalidException( "Payload layout scheme specified is unsupported/unknown or missing.", e); } catch (Exception e) { throw new Exception("Error in creation of payload demultiplexer.", e); } // Demux the payload try { mux.Execute(); } catch (Exception e) { // Catch different kinds of exception in future throw new Exception("Error in demultiplexing payload.", e); } // Read the trailer byte[] referenceTrailerTag = Athena.Packaging.GetPackageTrailerTag(); var trailerTag = new byte[referenceTrailerTag.Length]; Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadPayload", "Trailer offset (absolute)", _readingStream.Position)); int trailerBytesRead = _readingStream.Read(trailerTag, 0, trailerTag.Length); if (trailerTag.SequenceEqualShortCircuiting(referenceTrailerTag) == false) { const string pragmatist = "It would appear, however, that the package has unpacked successfully despite this."; if (trailerBytesRead != referenceTrailerTag.Length) { throw new EndOfStreamException("Insufficient data to read package trailer tag. " + pragmatist); } throw new InvalidDataException("Package is malformed. Trailer tag is either absent or malformed." + pragmatist); } Debug.Print(DebugUtility.CreateReportString("PackageReader", "ReadPayload", "[* PACKAGE END *] Offset (absolute)", _readingStream.Position)); } } }
#if DEBUG && !PROFILE_SVELTO #define ENABLE_DEBUG_FUNC #endif using System; using System.Runtime.CompilerServices; using Svelto.Common; using Svelto.DataStructures; using Svelto.DataStructures.Native; using Svelto.ECS.Internal; namespace Svelto.ECS { public partial class EntitiesDB { internal EntitiesDB(EnginesRoot enginesRoot, EnginesRoot.LocatorMap entityReferencesMap) { _enginesRoot = enginesRoot; _entityReferencesMap = entityReferencesMap; } EntityCollection<T> InternalQueryEntities<T> (FasterDictionary<RefWrapperType, ITypeSafeDictionary> entitiesInGroupPerType) where T : struct, IEntityComponent { uint count = 0; IBuffer<T> buffer; if (SafeQueryEntityDictionary<T>(out var typeSafeDictionary, entitiesInGroupPerType) == false) buffer = RetrieveEmptyEntityComponentArray<T>(); else { var safeDictionary = (typeSafeDictionary as ITypeSafeDictionary<T>); buffer = safeDictionary.GetValues(out count); } return new EntityCollection<T>(buffer, count); } /// <summary> /// The QueryEntities<T> follows the rule that entities could always be iterated regardless if they /// are 0, 1 or N. In case of 0 it returns an empty array. This allows to use the same for iteration /// regardless the number of entities built. /// </summary> /// <param name="groupStructId"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public EntityCollection<T> QueryEntities<T>(ExclusiveGroupStruct groupStructId) where T : struct, IEntityComponent { if (groupEntityComponentsDB.TryGetValue(groupStructId, out var entitiesInGroupPerType) == false) { var buffer = RetrieveEmptyEntityComponentArray<T>(); return new EntityCollection<T>(buffer, 0); } return InternalQueryEntities<T>(entitiesInGroupPerType); } public EntityCollection<T1, T2> QueryEntities<T1, T2>(ExclusiveGroupStruct groupStruct) where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent { if (groupEntityComponentsDB.TryGetValue(groupStruct, out var entitiesInGroupPerType) == false) { return new EntityCollection<T1, T2>(new EntityCollection<T1>(RetrieveEmptyEntityComponentArray<T1>(), 0) , new EntityCollection<T2>( RetrieveEmptyEntityComponentArray<T2>(), 0)); } var T1entities = InternalQueryEntities<T1>(entitiesInGroupPerType); var T2entities = InternalQueryEntities<T2>(entitiesInGroupPerType); #if DEBUG && !PROFILE_SVELTO if (T1entities.count != T2entities.count) throw new ECSException("Entity components count do not match in group. Entity 1: ' count: " .FastConcat(T1entities.count).FastConcat(" ", typeof(T1).ToString()) .FastConcat("'. Entity 2: ' count: ".FastConcat(T2entities.count) .FastConcat(" ", typeof(T2).ToString()) .FastConcat( "' group: ", groupStruct.ToName()))); #endif return new EntityCollection<T1, T2>(T1entities, T2entities); } public EntityCollection<T1, T2, T3> QueryEntities<T1, T2, T3>(ExclusiveGroupStruct groupStruct) where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent where T3 : struct, IEntityComponent { if (groupEntityComponentsDB.TryGetValue(groupStruct, out var entitiesInGroupPerType) == false) { return new EntityCollection<T1, T2, T3>( new EntityCollection<T1>(RetrieveEmptyEntityComponentArray<T1>(), 0) , new EntityCollection<T2>(RetrieveEmptyEntityComponentArray<T2>(), 0) , new EntityCollection<T3>(RetrieveEmptyEntityComponentArray<T3>(), 0)); } var T1entities = InternalQueryEntities<T1>(entitiesInGroupPerType); var T2entities = InternalQueryEntities<T2>(entitiesInGroupPerType); var T3entities = InternalQueryEntities<T3>(entitiesInGroupPerType); #if DEBUG && !PROFILE_SVELTO if (T1entities.count != T2entities.count || T2entities.count != T3entities.count) throw new ECSException("Entity components count do not match in group. Entity 1: " .FastConcat(typeof(T1).ToString()).FastConcat(" count: ") .FastConcat(T1entities.count).FastConcat( " Entity 2: ".FastConcat(typeof(T2).ToString()).FastConcat(" count: ") .FastConcat(T2entities.count) .FastConcat(" Entity 3: ".FastConcat(typeof(T3).ToString())) .FastConcat(" count: ").FastConcat(T3entities.count))); #endif return new EntityCollection<T1, T2, T3>(T1entities, T2entities, T3entities); } public EntityCollection<T1, T2, T3, T4> QueryEntities<T1, T2, T3, T4>(ExclusiveGroupStruct groupStruct) where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent where T3 : struct, IEntityComponent where T4 : struct, IEntityComponent { if (groupEntityComponentsDB.TryGetValue(groupStruct, out var entitiesInGroupPerType) == false) { return new EntityCollection<T1, T2, T3, T4>( new EntityCollection<T1>(RetrieveEmptyEntityComponentArray<T1>(), 0) , new EntityCollection<T2>(RetrieveEmptyEntityComponentArray<T2>(), 0) , new EntityCollection<T3>(RetrieveEmptyEntityComponentArray<T3>(), 0) , new EntityCollection<T4>(RetrieveEmptyEntityComponentArray<T4>(), 0)); } var T1entities = InternalQueryEntities<T1>(entitiesInGroupPerType); var T2entities = InternalQueryEntities<T2>(entitiesInGroupPerType); var T3entities = InternalQueryEntities<T3>(entitiesInGroupPerType); var T4entities = InternalQueryEntities<T4>(entitiesInGroupPerType); #if DEBUG && !PROFILE_SVELTO if (T1entities.count != T2entities.count || T2entities.count != T3entities.count || T3entities.count != T4entities.count) throw new ECSException("Entity components count do not match in group. Entity 1: " .FastConcat(typeof(T1).ToString()).FastConcat(" count: ") .FastConcat(T1entities.count).FastConcat( " Entity 2: ".FastConcat(typeof(T2).ToString()).FastConcat(" count: ") .FastConcat(T2entities.count) .FastConcat(" Entity 3: ".FastConcat(typeof(T3).ToString())) .FastConcat(" count: ").FastConcat(T3entities.count) .FastConcat(" Entity 4: ".FastConcat(typeof(T4).ToString())) .FastConcat(" count: ").FastConcat(T4entities.count))); #endif return new EntityCollection<T1, T2, T3, T4>(T1entities, T2entities, T3entities, T4entities); } public GroupsEnumerable<T> QueryEntities<T> (in LocalFasterReadOnlyList<ExclusiveGroupStruct> groups) where T : struct, IEntityComponent { return new GroupsEnumerable<T>(this, groups); } /// <summary> /// Note: Remember that EntityViewComponents are always put at the end of the generic parameters tuple. /// It won't compile otherwise /// </summary> /// <returns></returns> public GroupsEnumerable<T1, T2> QueryEntities<T1, T2>(in LocalFasterReadOnlyList<ExclusiveGroupStruct> groups) where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent { return new GroupsEnumerable<T1, T2>(this, groups); } public GroupsEnumerable<T1, T2, T3> QueryEntities<T1, T2, T3> (in LocalFasterReadOnlyList<ExclusiveGroupStruct> groups) where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent where T3 : struct, IEntityComponent { return new GroupsEnumerable<T1, T2, T3>(this, groups); } public GroupsEnumerable<T1, T2, T3, T4> QueryEntities<T1, T2, T3, T4> (in LocalFasterReadOnlyList<ExclusiveGroupStruct> groups) where T1 : struct, IEntityComponent where T2 : struct, IEntityComponent where T3 : struct, IEntityComponent where T4 : struct, IEntityComponent { return new GroupsEnumerable<T1, T2, T3, T4>(this, groups); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public EGIDMapper<T> QueryMappedEntities<T>(ExclusiveGroupStruct groupStructId) where T : struct, IEntityComponent { if (SafeQueryEntityDictionary<T>(groupStructId, out var typeSafeDictionary) == false) throw new EntityGroupNotFoundException(typeof(T), groupStructId.ToName()); return (typeSafeDictionary as ITypeSafeDictionary<T>).ToEGIDMapper(groupStructId); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryQueryMappedEntities<T> (ExclusiveGroupStruct groupStructId, out EGIDMapper<T> mapper) where T : struct, IEntityComponent { mapper = default; if (SafeQueryEntityDictionary<T>(groupStructId, out var typeSafeDictionary) == false || typeSafeDictionary.count == 0) return false; mapper = (typeSafeDictionary as ITypeSafeDictionary<T>).ToEGIDMapper(groupStructId); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Exists<T>(EGID entityGID) where T : struct, IEntityComponent { if (SafeQueryEntityDictionary<T>(entityGID.groupID, out var casted) == false) return false; return casted != null && casted.ContainsKey(entityGID.entityID); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Exists<T>(uint id, ExclusiveGroupStruct group) where T : struct, IEntityComponent { if (SafeQueryEntityDictionary<T>(group, out var casted) == false) return false; return casted != null && casted.ContainsKey(id); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ExistsAndIsNotEmpty(ExclusiveGroupStruct gid) { if (groupEntityComponentsDB.TryGetValue( gid, out FasterDictionary<RefWrapperType, ITypeSafeDictionary> group) == true) { return group.count > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool HasAny<T>(ExclusiveGroupStruct groupStruct) where T : struct, IEntityComponent { return Count<T>(groupStruct) > 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Count<T>(ExclusiveGroupStruct groupStruct) where T : struct, IEntityComponent { if (SafeQueryEntityDictionary<T>(groupStruct, out var typeSafeDictionary) == false) return 0; return (int) typeSafeDictionary.count; } public bool FoundInGroups<T1>() where T1 : IEntityComponent { return groupsPerEntity.ContainsKey(TypeRefWrapper<T1>.wrapper); } public bool IsDisposing => _enginesRoot._isDisposing; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool SafeQueryEntityDictionary<T> (out ITypeSafeDictionary typeSafeDictionary , FasterDictionary<RefWrapperType, ITypeSafeDictionary> entitiesInGroupPerType) where T : IEntityComponent { if (entitiesInGroupPerType.TryGetValue(new RefWrapperType(TypeCache<T>.type), out var safeDictionary) == false) { typeSafeDictionary = default; return false; } //return the indexes entities if they exist typeSafeDictionary = safeDictionary; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool SafeQueryEntityDictionary<T> (ExclusiveGroupStruct group, out ITypeSafeDictionary typeSafeDictionary) where T : IEntityComponent { if (UnsafeQueryEntityDictionary(group, TypeCache<T>.type, out var safeDictionary) == false) { typeSafeDictionary = default; return false; } //return the indexes entities if they exist typeSafeDictionary = safeDictionary; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool UnsafeQueryEntityDictionary (ExclusiveGroupStruct group, Type type, out ITypeSafeDictionary typeSafeDictionary) { //search for the group if (groupEntityComponentsDB.TryGetValue(group, out var entitiesInGroupPerType) == false) { typeSafeDictionary = null; return false; } //search for the indexed entities in the group return entitiesInGroupPerType.TryGetValue(new RefWrapperType(type), out typeSafeDictionary); } [MethodImpl(MethodImplOptions.AggressiveInlining)] static IBuffer<T> RetrieveEmptyEntityComponentArray<T>() where T : struct, IEntityComponent { return EmptyList<T>.emptyArray; } static class EmptyList<T> where T : struct, IEntityComponent { internal static readonly IBuffer<T> emptyArray; static EmptyList() { if (ComponentBuilder<T>.IS_ENTITY_VIEW_COMPONENT) { MB<T> b = default; emptyArray = b; } else { NB<T> b = default; emptyArray = b; } } } static readonly FasterDictionary<ExclusiveGroupStruct, ITypeSafeDictionary> _emptyDictionary = new FasterDictionary<ExclusiveGroupStruct, ITypeSafeDictionary>(); readonly EnginesRoot _enginesRoot; EntitiesStreams _entityStream => _enginesRoot._entityStreams; //grouped set of entity components, this is the standard way to handle entity components are grouped per //group, then indexable per type, then indexable per EGID. however the TypeSafeDictionary can return an array of //values directly, that can be iterated over, so that is possible to iterate over all the entity components of //a specific type inside a specific group. FasterDictionary<ExclusiveGroupStruct, FasterDictionary<RefWrapperType, ITypeSafeDictionary>> groupEntityComponentsDB => _enginesRoot._groupEntityComponentsDB; //for each entity view type, return the groups (dictionary of entities indexed by entity id) where they are //found indexed by group id. TypeSafeDictionary are never created, they instead point to the ones hold //by _groupEntityComponentsDB // <EntityComponentType <groupID <entityID, EntityComponent>>> FasterDictionary<RefWrapperType, FasterDictionary<ExclusiveGroupStruct, ITypeSafeDictionary>> groupsPerEntity => _enginesRoot._groupsPerEntity; EnginesRoot.LocatorMap _entityReferencesMap; } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using Encog.App.Analyst.Util; using Encog.Util.CSV; namespace Encog.App.Analyst.Script.Prop { /// <summary> /// A property entry for the Encog Analyst. Properties have a name and section. /// </summary> public class PropertyEntry : IComparable<PropertyEntry> { /// <summary> /// The type of property. /// </summary> private readonly PropertyType _entryType; /// <summary> /// The name of the property. /// </summary> private readonly String _name; /// <summary> /// The section of the property. /// </summary> private readonly String _section; /// <summary> /// Construct a property entry. /// </summary> /// <param name="theEntryType">The entry type.</param> /// <param name="theName">The name of the property.</param> /// <param name="theSection">The section of the property.</param> public PropertyEntry(PropertyType theEntryType, String theName, String theSection) { _entryType = theEntryType; _name = theName; _section = theSection; } /// <value>the entryType</value> public PropertyType EntryType { get { return _entryType; } } /// <value>The key.</value> public String Key { get { return _section + "_" + _name; } } /// <value>the name</value> public String Name { get { return _name; } } /// <value>the section</value> public String Section { get { return _section; } } #region IComparable<PropertyEntry> Members /// <summary> /// </summary> public int CompareTo(PropertyEntry o) { return String.CompareOrdinal(_name, o._name); } #endregion /// <summary> /// Put a property in dot form, which is "section.subsection.name". /// </summary> /// <param name="section">The section.</param> /// <param name="subSection">The subsection.</param> /// <param name="name">The name.</param> /// <returns>The property in dot form.</returns> public static String DotForm(String section, String subSection, String name) { var result = new StringBuilder(); result.Append(section); result.Append('.'); result.Append(subSection); result.Append('.'); result.Append(name); return result.ToString(); } /// <summary> /// </summary> public override sealed String ToString() { var result = new StringBuilder("["); result.Append(GetType().Name); result.Append(" name="); result.Append(_name); result.Append(", section="); result.Append(_section); result.Append("]"); return result.ToString(); } /// <summary> /// Validate the specified property. /// </summary> /// <param name="theSection">The section.</param> /// <param name="subSection">The sub section.</param> /// <param name="theName">The name of the property.</param> /// <param name="v">The value of the property.</param> public void Validate(String theSection, String subSection, String theName, String v) { if (string.IsNullOrEmpty(v)) { return; } try { switch (EntryType) { case PropertyType.TypeBoolean: if ((Char.ToUpper(v[0]) != 'T') && (Char.ToUpper(v[0]) != 'F')) { var result = new StringBuilder(); result.Append("Illegal boolean for "); result.Append(DotForm(_section, subSection, _name)); result.Append(", value is "); result.Append(v); result.Append("."); throw new AnalystError(result.ToString()); } break; case PropertyType.TypeDouble: CSVFormat.EgFormat.Parse(v); break; case PropertyType.TypeFormat: if (ConvertStringConst.String2AnalystFileFormat(v) == AnalystFileFormat.Unknown) { var result = new StringBuilder(); result.Append("Invalid file format for "); result.Append(DotForm(_section, subSection, _name)); result.Append(", value is "); result.Append(v); result.Append("."); throw new AnalystError(result.ToString()); } break; case PropertyType.TypeInteger: Int32.Parse(v); break; case PropertyType.TypeListString: break; case PropertyType.TypeString: break; default: throw new AnalystError("Unsupported property type."); } } catch (FormatException) { var result = new StringBuilder(); result.Append("Illegal value for "); result.Append(DotForm(_section, subSection, _name)); result.Append(", expecting a "); result.Append(EntryType.ToString()); result.Append(", but got "); result.Append(v); result.Append("."); throw new AnalystError(result.ToString()); } } } }
namespace SPALM.SPSF.Library.CustomWizardPages { using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Windows.Forms; using EnvDTE; using Microsoft.Practices.WizardFramework; using SPALM.SPSF.SharePointBridge; /// <summary> /// Example of a class that is a custom wizard page /// </summary> public partial class SiteColumnImportPage : CustomWizardPage { public SiteColumnImportPage(WizardForm parent) : base(parent) { // This call is required by the Windows Form Designer. InitializeComponent(); } public override bool IsDataValid { get { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; if (dictionaryService.GetValue("SiteColumnSchema") == null) { return false; } } catch (Exception) { } return base.IsDataValid; } } private void button1_Click(object sender, EventArgs e) { treeView_nodes.Nodes.Clear(); if (comboBox1.Text != "") { foreach (SharePointField item in LoadSiteColumns(comboBox1.Text)) { string key = item.Group; if ((key == null) || (key == "")) { key = "[nogroup]"; } TreeNode groupnode = null; if (!treeView_nodes.Nodes.ContainsKey(key)) { //create new group groupnode = new TreeNode(); groupnode.Text = key; groupnode.Name = key; treeView_nodes.Nodes.Add(groupnode); } else { groupnode = treeView_nodes.Nodes[key]; } TreeNode node = new TreeNode(item.Name); node.Tag = item; groupnode.Nodes.Add(node); } } } private List<SharePointField> LoadSiteColumns(string siteurl) { Cursor = Cursors.WaitCursor; DTE dte = GetService(typeof(DTE)) as DTE; SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte); List<SharePointField> siteColumns = helper.GetSiteColumns(siteurl); Cursor = Cursors.Default; return siteColumns; } private void GetAllSiteCollections() { Cursor = Cursors.WaitCursor; this.comboBox1.Items.Clear(); try { DTE dte = GetService(typeof(DTE)) as DTE; SharePointBrigdeHelper helper = new SharePointBrigdeHelper(dte); foreach (SharePointSiteCollection sitecoll in helper.GetAllSiteCollections()) { comboBox1.Items.Add(sitecoll.Url); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } Cursor = Cursors.Default; } private void comboBox1_DropDown(object sender, EventArgs e) { if (comboBox1.Items.Count == 0) { GetAllSiteCollections(); } } private void treeView_nodes_AfterSelect(object sender, TreeViewEventArgs e) { SetAsInvalid(); if (e.Node != null) { if (e.Node.Tag != null) { if (e.Node.Tag is SharePointField) { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; SharePointField vct = (SharePointField)e.Node.Tag; dictionaryService.SetValue("SiteColumnID", vct.Id.ToString()); dictionaryService.SetValue("SiteColumnName", vct.Name); dictionaryService.SetValue("SiteColumnDisplayName", vct.DisplayName); dictionaryService.SetValue("SiteColumnDescription", vct.Description); dictionaryService.SetValue("SiteColumnGroup", vct.Group); dictionaryService.SetValue("SiteColumnSchema", vct.SchemaXml); /* * * * XmlElement dummyNode = xmlDocument.CreateElement("dummy"); dummyNode.InnerXml = virtualField.OriginalField.SchemaXml; XmlElement fieldNode = (XmlElement) dummyNode.LastChild; fieldNode.SetAttribute("xmlns", "http://schemas.microsoft.com/sharepoint/"); if (virtualField.Name != string.Empty) { fieldNode.SetAttribute("Name", virtualField.Name); } else { if (virtualField.StaticName == string.Empty) { throw new ApplicationException("No Name or StaticName for VirtualField: " + virtualField.OriginalField.SchemaXml); } fieldNode.SetAttribute("Name", virtualField.StaticName); } if (virtualField.DisplayName != string.Empty) { fieldNode.SetAttribute("DisplayName", virtualField.DisplayName); } if (virtualField.StaticName != string.Empty) { fieldNode.SetAttribute("StaticName", virtualField.StaticName); } if (virtualField.Group != string.Empty) { fieldNode.SetAttribute("Group", virtualField.Group); } fieldNode.SetAttribute("ID", virtualField.Id.ToString("B")); if (virtualField.MaxLength.HasValue) { fieldNode.SetAttribute("MaxLength", virtualField.MaxLength.ToString()); } if (virtualField.SourceID != string.Empty) { fieldNode.SetAttribute("SourceID", virtualField.SourceID); } fieldNode.RemoveAttribute("WebId"); fieldNode.RemoveAttribute("Version"); fieldNode.RemoveAttribute("UserSelectionMode"); fieldNode.RemoveAttribute("UserSelectionScope"); return CleanFeatureXml(dummyNode.InnerXml); * * */ //vct.OriginalField.SchemaXml /* string fieldschema = "<FieldRefs>"; foreach (SPFieldLink fieldLink in vct.OriginalContentType.FieldLinks) { fieldschema = fieldschema + fieldLink.SchemaXml; } fieldschema += "</FieldRefs>"; dictionaryService.SetValue("ContentTypeID", vct.Id); dictionaryService.SetValue("ContentTypeName", vct.Name); dictionaryService.SetValue("ContentTypeDescription", vct.Description); dictionaryService.SetValue("ContentTypeGroup", vct.Group); dictionaryService.SetValue("ContentTypeFieldSchema", fieldschema); dictionaryService.SetValue("ContentTypeVersion", vct.Version); dictionaryService.SetValue("ContentTypeHidden", vct.Hidden); dictionaryService.SetValue("ContentTypeReadOnly", vct.ReadOnly); dictionaryService.SetValue("ContentTypeSealed", vct.Sealed); */ } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } } Wizard.OnValidationStateChanged(this); } private void SetAsInvalid() { try { IDictionaryService dictionaryService = GetService(typeof(IDictionaryService)) as IDictionaryService; dictionaryService.SetValue("SiteColumnSchema", null); } catch (Exception) { } } private void comboBox1_TextChanged(object sender, EventArgs e) { if (comboBox1.Text != "") { button1.Enabled = true; } else { button1.Enabled = false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Globalization; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumWithFlagsAttributeFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class EnumWithFlagsAttributeTests { private static string GetCSharpCode_EnumWithFlagsAttributes(string code, bool hasFlags) { string stringToReplace = hasFlags ? "[System.Flags]" : ""; return string.Format(CultureInfo.CurrentCulture, code, stringToReplace); } private static string GetBasicCode_EnumWithFlagsAttributes(string code, bool hasFlags) { string stringToReplace = hasFlags ? "<System.Flags>" : ""; return string.Format(CultureInfo.CurrentCulture, code, stringToReplace); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_SimpleCaseAsync() { var code = @"{0} public enum SimpleFlagsEnumClass {{ Zero = 0, One = 1, Two = 2, Four = 4 }} {0} public enum HexFlagsEnumClass {{ One = 0x1, Two = 0x2, Four = 0x4, All = 0x7 }}"; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027CSharpResultAt(2, 13, "SimpleFlagsEnumClass"), GetCA1027CSharpResultAt(11, 13, "HexFlagsEnumClass")); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CSharp_EnumWithFlagsAttributes_SimpleCase_InternalAsync() { var code = @"{0} internal enum SimpleFlagsEnumClass {{ Zero = 0, One = 1, Two = 2, Four = 4 }} internal class OuterClass {{ {0} public enum HexFlagsEnumClass {{ One = 0x1, Two = 0x2, Four = 0x4, All = 0x7 }} }}"; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_SimpleCaseWithScopeAsync() { var code = @"{0} public enum {{|CA1027:SimpleFlagsEnumClass|}} {{ Zero = 0, One = 1, Two = 2, Four = 4 }} {0} public enum HexFlagsEnumClass {{ One = 0x1, Two = 0x2, Four = 0x4, All = 0x7 }}"; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027CSharpResultAt(11, 13, "HexFlagsEnumClass")); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_SimpleCaseAsync() { var code = @"{0} Public Enum SimpleFlagsEnumClass Zero = 0 One = 1 Two = 2 Four = 4 End Enum {0} Public Enum HexFlagsEnumClass One = &H1 Two = &H2 Four = &H4 All = &H7 End Enum"; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027BasicResultAt(2, 13, "SimpleFlagsEnumClass"), GetCA1027BasicResultAt(10, 13, "HexFlagsEnumClass")); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VisualBasic_EnumWithFlagsAttributes_SimpleCase_InternalAsync() { var code = @"{0} Friend Enum SimpleFlagsEnumClass Zero = 0 One = 1 Two = 2 Four = 4 End Enum Friend Class OuterClass {0} Public Enum HexFlagsEnumClass One = &H1 Two = &H2 Four = &H4 All = &H7 End Enum End Class"; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_SimpleCaseWithScopeAsync() { var code = @"{0} Public Enum {{|CA1027:SimpleFlagsEnumClass|}} Zero = 0 One = 1 Two = 2 Four = 4 End Enum {0} Public Enum HexFlagsEnumClass One = &H1 Two = &H2 Four = &H4 All = &H7 End Enum"; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027BasicResultAt(10, 13, "HexFlagsEnumClass")); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_DuplicateValuesAsync() { string code = @"{0} public enum DuplicateValuesEnumClass {{ Zero = 0, One = 1, Two = 2, Four = 4, AnotherFour = 4, ThreePlusOne = Two + One + One }} "; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027CSharpResultAt(2, 13, "DuplicateValuesEnumClass")); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_DuplicateValuesAsync() { string code = @"{0} Public Enum DuplicateValuesEnumClass Zero = 0 One = 1 Two = 2 Four = 4 AnotherFour = 4 ThreePlusOne = Two + One + One End Enum "; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027BasicResultAt(2, 13, "DuplicateValuesEnumClass")); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_MissingPowerOfTwoAsync() { string code = @" {0} public enum MissingPowerOfTwoEnumClass {{ Zero = 0, One = 1, Two = 2, Four = 4, Sixteen = 16 }} {0} public enum MultipleMissingPowerOfTwoEnumClass {{ Zero = 0, One = 1, Two = 2, Four = 4, ThirtyTwo = 32 }}"; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027CSharpResultAt(3, 13, "MissingPowerOfTwoEnumClass"), GetCA1027CSharpResultAt(13, 13, "MultipleMissingPowerOfTwoEnumClass")); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_IncorrectNumbersAsync() { string code = @" {0} public enum AnotherTestValue {{ Value1 = 0, Value2 = 1, Value3 = 1, Value4 = 3 }}"; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags); // Verify CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags, GetCA2217CSharpResultAt(3, 13, "AnotherTestValue", "2")); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_MissingPowerOfTwoAsync() { string code = @" {0} Public Enum MissingPowerOfTwoEnumClass Zero = 0 One = 1 Two = 2 Four = 4 Sixteen = 16 End Enum {0} Public Enum MultipleMissingPowerOfTwoEnumClass Zero = 0 One = 1 Two = 2 Four = 4 ThirtyTwo = 32 End Enum "; // Verify CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags, GetCA1027BasicResultAt(3, 13, "MissingPowerOfTwoEnumClass"), GetCA1027BasicResultAt(12, 13, "MultipleMissingPowerOfTwoEnumClass")); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_IncorrectNumbersAsync() { string code = @" {0} Public Enum AnotherTestValue Value1 = 0 Value2 = 1 Value3 = 1 Value4 = 3 End Enum "; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags); // Verify CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags, GetCA2217BasicResultAt(3, 13, "AnotherTestValue", "2")); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_ContiguousValuesAsync() { var code = @" {0} public enum ContiguousEnumClass {{ Zero = 0, One = 1, Two = 2 }} {0} public enum ContiguousEnumClass2 {{ Zero = 0, One = 1, Two = 2, Three = 3, Four = 4, Five = 5 }} {0} public enum ValuesNotDeclaredEnumClass {{ Zero, One, Two, Three, Four, Five }} {0} public enum ShortUnderlyingType: short {{ Zero = 0, One, Two, Three, Four, Five }}"; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_ContiguousValuesAsync() { var code = @" {0} Public Enum ContiguousEnumClass Zero = 0 One = 1 Two = 2 End Enum {0} Public Enum ContiguousEnumClass2 Zero = 0 One = 1 Two = 2 Three = 3 Four = 4 Five = 5 End Enum {0} Public Enum ValuesNotDeclaredEnumClass Zero One Two Three Four Five End Enum {0} Public Enum ShortUnderlyingType As Short Zero = 0 One Two Three Four Five End Enum "; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags); // Verify no CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags); } [Fact] public async Task CSharp_EnumWithFlagsAttributes_NonSimpleFlagsAsync() { var code = @" {0} public enum NonSimpleFlagEnumClass {{ Zero = 0x0, // 0000 One = 0x1, // 0001 Two = 0x2, // 0010 Eight = 0x8, // 1000 Twelve = 0xC, // 1100 HighValue = -1 // will be cast to UInt32.MaxValue, then zero-extended to UInt64 }} {0} public enum BitValuesClass {{ None = 0x0, One = 0x1, // 0001 Two = 0x2, // 0010 Eight = 0x8, // 1000 Twelve = 0xC, // 1100 }} {0} public enum LabelsClass {{ None = 0, One = 1, Four = 4, Six = 6, Seven = 7 }}"; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyCS.VerifyAnalyzerAsync(codeWithoutFlags); // Verify CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetCSharpCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyCS.VerifyAnalyzerAsync(codeWithFlags, GetCA2217CSharpResultAt(3, 13, "NonSimpleFlagEnumClass", "4, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296, 8589934592, 17179869184, 34359738368, 68719476736, 137438953472, 274877906944, 549755813888, 1099511627776, 2199023255552, 4398046511104, 8796093022208, 17592186044416, 35184372088832, 70368744177664, 140737488355328, 281474976710656, 562949953421312, 1125899906842624, 2251799813685248, 4503599627370496, 9007199254740992, 18014398509481984, 36028797018963968, 72057594037927936, 144115188075855872, 288230376151711744, 576460752303423488, 1152921504606846976, 2305843009213693952, 4611686018427387904, 9223372036854775808"), GetCA2217CSharpResultAt(14, 13, "BitValuesClass", "4"), GetCA2217CSharpResultAt(24, 13, "LabelsClass", "2")); } [Fact] public async Task VisualBasic_EnumWithFlagsAttributes_NonSimpleFlagsAsync() { var code = @" {0} Public Enum NonSimpleFlagEnumClass Zero = &H0 ' 0000 One = &H1 ' 0001 Two = &H2 ' 0010 Eight = &H8 ' 1000 Twelve = &Hc ' 1100 HighValue = -1 ' will be cast to UInt32.MaxValue, then zero-extended to UInt64 End Enum {0} Public Enum BitValuesClass None = &H0 One = &H1 ' 0001 Two = &H2 ' 0010 Eight = &H8 ' 1000 Twelve = &Hc ' 1100 End Enum {0} Public Enum LabelsClass None = 0 One = 1 Four = 4 Six = 6 Seven = 7 End Enum "; // Verify no CA1027: Mark enums with FlagsAttribute string codeWithoutFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: false); await VerifyVB.VerifyAnalyzerAsync(codeWithoutFlags); // Verify CA2217: Do not mark enums with FlagsAttribute string codeWithFlags = GetBasicCode_EnumWithFlagsAttributes(code, hasFlags: true); await VerifyVB.VerifyAnalyzerAsync(codeWithFlags, GetCA2217BasicResultAt(3, 13, "NonSimpleFlagEnumClass", "4, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648, 4294967296, 8589934592, 17179869184, 34359738368, 68719476736, 137438953472, 274877906944, 549755813888, 1099511627776, 2199023255552, 4398046511104, 8796093022208, 17592186044416, 35184372088832, 70368744177664, 140737488355328, 281474976710656, 562949953421312, 1125899906842624, 2251799813685248, 4503599627370496, 9007199254740992, 18014398509481984, 36028797018963968, 72057594037927936, 144115188075855872, 288230376151711744, 576460752303423488, 1152921504606846976, 2305843009213693952, 4611686018427387904, 9223372036854775808"), GetCA2217BasicResultAt(13, 13, "BitValuesClass", "4"), GetCA2217BasicResultAt(22, 13, "LabelsClass", "2")); } private static DiagnosticResult GetCA1027CSharpResultAt(int line, int column, string enumTypeName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule1027) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(enumTypeName); private static DiagnosticResult GetCA1027BasicResultAt(int line, int column, string enumTypeName) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule1027) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(enumTypeName); private static DiagnosticResult GetCA2217CSharpResultAt(int line, int column, string enumTypeName, string missingValuesString) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule2217) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(enumTypeName, missingValuesString); private static DiagnosticResult GetCA2217BasicResultAt(int line, int column, string enumTypeName, string missingValuesString) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(EnumWithFlagsAttributeAnalyzer.Rule2217) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(enumTypeName, missingValuesString); } }
// 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.Globalization; using Xunit; namespace System.Tests { public static partial class TimeSpanTests { private static IEnumerable<object[]> MultiplicationTestData() { yield return new object[] {new TimeSpan(2, 30, 0), 2.0, new TimeSpan(5, 0, 0)}; yield return new object[] {new TimeSpan(14, 2, 30, 0), 192.0, TimeSpan.FromDays(2708)}; yield return new object[] {TimeSpan.FromDays(366), Math.PI, new TimeSpan(993446995288779)}; yield return new object[] {TimeSpan.FromDays(366), -Math.E, new TimeSpan(-859585952922633)}; yield return new object[] {TimeSpan.FromDays(29.530587981), 13.0, TimeSpan.FromDays(383.897643819444)}; yield return new object[] {TimeSpan.FromDays(-29.530587981), -12.0, TimeSpan.FromDays(354.367055833333)}; yield return new object[] {TimeSpan.FromDays(-29.530587981), 0.0, TimeSpan.Zero}; yield return new object[] {TimeSpan.MaxValue, 0.5, TimeSpan.FromTicks((long)(long.MaxValue * 0.5))}; } [Theory, MemberData(nameof(MultiplicationTestData))] public static void Multiplication(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(expected, timeSpan * factor); Assert.Equal(expected, factor * timeSpan); } [Fact] public static void OverflowingMultiplication() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue * 1.000000001); Assert.Throws<OverflowException>(() => -1.000000001 * TimeSpan.MaxValue); } [Fact] public static void NaNMultiplication() { AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1) * double.NaN); AssertExtensions.Throws<ArgumentException>("factor", () => double.NaN * TimeSpan.FromDays(1)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void Division(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(factor, expected / timeSpan, 14); double divisor = 1.0 / factor; Assert.Equal(expected, timeSpan / divisor); } [Fact] public static void DivideByZero() { Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1) / 0); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1) / 0); Assert.Throws<OverflowException>(() => TimeSpan.Zero / 0); Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1) / TimeSpan.Zero); Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1) / TimeSpan.Zero); Assert.True(double.IsNaN(TimeSpan.Zero / TimeSpan.Zero)); } [Fact] public static void NaNDivision() { AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1) / double.NaN); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void NamedMultiplication(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(expected, timeSpan.Multiply(factor)); } [Fact] public static void NamedOverflowingMultiplication() { Assert.Throws<OverflowException>(() => TimeSpan.MaxValue.Multiply(1.000000001)); } [Fact] public static void NamedNaNMultiplication() { AssertExtensions.Throws<ArgumentException>("factor", () => TimeSpan.FromDays(1).Multiply(double.NaN)); } [Theory, MemberData(nameof(MultiplicationTestData))] public static void NamedDivision(TimeSpan timeSpan, double factor, TimeSpan expected) { Assert.Equal(factor, expected.Divide(timeSpan), 14); double divisor = 1.0 / factor; Assert.Equal(expected, timeSpan.Divide(divisor)); } [Fact] public static void NamedDivideByZero() { Assert.Throws<OverflowException>(() => TimeSpan.FromDays(1).Divide(0)); Assert.Throws<OverflowException>(() => TimeSpan.FromDays(-1).Divide(0)); Assert.Throws<OverflowException>(() => TimeSpan.Zero.Divide(0)); Assert.Equal(double.PositiveInfinity, TimeSpan.FromDays(1).Divide(TimeSpan.Zero)); Assert.Equal(double.NegativeInfinity, TimeSpan.FromDays(-1).Divide(TimeSpan.Zero)); Assert.True(double.IsNaN(TimeSpan.Zero.Divide(TimeSpan.Zero))); } [Fact] public static void NamedNaNDivision() { AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1).Divide(double.NaN)); } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse_Span(string inputString, IFormatProvider provider, TimeSpan expected) { ReadOnlySpan<char> input = inputString.AsReadOnlySpan(); TimeSpan result; Assert.Equal(expected, TimeSpan.Parse(input, provider)); Assert.True(TimeSpan.TryParse(input, out result, provider)); Assert.Equal(expected, result); // Also negate if (!char.IsWhiteSpace(input[0])) { input = ("-" + inputString).AsReadOnlySpan(); expected = -expected; Assert.Equal(expected, TimeSpan.Parse(input, provider)); Assert.True(TimeSpan.TryParse(input, out result, provider)); Assert.Equal(expected, result); } } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Span_Invalid(string inputString, IFormatProvider provider, Type exceptionType) { if (inputString != null) { Assert.Throws(exceptionType, () => TimeSpan.Parse(inputString.AsReadOnlySpan(), provider)); Assert.False(TimeSpan.TryParse(inputString.AsReadOnlySpan(), out TimeSpan result, provider)); Assert.Equal(TimeSpan.Zero, result); } } [Theory] [MemberData(nameof(ParseExact_Valid_TestData))] public static void ParseExact_Span_Valid(string inputString, string format, TimeSpan expected) { ReadOnlySpan<char> input = inputString.AsReadOnlySpan(); TimeSpan result; Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US"))); Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US"))); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(expected, result); if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G") { // TimeSpanStyles is interpreted only for custom formats Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative)); Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result, TimeSpanStyles.AssumeNegative)); Assert.Equal(expected.Negate(), result); } else { // Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture)); Assert.True(TimeSpan.TryParse(input, out result, CultureInfo.InvariantCulture)); Assert.Equal(expected, result); } } [Theory] [MemberData(nameof(ParseExact_Invalid_TestData))] public static void ParseExactTest__Span_Invalid(string inputString, string format, Type exceptionType) { if (inputString != null) { Assert.Throws(exceptionType, () => TimeSpan.ParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"))); TimeSpan result; Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), new[] { format }, new CultureInfo("en-US"), out result)); Assert.Equal(TimeSpan.Zero, result); } } [Fact] public static void ParseExactMultiple_Span_InvalidNullEmptyFormats() { TimeSpan result; AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null)); Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null, out result)); Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), new string[0], null)); Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), new string[0], null, out result)); } [Theory] [MemberData(nameof(ToString_MemberData))] public static void TryFormat_Valid(TimeSpan input, string format, string expected) { int charsWritten; Span<char> dst; dst = new char[expected.Length - 1]; Assert.False(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture)); Assert.Equal(0, charsWritten); dst = new char[expected.Length]; Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(dst)); dst = new char[expected.Length + 1]; Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture)); Assert.Equal(expected.Length, charsWritten); Assert.Equal(expected, new string(dst.Slice(0, dst.Length - 1))); Assert.Equal(0, dst[dst.Length - 1]); } } }
using System; using System.Collections.Generic; using xsc = DotNetXmlSwfChart; namespace testWeb.tests { public class ColumnOne : ChartTestBase { #region ChartInclude public override DotNetXmlSwfChart.ChartHTML ChartInclude { get { DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML(); chartHtml.height = 300; chartHtml.bgColor = "ffffff"; chartHtml.flashFile = "charts/charts.swf"; chartHtml.libraryPath = "charts/charts_library"; chartHtml.xmlSource = "xmlData.aspx"; return chartHtml; } } #endregion #region Chart public override DotNetXmlSwfChart.Chart Chart { get { xsc.Chart chart = new xsc.Chart(); chart.AddChartType(xsc.XmlSwfChartType.Column); chart.AxisValue = SetAxisValue(xsc.XmlSwfChartType.Column); chart.ChartBorder = SetChartBorder(); chart.Data = SetChartData(); chart.ChartGridH = SetChartGridH(); chart.ChartRectangle = SetChartRectangle(); chart.ChartTransition = SetChartTransition(); chart.ChartValue = SetChartValue(); chart.DrawTexts = SetDrawTexts(); chart.LegendLabel = SetLegendLabel(); chart.LegendRectangle = SetLegendRectangle(); chart.SeriesColors = SetSeriesColors(); chart.SeriesGap = SetSeriesGap(); return chart; } } #endregion #region Properties #region SetAxisValue() private xsc.AxisValue SetAxisValue(xsc.XmlSwfChartType type) { xsc.AxisValue av = new xsc.AxisValue(); av.Min = -60; av.Font = "Arial"; av.Bold = true; av.Size = 10; av.Color = "000000"; av.Alpha = 50; av.Steps = 4; av.Prefix = ""; av.Suffix = ""; av.Decimals = 0; av.Separator = ""; av.ShowMin = true; return av; } #endregion #region SetChartBorder() private xsc.ChartBorder SetChartBorder() { xsc.ChartBorder cb = new xsc.ChartBorder(); cb.Color = "000000"; cb.TopThickness = 1; cb.BottomThickness = 2; cb.LeftThickness = 0; cb.RightThickness = 0; return cb; } #endregion #region SetChartData() private xsc.ChartData SetChartData() { xsc.ChartData cd = new xsc.ChartData(); cd.AddDataPoint(new xsc.ChartDataPoint("region A", "2005", -20)); cd.AddDataPoint(new xsc.ChartDataPoint("region A", "2006", 45)); cd.AddDataPoint(new xsc.ChartDataPoint("region A", "2007", 100)); cd.AddDataPoint(new xsc.ChartDataPoint("region B", "2005", -40)); cd.AddDataPoint(new xsc.ChartDataPoint("region B", "2006", 65)); cd.AddDataPoint(new xsc.ChartDataPoint("region B", "2007", 80)); return cd; } #endregion #region SetChartGridH() private xsc.ChartGrid SetChartGridH() { xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal); cg.Alpha = 20; cg.Color = "000000"; cg.Thickness = 1; cg.GridLineType = xsc.ChartGridLineType.dashed; return cg; } #endregion #region SetChartRectangle() private xsc.ChartRectangle SetChartRectangle() { xsc.ChartRectangle cr = new xsc.ChartRectangle(); cr.X = 75; cr.Y = 50; cr.Width = 300; cr.Height = 200; cr.PositiveColor = "000066"; cr.NegativeColor = "000000"; cr.PositiveAlpha = 10; cr.NegativeAlpha = 30; return cr; } #endregion #region SetChartTransition() private xsc.ChartTransition SetChartTransition() { xsc.ChartTransition ct = new xsc.ChartTransition(); ct.TransitionType = xsc.TransitionType.scale; ct.Delay = 0.5; ct.Duration = 0.5; ct.Order = xsc.TransitionOrder.series; return ct; } #endregion #region SetChartValue() private xsc.ChartValue SetChartValue() { xsc.ChartValue cv = new xsc.ChartValue(); cv.Color = "ffffff"; cv.Alpha = 85; cv.Font = "Arial"; cv.Bold = true; cv.Size = 10; cv.Position = "middle"; cv.Suffix = ""; cv.Prefix = ""; cv.Decimals = 0; cv.Separator = ""; cv.AsPercentage = false; return cv; } #endregion #region SetDrawTexts() private List<xsc.DrawText> SetDrawTexts() { List<xsc.DrawText> t = new List<xsc.DrawText>(); xsc.DrawText dt = new xsc.DrawText(); dt.Color = "000000"; dt.Alpha = 10; dt.Font = "Arial"; dt.Rotation = -90; dt.Bold = true; dt.Size = 75; dt.X = -20; dt.Y = 300; dt.Width = 300; dt.Height = 200; dt.HAlign = xsc.TextHAlign.left; dt.VAlign = xsc.TextVAlign.top; dt.Text = "revenue"; t.Add(dt); dt = new xsc.DrawText(); dt.Color = "000033"; dt.Alpha = 50; dt.Font = "Arial"; dt.Rotation = -90; dt.Bold = true; dt.Size = 16; dt.X = 7; dt.Y = 230; dt.Width = 300; dt.Height = 50; dt.HAlign = xsc.TextHAlign.center; dt.VAlign = xsc.TextVAlign.middle; dt.Text = "(millions)"; t.Add(dt); return t; } #endregion #region SetLegendLabel() private xsc.LegendLabel SetLegendLabel() { xsc.LegendLabel ll = new xsc.LegendLabel(); ll.Layout = xsc.LegendLabelLayout.horizontal; ll.Font = "Arial"; ll.Bold = true; ll.Size = 12; ll.Color = "333355"; ll.Alpha = 90; return ll; } #endregion #region SetLegendRectangle() private xsc.LegendRectangle SetLegendRectangle() { xsc.LegendRectangle lr = new xsc.LegendRectangle(); lr.X = 75; lr.Y = 27; lr.Width = 300; lr.Height = 20; lr.Margin = 5; lr.FillColor = "000066"; lr.FillAlpha = 8; lr.LineColor = "000000"; lr.LineAlpha = 0; lr.LineThickness = 0; return lr; } #endregion #region SetSeriesColors() private List<string> SetSeriesColors() { List<string> c = new List<string>(); c.Add("666666"); c.Add("768bb3"); return c; } #endregion #region SetSeriesGap() private xsc.SeriesGap SetSeriesGap() { xsc.SeriesGap sg = new xsc.SeriesGap(); sg.SetGap = 40; sg.BarGap = -25; return sg; } #endregion #endregion } }
// ------------------------------------------------------------------------------------------------------------------- // <copyright file="StringDifference.cs" company=""> // Copyright 2017 Cyrille Dupuydauby // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace NFluent.Helpers { using System; using System.Collections.Generic; using Extensions; /// <summary> /// Describes difference between strings. /// </summary> internal enum DifferenceMode { /// <summary> /// Strings are same. /// </summary> NoDifference, /// <summary> /// General difference. /// </summary> General, /// <summary> /// Difference only in case (e.g. Foo vs foo). /// </summary> CaseDifference, /// <summary> /// Contains at least one longer line. /// </summary> LongerLine, /// <summary> /// Contains at least one shorter line. /// </summary> ShorterLine, /// <summary> /// End of line marker is different. /// </summary> EndOfLine, /// <summary> /// Line(s) are missing. /// </summary> MissingLines, /// <summary> /// Extra lines found. /// </summary> ExtraLines, /// <summary> /// Different in spaces (one vs many, tabs vs spaces...). /// </summary> Spaces, /// <summary> /// String is longer. /// </summary> Longer, /// <summary> /// String is shorter. /// </summary> Shorter, /// <summary> /// Strings have the same length but are different. /// </summary> GeneralSameLength } internal class StringDifference { private const char Linefeed = '\n'; private const char CarriageReturn = '\r'; private StringDifference(DifferenceMode mode, int line, int position, string actual, string expected, bool isFulltext) { this.Kind = mode; this.Line = line; this.Position = position; this.Expected = expected; this.Actual = actual; this.IsFullText = isFulltext; } public DifferenceMode Kind { get; } public int Line { get; } public string Expected { get; internal set; } public string Actual { get; internal set; } public int Position { get; } private bool IsFullText { get; } private static string[] SplitLines(string text) { var temp = new List<string>(); var index = 0; while (index <=text.Length) { var start = index; if (index == text.Length) { temp.Add(string.Empty); break; } index = text.IndexOf(Linefeed, start); if (index < 0) { temp.Add(text.Substring(start)); index = text.Length+1; } else { temp.Add(text.Substring(start, index+1-start)); index = index + 1; } } return temp.ToArray(); } public static IList<StringDifference> Analyze(string actual, string expected, bool caseInsensitive) { if (actual == expected) { return null; } var result = new List<StringDifference>(); var actualLines = SplitLines(actual); var expectedLines = SplitLines(expected); var sharedLines = Math.Min(actualLines.Length, expectedLines.Length); var boolSingleLine = expectedLines.Length == 1; for (var line = 0; line < sharedLines; line++) { var stringDifference = Build(line, actualLines[line], expectedLines[line], caseInsensitive, boolSingleLine); if (stringDifference.Kind != DifferenceMode.NoDifference) { result.Add(stringDifference); } } if (expectedLines.Length > sharedLines) { result.Add(Build(sharedLines, null, expectedLines[sharedLines], caseInsensitive, false)); } else if (actualLines.Length > sharedLines) { result.Add(Build(sharedLines, actualLines[sharedLines], null, caseInsensitive, false)); } return result; } /// <summary> /// Summarize a list of issues to a single difference code. /// </summary> /// <param name="stringDifferences"> /// List of differences. /// </param> /// <returns> /// A <see cref="DifferenceMode"/> value describing the overall differences. /// </returns> /// <remarks> /// Returns <see cref="DifferenceMode.General"/> unless all differences are of same kind. /// </remarks> public static DifferenceMode Summarize(IEnumerable<StringDifference> stringDifferences) { var result = DifferenceMode.NoDifference; foreach (var stringDifference in stringDifferences) { if (result == DifferenceMode.NoDifference) { result = stringDifference.Kind; } else if (result != stringDifference.Kind) { result = DifferenceMode.General; break; } } return result; } public static string SummaryMessage(IList<StringDifference> differences) { return differences[0].GetErrorMessage(Summarize(differences)); } /// <summary> /// Transform a string to identify not printable difference /// </summary> /// <param name="textToScan"></param> /// <returns></returns> public string HighLightForDifference(string textToScan) { switch (this.Kind) { case DifferenceMode.Spaces: textToScan = HighlightTabsIfAny(textToScan); break; case DifferenceMode.EndOfLine: textToScan = HighlightCrlfOrLfIfAny(textToScan); break; } return textToScan; } private string GetErrorMessage(DifferenceMode summary) { var mainText = GetMessage(summary); const int extractLength = 20; string actual; string expected; if (this.Line > 0 || this.Expected.Length > extractLength * 2 || this.Actual.Length > extractLength * 2) { actual = this.Actual.Extract(this.Position, extractLength); expected = this.Expected.Extract(this.Position, extractLength); } else { actual = this.Actual; expected = this.Expected; } actual = this.HighLightForDifference(actual); expected = this.HighLightForDifference(expected); if (!this.IsFullText || this.Actual != actual || this.Expected != expected) { if (summary == DifferenceMode.MissingLines) { mainText+= $" At line {this.Line + 1}, expected '{HighlightCrlfOrLfIfAny(expected)}' but line is missing."; } else if (summary == DifferenceMode.ExtraLines) { mainText+= $" Found line {this.Line + 1} '{HighlightCrlfOrLfIfAny(actual)}'."; } else { mainText += string.Format( " At line {0}, col {3}, expected '{1}' was '{2}'.", this.Line + 1, HighlightCrlfOrLfIfAny(expected), HighlightCrlfOrLfIfAny(actual), this.Position + 1); } } return mainText; } /// <summary> /// Inserts &lt;&lt;CRLF&gt;&gt; before the first CRLF or &lt;&lt;LF&gt;&gt; before the first LF. /// </summary> /// <param name="str">The string.</param> /// <returns>The same string but with &lt;&lt;CRLF&gt;&gt; inserted before the first CRLF or &lt;&lt;LF&gt;&gt; inserted before the first LF.</returns> private static string HighlightCrlfOrLfIfAny(string str) { str = str.Replace("\r\n", "<<CRLF>>"); //str = str.Replace("\r", "<<CR>>"); //==> isolated CR are not considered as EOL markers str = str.Replace("\n", "<<LF>>"); return str; } /// <summary> /// Replace every tab char by "&lt;&lt;tab&gt;&gt;". /// </summary> /// <param name="str">The original string.</param> /// <returns>The original string with every \t replaced with "&lt;&lt;tab&gt;&gt;".</returns> private static string HighlightTabsIfAny(string str) { return str.Replace("\t", "<<tab>>"); } #region Static Methods private static StringDifference Build(int line, string actual, string expected, bool ignoreCase, bool isFullText) { if (actual == null) { return new StringDifference(DifferenceMode.MissingLines, line, 0, null, expected, isFullText); } if (expected == null) { return new StringDifference(DifferenceMode.ExtraLines, line, 0, actual, null, isFullText); } // check the common part of both strings var j = 0; var i = 0; var type = DifferenceMode.NoDifference; var position = 0; for (; i < actual.Length && j < expected.Length; i++, j++) { var actualChar = actual[i]; var expectedChar = expected[j]; if (char.IsWhiteSpace(actualChar) && char.IsWhiteSpace(expectedChar)) { // special case for end of line markers if (IsEol(actualChar)) { if (expectedChar == actualChar) { continue; } return new StringDifference( IsEol(expectedChar) ? DifferenceMode.EndOfLine : DifferenceMode.ShorterLine, line, i, actual, expected, isFullText); } if (IsEol(expectedChar)) { return new StringDifference(DifferenceMode.LongerLine, line, i, actual, expected, isFullText); } var actualStart = i; var expectedStart = j; // we skip all spaces while (ContainsWhiteSpaceAt(actual, i+1)) { i++; } while (ContainsWhiteSpaceAt(expected, j+1)) { j++; } if (actual.Substring(actualStart, i - actualStart) != expected.Substring(expectedStart, j - expectedStart)) { if (type != DifferenceMode.Spaces) { type = DifferenceMode.Spaces; position = i; } } } else if (actualChar == expectedChar) { } else if (StringExtensions.CompareCharIgnoringCase(actualChar, expectedChar)) { if (ignoreCase) { continue; } // difference in case only if (type == DifferenceMode.CaseDifference) { continue; } type = DifferenceMode.CaseDifference; position = i; } else { type = DifferenceMode.General; position = i; break; } } switch (type) { case DifferenceMode.General: if (actual.Length == expected.Length) { type = DifferenceMode.GeneralSameLength; } return new StringDifference(type, line, position, actual, expected, isFullText); case DifferenceMode.Spaces when i == actual.Length && j == expected.Length: return new StringDifference(type, line, position, actual, expected, isFullText); } // strings are same so far // the actualLine string is longer than expectedLine if (i < actual.Length) { DifferenceMode difference; if (IsEol(actual[i])) { // lines are missing, the error will be reported at next line difference = DifferenceMode.NoDifference; } else difference = isFullText ? DifferenceMode.Longer : DifferenceMode.LongerLine; return new StringDifference( difference, line, i, actual, expected, isFullText); } if (j < expected.Length) { DifferenceMode difference; if (IsEol(expected[j])) { // lines are missing, the error will be reported at next sline difference = DifferenceMode.NoDifference; } else difference = isFullText ? DifferenceMode.Shorter : DifferenceMode.ShorterLine; return new StringDifference( difference, line, j, actual, expected, isFullText); } return new StringDifference(type, line, position, actual, expected, isFullText); } private static bool ContainsWhiteSpaceAt(string actual, int i) { return i < actual.Length && char.IsWhiteSpace(actual[i]) && !IsEol(actual[i]); } private static bool IsEol(char theChar) { return theChar == CarriageReturn || theChar == Linefeed; } /// <summary> /// Get general message /// </summary> /// <param name="summary">Synthetic error</param> /// <returns></returns> public static string GetMessage(DifferenceMode summary) { string message; switch (summary) { default: message = "The {0} is different from {1}."; break; case DifferenceMode.GeneralSameLength: message = "The {0} is different from the {1} but has same length."; break; case DifferenceMode.Spaces: message = "The {0} has different spaces than {1}."; break; case DifferenceMode.EndOfLine: message = "The {0} has different end of line markers than {1}."; break; case DifferenceMode.CaseDifference: message = "The {0} is different in case from the {1}."; break; case DifferenceMode.ExtraLines: message = "The {0} is different from {1}, it contains extra lines at the end."; break; case DifferenceMode.LongerLine: message = "The {0} is different from {1}, one line is longer."; break; case DifferenceMode.ShorterLine: message = "The {0} is different from {1}, one line is shorter."; break; case DifferenceMode.MissingLines: message = "The {0} is different from {1}, it is missing some line(s)."; break; case DifferenceMode.Longer: message = "The {0} is different from {1}, it contains extra text at the end."; break; case DifferenceMode.Shorter: message = "The {0} is different from {1}, it is missing the end."; break; } return message; } #endregion } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Telegram.Bot.Tests.Integ.Framework; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Xunit; using Constants = Telegram.Bot.Tests.Integ.Framework.Constants; namespace Telegram.Bot.Tests.Integ.Admin_Bot { [Collection(Constants.TestCollections.ChatMemberAdministration)] [Trait(Constants.CategoryTraitName, Constants.InteractiveCategoryValue)] [TestCaseOrderer(Constants.TestCaseOrderer, Constants.AssemblyName)] public class ChatMemberAdministrationTests : IClassFixture<ChatMemberAdministrationTestFixture> { ITelegramBotClient BotClient => _fixture.BotClient; readonly TestsFixture _fixture; readonly ChatMemberAdministrationTestFixture _classFixture; public ChatMemberAdministrationTests(TestsFixture fixture, ChatMemberAdministrationTestFixture classFixture) { _fixture = fixture; _classFixture = classFixture; } #region Kick, Unban, and Invite chat member back [OrderedFact("Should get regular chat member with member status and of ChatMemberMember type")] public async Task Should_Get_Chat_Member_Member() { ChatMember chatMember = await BotClient.GetChatMemberAsync( chatId: _fixture.SupergroupChat, userId: _classFixture.RegularMemberUserId ); Assert.Equal(ChatMemberStatus.Member, chatMember.Status); Assert.IsType<ChatMemberMember>(chatMember); } [OrderedFact("Should kick user from chat and ban him/her for ever")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.KickChatMember)] public async Task Should_Kick_Chat_Member_For_Ever() { await BotClient.BanChatMemberAsync( chatId: _fixture.SupergroupChat.Id, userId: _classFixture.RegularMemberUserId ); } [OrderedFact("Should get banned chat member with kicked status and of ChatMemberBanned type")] public async Task Should_Get_Chat_Member_Kicked() { ChatMember chatMember = await BotClient.GetChatMemberAsync( chatId: _fixture.SupergroupChat, userId: _classFixture.RegularMemberUserId ); Assert.Equal(ChatMemberStatus.Kicked, chatMember.Status); ChatMemberBanned bannedChatMember = Assert.IsType<ChatMemberBanned>(chatMember); Assert.Equal(default, bannedChatMember.UntilDate); Assert.Null(bannedChatMember.UntilDate); } [OrderedFact("Should unban a chat member")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.UnbanChatMember)] public async Task Should_Unban_Chat_Member() { await BotClient.UnbanChatMemberAsync( chatId: _fixture.SupergroupChat.Id, userId: _classFixture.RegularMemberUserId ); } [OrderedFact("Should export an invite link to the group")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.ExportChatInviteLink)] public async Task Should_Export_Chat_Invite_Link() { string result = await BotClient.ExportChatInviteLinkAsync(_fixture.SupergroupChat.Id); Assert.StartsWith("https://t.me/joinchat/", result); _classFixture.GroupInviteLink = result; } [OrderedFact("Should receive a notification of new member (same kicked member) joining the chat")] public async Task Should_Receive_New_Chat_Member_Notification() { await _fixture.SendTestInstructionsAsync( $"@{_classFixture.RegularMemberUserName.Replace("_", @"\_")} should join the group using invite link sent to " + "him/her in private chat" ); await _fixture.UpdateReceiver.DiscardNewUpdatesAsync(); await BotClient.SendTextMessageAsync( chatId: _classFixture.RegularMemberChat, text: _classFixture.GroupInviteLink ); Update update = ( await _fixture.UpdateReceiver.GetUpdatesAsync( predicate: u => u.Message!.Chat.Type == ChatType.Supergroup && u.Message!.Chat.Id == _fixture.SupergroupChat.Id && u.Message!.Type == MessageType.ChatMembersAdded, updateTypes: new[] { UpdateType.Message }) ).Single(); await _fixture.UpdateReceiver.DiscardNewUpdatesAsync(); Message serviceMsg = update.Message; Assert.NotNull(serviceMsg); Assert.NotNull(serviceMsg.NewChatMembers); Assert.NotEmpty(serviceMsg.NewChatMembers); User newUser = Assert.Single(serviceMsg.NewChatMembers); Assert.Equal( _classFixture.RegularMemberUserId.ToString(), newUser!.Id.ToString() ); } #endregion #region Promote and Restrict Chat Member [OrderedFact("Should promote chat member to change chat information")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.PromoteChatMember)] public async Task Should_Promote_User_To_Change_Chat_Info() { //ToDo exception when user isn't in group. Bad Request: bots can't add new chat members await BotClient.PromoteChatMemberAsync( chatId: _fixture.SupergroupChat.Id, userId: _classFixture.RegularMemberUserId, canChangeInfo: true ); } [OrderedFact("Should set a custom title for the previously promoted admin")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.SetChatAdministratorCustomTitle)] public async Task Should_Set_Custom_Title_For_Admin() { ChatMember promotedRegularUser = await BotClient.GetChatMemberAsync( _fixture.SupergroupChat, _classFixture.RegularMemberUserId ); await BotClient.SetChatAdministratorCustomTitleAsync( chatId: _fixture.SupergroupChat, userId: promotedRegularUser.User.Id, customTitle: "CHANGED TITLE" ); ChatMember newChatMember = await BotClient.GetChatMemberAsync( _fixture.SupergroupChat, promotedRegularUser.User.Id ); Assert.Equal(ChatMemberStatus.Administrator, newChatMember.Status); ChatMemberAdministrator administrator = Assert.IsType<ChatMemberAdministrator>(newChatMember); Assert.Equal("CHANGED TITLE", administrator.CustomTitle); // Restore default title by sending empty string await BotClient.SetChatAdministratorCustomTitleAsync( chatId: _fixture.SupergroupChat, userId: promotedRegularUser.User.Id, customTitle: string.Empty ); } [OrderedFact("Should demote chat member by taking his/her only admin right: change_info")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.PromoteChatMember)] public async Task Should_Demote_User() { //ToDo exception when user isn't in group. Bad Request: USER_NOT_MUTUAL_CONTACT await BotClient.PromoteChatMemberAsync( chatId: _fixture.SupergroupChat.Id, userId: _classFixture.RegularMemberUserId, canChangeInfo: false ); } [OrderedFact("Should restrict chat member from sending stickers temporarily")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.RestrictChatMember)] public async Task Should_Restrict_Sending_Stickers_Temporarily() { const int banSeconds = 35; await BotClient.RestrictChatMemberAsync( chatId: _fixture.SupergroupChat.Id, userId: _classFixture.RegularMemberUserId, untilDate: DateTime.UtcNow.AddSeconds(banSeconds), permissions: new ChatPermissions { CanSendMessages = true, CanSendMediaMessages = true, CanSendOtherMessages = false } ); } [OrderedFact("Should get banned chat member with restricted status and of ChatMemberRestricted type")] public async Task Should_Get_Chat_Member_Restricted() { ChatMember chatMember = await BotClient.GetChatMemberAsync( chatId: _fixture.SupergroupChat, userId: _classFixture.RegularMemberUserId ); Assert.Equal(ChatMemberStatus.Restricted, chatMember.Status); ChatMemberRestricted restrictedMember = Assert.IsType<ChatMemberRestricted>(chatMember); Assert.NotNull(restrictedMember.UntilDate); Assert.False(restrictedMember.CanSendOtherMessages); } #endregion #region Receving chat member status update [OrderedFact("Should receive chat member updated")] public async Task Should_Receive_Chat_Member_Updated() { await _fixture.SendTestInstructionsAsync( $"Chat admin should kick @{_classFixture.RegularMemberUserName.Replace("_", @"\_")}." ); Update[] updates = await _fixture.UpdateReceiver .GetUpdatesAsync( predicate: u => u.ChatMember?.Chat.Id == _fixture.SupergroupChat.Id, updateTypes: UpdateType.ChatMember ) .ConfigureAwait(false); Update update = updates.Single(); await _fixture.UpdateReceiver.DiscardNewUpdatesAsync(); ChatMemberUpdated chatMemberUpdated = update.ChatMember; Assert.NotNull(chatMemberUpdated); Assert.NotNull(chatMemberUpdated.OldChatMember); Assert.NotNull(chatMemberUpdated.NewChatMember); Assert.True(chatMemberUpdated.OldChatMember.Status == ChatMemberStatus.Restricted); Assert.True(chatMemberUpdated.NewChatMember.Status == ChatMemberStatus.Kicked); Assert.IsType<ChatMemberRestricted>(chatMemberUpdated.OldChatMember); ChatMemberBanned newChatMember = Assert.IsType<ChatMemberBanned>(chatMemberUpdated.NewChatMember); Assert.Null(newChatMember.UntilDate); Assert.Equal(_classFixture.RegularMemberUserId, newChatMember.User.Id); } // This section is needed for technical reasons, don't remove [OrderedFact("Should_Wait_For_Regular_Chat_Member_To_Join")] public async Task Should_Wait_For_Regular_Chat_Member_To_Join() { TimeSpan waitTime = TimeSpan.FromMinutes(2); using CancellationTokenSource cts = new(TimeSpan.FromMinutes(2)); await _fixture.SendTestInstructionsAsync( $"Chat admin should invite @{_classFixture.RegularMemberUserName.Replace("_", @"\_")} back to the group. Bot will be waiting" + $" for {waitTime.Minutes} minutes." ); await _fixture.UpdateReceiver.DiscardNewUpdatesAsync(); Update _ = (await _fixture.UpdateReceiver .GetUpdatesAsync( u => u.Message?.Chat.Id == _fixture.SupergroupChat.Id && u.Message.Type == MessageType.ChatMembersAdded, updateTypes: UpdateType.Message, cancellationToken: cts.Token ) ).Single(); // ReSharper disable once MethodSupportsCancellation await _fixture.UpdateReceiver.DiscardNewUpdatesAsync(); } #endregion #region Kick chat member temporarily [OrderedFact("Should kick user from chat and ban him/her temporarily")] [Trait(Constants.MethodTraitName, Constants.TelegramBotApiMethods.KickChatMember)] public async Task Should_Kick_Chat_Member_Temporarily() { const int banSeconds = 35; await _fixture.SendTestInstructionsAsync( $"@{_classFixture.RegularMemberUserName.Replace("_", @"\_")} should be able to join again in" + $" *{banSeconds} seconds* via the link shared in private chat with him/her" ); await BotClient.BanChatMemberAsync( chatId: _fixture.SupergroupChat.Id, userId: _classFixture.RegularMemberUserId, untilDate: DateTime.UtcNow.AddSeconds(banSeconds) ); } [OrderedFact("Should get banned chat member with restricted status and of ChatMemberBanned type with not null UntilDate")] public async Task Should_Get_Chat_Member_Restricted_With_Until_Date() { ChatMember chatMember = await BotClient.GetChatMemberAsync( chatId: _fixture.SupergroupChat, userId: _classFixture.RegularMemberUserId ); Assert.Equal(ChatMemberStatus.Kicked, chatMember.Status); ChatMemberBanned restrictedMember = Assert.IsType<ChatMemberBanned>(chatMember); Assert.NotNull(restrictedMember.UntilDate); } #endregion } }
using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Core.Auth; using Microsoft.WindowsAzure.Storage.Core.Executor; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using Microsoft.WindowsAzure.Storage.Table.Protocol; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Storage.Table { public class CloudTable { public CloudTableClient ServiceClient { get; private set; } public string Name { get; private set; } public Uri Uri { get { throw new System.NotImplementedException(); } } public StorageUri StorageUri { get; private set; } public CloudTable(Uri tableAddress) : this(tableAddress, (StorageCredentials) null) { throw new System.NotImplementedException(); } public CloudTable(Uri tableAbsoluteUri, StorageCredentials credentials) : this(new StorageUri(tableAbsoluteUri), credentials) { throw new System.NotImplementedException(); } public CloudTable(StorageUri tableAddress, StorageCredentials credentials) { throw new System.NotImplementedException(); } internal CloudTable(string tableName, CloudTableClient client) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<TableResult> ExecuteAsync(TableOperation operation) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<TableResult> ExecuteAsync(TableOperation operation, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch) { throw new System.NotImplementedException(); } public virtual Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<IList<TableResult>> ExecuteBatchAsync(TableBatchOperation batch, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync(TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync(TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> CreateIfNotExistsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> CreateIfNotExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> CreateIfNotExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteAsync(TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteAsync(TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> DeleteIfExistsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> DeleteIfExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> DeleteIfExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> ExistsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> ExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> ExistsAsync(TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetPermissionsAsync(TablePermissions permissions) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetPermissionsAsync(TablePermissions permissions, TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetPermissionsAsync(TablePermissions permissions, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<TablePermissions> GetPermissionsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<TablePermissions> GetPermissionsAsync(TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<TablePermissions> GetPermissionsAsync(TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public virtual Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token) { throw new System.NotImplementedException(); } public virtual Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext) { throw new System.NotImplementedException(); } public virtual Task<TableQuerySegment<TResult>> ExecuteQuerySegmentedAsync<TResult>(TableQuery query, EntityResolver<TResult> resolver, TableContinuationToken token, TableRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessTablePolicy policy) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessTablePolicy policy, string accessPolicyIdentifier, string startPartitionKey, string startRowKey, string endPartitionKey, string endRowKey, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange) { throw new System.NotImplementedException(); } public override string ToString() { throw new System.NotImplementedException(); } private void ParseQueryAndVerify(StorageUri address, StorageCredentials credentials) { throw new System.NotImplementedException(); } private string GetCanonicalName() { throw new System.NotImplementedException(); } } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Email Queues. /// </summary> [RoutePrefix("api/v1.0/config/email-queue")] public class EmailQueueController : FrapidApiController { /// <summary> /// The EmailQueue repository. /// </summary> private readonly IEmailQueueRepository EmailQueueRepository; public EmailQueueController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>(); this._UserId = AppUsers.GetCurrent().View.UserId.To<int>(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>(); this._Catalog = AppUsers.GetCatalog(); this.EmailQueueRepository = new Frapid.Config.DataAccess.EmailQueue { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public EmailQueueController(IEmailQueueRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.To<long>(); this._UserId = view.UserId.To<int>(); this._OfficeId = view.OfficeId.To<int>(); this._Catalog = catalog; this.EmailQueueRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Creates meta information of "email queue" entity. /// </summary> /// <returns>Returns the "email queue" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/email-queue/meta")] [Authorize] public EntityView GetEntityView() { if (this._LoginId == 0) { return new EntityView(); } return new EntityView { PrimaryKey = "queue_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "queue_id", PropertyName = "QueueId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "from_name", PropertyName = "FromName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "reply_to", PropertyName = "ReplyTo", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "subject", PropertyName = "Subject", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "send_to", PropertyName = "SendTo", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 256 }, new EntityColumn { ColumnName = "attachments", PropertyName = "Attachments", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "message", PropertyName = "Message", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "added_on", PropertyName = "AddedOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "delivered", PropertyName = "Delivered", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "delivered_on", PropertyName = "DeliveredOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "canceled", PropertyName = "Canceled", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "canceled_on", PropertyName = "CanceledOn", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of email queues. /// </summary> /// <returns>Returns the count of the email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/email-queue/count")] [Authorize] public long Count() { try { return this.EmailQueueRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of email queue. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/email-queue/all")] [Authorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetAll() { try { return this.EmailQueueRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of email queue for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/email-queue/export")] [Authorize] public IEnumerable<dynamic> Export() { try { return this.EmailQueueRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of email queue. /// </summary> /// <param name="queueId">Enter QueueId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{queueId}")] [Route("~/api/config/email-queue/{queueId}")] [Authorize] public Frapid.Config.Entities.EmailQueue Get(long queueId) { try { return this.EmailQueueRepository.Get(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/email-queue/get")] [Authorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> Get([FromUri] long[] queueIds) { try { return this.EmailQueueRepository.Get(queueIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of email queue. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/email-queue/first")] [Authorize] public Frapid.Config.Entities.EmailQueue GetFirst() { try { return this.EmailQueueRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of email queue. /// </summary> /// <param name="queueId">Enter QueueId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{queueId}")] [Route("~/api/config/email-queue/previous/{queueId}")] [Authorize] public Frapid.Config.Entities.EmailQueue GetPrevious(long queueId) { try { return this.EmailQueueRepository.GetPrevious(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of email queue. /// </summary> /// <param name="queueId">Enter QueueId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{queueId}")] [Route("~/api/config/email-queue/next/{queueId}")] [Authorize] public Frapid.Config.Entities.EmailQueue GetNext(long queueId) { try { return this.EmailQueueRepository.GetNext(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of email queue. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/email-queue/last")] [Authorize] public Frapid.Config.Entities.EmailQueue GetLast() { try { return this.EmailQueueRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/email-queue")] [Authorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetPaginatedResult() { try { return this.EmailQueueRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/email-queue/page/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetPaginatedResult(long pageNumber) { try { return this.EmailQueueRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of email queues using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered email queues.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/email-queue/count-where")] [Authorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.EmailQueueRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/email-queue/get-where/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.EmailQueueRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of email queues using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/email-queue/count-filtered/{filterName}")] [Authorize] public long CountFiltered(string filterName) { try { return this.EmailQueueRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 email queues on each page, sorted by the property QueueId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/email-queue/get-filtered/{pageNumber}/{filterName}")] [Authorize] public IEnumerable<Frapid.Config.Entities.EmailQueue> GetFiltered(long pageNumber, string filterName) { try { return this.EmailQueueRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of email queues. /// </summary> /// <returns>Returns an enumerable key/value collection of email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/email-queue/display-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.EmailQueueRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for email queues. /// </summary> /// <returns>Returns an enumerable custom field collection of email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/email-queue/custom-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.EmailQueueRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for email queues. /// </summary> /// <returns>Returns an enumerable custom field collection of email queues.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/email-queue/custom-fields/{resourceId}")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.EmailQueueRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of EmailQueue class. /// </summary> /// <param name="emailQueue">Your instance of email queues class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/email-queue/add-or-edit")] [Authorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic emailQueue = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (emailQueue == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.EmailQueueRepository.AddOrEdit(emailQueue, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of EmailQueue class. /// </summary> /// <param name="emailQueue">Your instance of email queues class to add.</param> [AcceptVerbs("POST")] [Route("add/{emailQueue}")] [Route("~/api/config/email-queue/add/{emailQueue}")] [Authorize] public void Add(Frapid.Config.Entities.EmailQueue emailQueue) { if (emailQueue == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.EmailQueueRepository.Add(emailQueue); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of EmailQueue class. /// </summary> /// <param name="emailQueue">Your instance of EmailQueue class to edit.</param> /// <param name="queueId">Enter the value for QueueId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{queueId}")] [Route("~/api/config/email-queue/edit/{queueId}")] [Authorize] public void Edit(long queueId, [FromBody] Frapid.Config.Entities.EmailQueue emailQueue) { if (emailQueue == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.EmailQueueRepository.Update(emailQueue, queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of EmailQueue class. /// </summary> /// <param name="collection">Your collection of EmailQueue class to bulk import.</param> /// <returns>Returns list of imported queueIds.</returns> /// <exception cref="DataAccessException">Thrown when your any EmailQueue class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/email-queue/bulk-import")] [Authorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> emailQueueCollection = this.ParseCollection(collection); if (emailQueueCollection == null || emailQueueCollection.Count.Equals(0)) { return null; } try { return this.EmailQueueRepository.BulkImport(emailQueueCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of EmailQueue class via QueueId. /// </summary> /// <param name="queueId">Enter the value for QueueId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{queueId}")] [Route("~/api/config/email-queue/delete/{queueId}")] [Authorize] public void Delete(long queueId) { try { this.EmailQueueRepository.Delete(queueId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using mshtml; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Mshtml; using System.Text.RegularExpressions; namespace OpenLiveWriter.SpellChecker { public delegate void DamageFunction(MarkupRange range); public delegate bool MarkupRangeFilter(MarkupRange range); /// <summary> /// Implementation of IWordRange for an MSHTML control /// </summary> public class MshtmlWordRange : IWordRange { MarkupRangeFilter filter = null; DamageFunction damageFunction = null; /// <summary> /// Initialize word range for the entire body of the document /// </summary> /// <param name="mshtml">mshtml control</param> public MshtmlWordRange(MshtmlControl mshtmlControl) : this(mshtmlControl.HTMLDocument, false, null, null) { } /// <summary> /// Initialize word range for the specified markup-range within the document /// </summary> public MshtmlWordRange(IHTMLDocument document, bool useDocumentSelectionRange, MarkupRangeFilter filter, DamageFunction damageFunction) { MshtmlMarkupServices markupServices = new MshtmlMarkupServices((IMarkupServicesRaw)document); IHTMLDocument2 document2 = (IHTMLDocument2)document; MarkupRange markupRange; if (useDocumentSelectionRange) { markupRange = markupServices.CreateMarkupRange(document2.selection); } else { // TODO: Although this works fine, it would be better to only spellcheck inside editable regions. markupRange = markupServices.CreateMarkupRange(document2.body, false); } Init(document, markupServices, markupRange, filter, damageFunction, useDocumentSelectionRange); } /// <summary> /// Initialize word range for the specified markup-range within the document /// </summary> public MshtmlWordRange(IHTMLDocument document, MarkupRange markupRange, MarkupRangeFilter filter, DamageFunction damageFunction) { MshtmlMarkupServices markupServices = new MshtmlMarkupServices((IMarkupServicesRaw)document); Init(document, markupServices, markupRange, filter, damageFunction, true); } private void Init(IHTMLDocument document, MshtmlMarkupServices markupServices, MarkupRange selectionRange, MarkupRangeFilter filter, DamageFunction damageFunction, bool expandRange) { // save references this.htmlDocument = document; this.markupServices = markupServices; this.selectionRange = selectionRange; this.filter = filter; this.damageFunction = damageFunction; // If the range is already the body, don't expand it or else it will be the whole document if (expandRange) ExpandRangeToWordBoundaries(selectionRange); // initialize pointer to beginning of selection range MarkupPointer wordStart = MarkupServices.CreateMarkupPointer(selectionRange.Start); MarkupPointer wordEnd = MarkupServices.CreateMarkupPointer(selectionRange.Start); //create the range for holding the current word. //Be sure to set its gravity so that it stays around text that get replaced. currentWordRange = MarkupServices.CreateMarkupRange(wordStart, wordEnd); currentWordRange.Start.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Left; currentWordRange.End.Gravity = _POINTER_GRAVITY.POINTER_GRAVITY_Right; currentVirtualPosition = currentWordRange.End.Clone(); } public static void ExpandRangeToWordBoundaries(MarkupRange range) { //adjust the selection so that it entirely covers the first and last words. range.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDEND); range.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVWORDBEGIN); range.End.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVWORDBEGIN); range.End.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDEND); } public bool IsCurrentWordUrlPart() { return IsRangeInUrl(currentWordRange); } public bool FilterApplies() { return filter != null && filter(currentWordRange); } public bool FilterAppliesRanged(int offset, int length) { MarkupRange adjustedRange = currentWordRange.Clone(); MarkupHelpers.AdjustMarkupRange(ref stagingTextRange, adjustedRange, offset, length); return filter != null && filter(adjustedRange); } /// <summary> /// Do we have another word in our range? /// </summary> /// <returns></returns> public bool HasNext() { return currentWordRange.End.IsLeftOf(selectionRange.End); } /// <summary> /// Advance to next word /// </summary> public void Next() { currentWordRange.End.MoveToPointer(currentVirtualPosition); do { //advance the start pointer to the beginning of next word if(!currentWordRange.End.IsEqualTo(selectionRange.Start)) //avoids skipping over the first word { //fix bug 1848 - move the start to the end pointer before advancing to the next word //this ensures that the "next begin" is after the current selection. currentWordRange.Start.MoveToPointer(currentWordRange.End); currentWordRange.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVWORDBEGIN); currentWordRange.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDBEGIN); } else { //Special case for putting the start pointer at the beginning of the //correct word when the selection may or may not be already adjacent //to the the beginning of the word. //Note: theoretically, the selection adjustment in the constructor //guarantees that we will be flush against the first word, so we could //probably do nothing, but it works, so we'll keep it. currentWordRange.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDEND); currentWordRange.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVWORDBEGIN); } //advance the end pointer to the end of next word currentWordRange.End.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_NEXTWORDEND); if(currentWordRange.Start.IsRightOf(currentWordRange.End)) { //Note: this was a condition that caused several bugs that caused us to stop //spell-checking correctly, so this logic is here in case we still have edge //cases that trigger it. //This should not occur anymore since we fixed several causes of this //condition by setting the currentWordRange gravity, and detecting case where //the selection may or may-not start at the beginning of a word. Debug.Fail("word start jumped past word end"); //if this occured, it was probably because start was already at the beginning //of the correct word before it was moved. To resolve this situation, we //move the start pointer back to the beginning of the word that the end pointer //is at. Since the End pointer always advances on each iteration, this should not //cause an infinite loop. The worst case scenario is that we check the same word //more than once. currentWordRange.Start.MoveToPointer(currentWordRange.End); currentWordRange.Start.MoveUnit(_MOVEUNIT_ACTION.MOVEUNIT_PREVWORDBEGIN); } } while( MarkupHelpers.GetRangeTextFast(currentWordRange) == null && currentWordRange.End.IsLeftOf(selectionRange.End)); currentVirtualPosition.MoveToPointer(currentWordRange.End); if(currentWordRange.End.IsRightOf(selectionRange.End)) { //then collapse the range so that CurrentWord returns Empty; currentWordRange.Start.MoveToPointer(currentWordRange.End); } else { MarkupRange testRange = currentWordRange.Clone(); testRange.Collapse(false); testRange.End.MoveUnitBounded(_MOVEUNIT_ACTION.MOVEUNIT_NEXTCHAR, selectionRange.End); if (MarkupHelpers.GetRangeHtmlFast(testRange) == ".") { currentWordRange.End.MoveToPointer(testRange.End); } } } private bool IsRangeInUrl(MarkupRange range) { //must have this range cloned, otherwise in some cases IsInsideURL call // was MOVING the current word range! if "www.foo.com" was in the editor, // when the final "\"" was the current word, this call MOVED the current // word range BACK to www.foo.com, then nextWord would get "\"" and a loop // would occur (bug 411528) range = range.Clone(); IMarkupPointer2Raw p2StartRaw = (IMarkupPointer2Raw)range.Start.PointerRaw; bool insideUrl; p2StartRaw.IsInsideURL(range.End.PointerRaw, out insideUrl); return insideUrl; } /// <summary> /// Get the text of the current word /// </summary> public string CurrentWord { get { return currentWordRange.Text ?? ""; } } public void PlaceCursor() { currentWordRange.Collapse(false); currentWordRange.ToTextRange().select(); } /// <summary> /// Highlight the current word /// </summary> public void Highlight(int offset, int length) { // select word MarkupRange highlightRange = currentWordRange.Clone(); MarkupHelpers.AdjustMarkupRange(highlightRange, offset, length); try { highlightRange.ToTextRange().select(); } catch (COMException ce) { // Fix bug 772709: This error happens when we try to select un-selectable objects. if (ce.ErrorCode != unchecked((int)0x800A025E)) throw; } } /// <summary> /// Remove highlighting from the document /// </summary> public void RemoveHighlight() { // clear document selection try { ((IHTMLDocument2) (htmlDocument)).selection.empty(); } catch (COMException ce) { if (ce.ErrorCode != unchecked((int)0x800A025E)) throw; } } /// <summary> /// Replace the text of the current word /// </summary> public void Replace(int offset, int length, string newText) { MarkupRange origRange = currentWordRange.Clone(); // set the text currentWordRange.Text = StringHelper.Replace(currentWordRange.Text, offset, length, newText); damageFunction(origRange); } /// <summary> /// Markup services for mshtml control /// </summary> private MshtmlMarkupServices MarkupServices { get { return markupServices; } } /// <summary> /// Control we are providing a word range for /// </summary> //private MshtmlControl mshtmlControl ; private IHTMLDocument htmlDocument; private MshtmlMarkupServices markupServices; /// <summary> /// Range over which we are iterating /// </summary> private MarkupRange selectionRange; public MarkupRange SelectionRange { get { return selectionRange; } } /// <summary> /// In order to fix the "vs." defect (trailing periods need to /// be included in spell checked words) we adjust the currentWordRange.End /// to include trailing periods. This has the effect of triggering /// the "word start jumped past word end" assert in some circumstances /// (try typing "foo.. bar"). The currentVirtualPosition tells us how to /// undo the currentWordRange.End adjustment right before attempting /// to navigate to the next word. /// </summary> private MarkupPointer currentVirtualPosition; private IHTMLTxtRange stagingTextRange; /// <summary> /// Pointer to current word /// </summary> private MarkupRange currentWordRange; public MarkupRange CurrentWordRange { get { return currentWordRange; } } } }
#region License // Copyright 2010 Buu Nguyen, Morten Mertner // // 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. // // The latest version of this file can be found at http://fasterflect.codeplex.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Fasterflect.Emitter; namespace Fasterflect { /// <summary> /// Extension methods for locating and accessing properties. /// </summary> public static class PropertyExtensions { #region Property Access /// <summary> /// Sets the property specified by <param name="name"/> on the given <param name="obj"/> to the /// specified <param name="value" />. /// </summary> /// <returns><paramref name="obj"/>.</returns> public static object SetPropertyValue( this object obj, string name, object value ) { DelegateForSetPropertyValue( obj.GetTypeAdjusted(), name )( obj, value ); return obj; } /// <summary> /// Gets the value of the property specified by <param name="name"/> on the given <param name="obj"/>. /// </summary> public static object GetPropertyValue( this object obj, string name ) { return DelegateForGetPropertyValue( obj.GetTypeAdjusted(), name )( obj ); } /// <summary> /// Sets the property specified by <param name="name"/> matching <param name="bindingFlags"/> /// on the given <param name="obj"/> to the specified <param name="value" />. /// </summary> /// <returns><paramref name="obj"/>.</returns> public static object SetPropertyValue( this object obj, string name, object value, Flags bindingFlags ) { DelegateForSetPropertyValue( obj.GetTypeAdjusted(), name, bindingFlags )( obj, value ); return obj; } /// <summary> /// Gets the value of the property specified by <param name="name"/> matching <param name="bindingFlags"/> /// on the given <param name="obj"/>. /// </summary> public static object GetPropertyValue( this object obj, string name, Flags bindingFlags ) { return DelegateForGetPropertyValue( obj.GetTypeAdjusted(), name, bindingFlags )( obj ); } /// <summary> /// Sets the property specified by <param name="memberExpression"/> on the given <param name="obj"/> to the /// specified <param name="value" />. /// </summary> /// <returns><paramref name="obj"/>.</returns> public static object SetPropertyValue( this object obj, Expression<Func<object>> memberExpression, object value ) { var body = memberExpression != null ? memberExpression.Body as MemberExpression : null; if( body == null || body.Member == null ) { throw new ArgumentNullException( "memberExpression" ); } return obj.SetPropertyValue( body.Member.Name, value ); } /// <summary> /// Gets the value of the property specified by <param name="memberExpression"/> on the given <param name="obj"/>. /// </summary> public static object GetPropertyValue( this object obj, Expression<Func<object>> memberExpression ) { var body = memberExpression != null ? memberExpression.Body as MemberExpression : null; if( body == null || body.Member == null ) { throw new ArgumentNullException( "memberExpression" ); } return obj.GetPropertyValue( body.Member.Name ); } /// <summary> /// Creates a delegate which can set the value of the property specified by <param name="name"/> /// on the given <param name="type"/>. /// </summary> public static MemberSetter DelegateForSetPropertyValue( this Type type, string name ) { return DelegateForSetPropertyValue( type, name, Flags.StaticInstanceAnyVisibility ); } /// <summary> /// Creates a delegate which can get the value of the property specified by <param name="name"/> /// on the given <param name="type"/>. /// </summary> public static MemberGetter DelegateForGetPropertyValue( this Type type, string name ) { return DelegateForGetPropertyValue( type, name, Flags.StaticInstanceAnyVisibility ); } /// <summary> /// Creates a delegate which can set the value of the property specified by <param name="name"/> /// matching <param name="bindingFlags"/> on the given <param name="type"/>. /// </summary> public static MemberSetter DelegateForSetPropertyValue( this Type type, string name, Flags bindingFlags ) { var callInfo = new CallInfo(type, null, bindingFlags, MemberTypes.Property, name, null, null, false); return (MemberSetter) new MemberSetEmitter( callInfo ).GetDelegate(); } /// <summary> /// Creates a delegate which can get the value of the property specified by <param name="name"/> /// matching <param name="bindingFlags"/> on the given <param name="type"/>. /// </summary> public static MemberGetter DelegateForGetPropertyValue( this Type type, string name, Flags bindingFlags ) { var callInfo = new CallInfo(type, null, bindingFlags, MemberTypes.Property, name, null, null, true); return (MemberGetter) new MemberGetEmitter( callInfo ).GetDelegate(); } #endregion #region Indexer Access /// <summary> /// Sets the value of the indexer of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be set.</param> /// <param name="parameters">The list of the indexer parameters plus the value to be set to the indexer. /// The parameter types are determined from these parameters, therefore no parameter can be <c>null</c>. /// If any parameter is <c>null</c> (or you can't be sure of that, i.e. receive from a variable), /// use a different overload of this method.</param> /// <returns>The object whose indexer is to be set.</returns> /// <example> /// If the indexer is of type <c>string</c> and accepts one parameter of type <c>int</c>, this /// method should be invoked as follow: /// <code> /// obj.SetIndexer(new Type[]{typeof(int), typeof(string)}, new object[]{1, "a"}); /// </code> /// </example> public static object SetIndexer( this object obj, params object[] parameters ) { DelegateForSetIndexer( obj.GetTypeAdjusted(), parameters.ToTypeArray() )( obj, parameters ); return obj; } /// <summary> /// Sets the value of the indexer of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be set.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order), plus /// the type of the indexer.</param> /// <param name="parameters">The list of the indexer parameters plus the value to be set to the indexer. /// This list must match with the <paramref name="parameterTypes"/> list.</param> /// <returns>The object whose indexer is to be set.</returns> /// <example> /// If the indexer is of type <c>string</c> and accepts one parameter of type <c>int</c>, this /// method should be invoked as follow: /// <code> /// obj.SetIndexer(new Type[]{typeof(int), typeof(string)}, new object[]{1, "a"}); /// </code> /// </example> public static object SetIndexer( this object obj, Type[] parameterTypes, params object[] parameters ) { DelegateForSetIndexer( obj.GetTypeAdjusted(), parameterTypes )( obj, parameters ); return obj; } /// <summary> /// Gets the value of the indexer of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be retrieved.</param> /// <param name="parameters">The list of the indexer parameters. /// The parameter types are determined from these parameters, therefore no parameter can be <code>null</code>. /// If any parameter is <code>null</code> (or you can't be sure of that, i.e. receive from a variable), /// use a different overload of this method.</param> /// <returns>The value returned by the indexer.</returns> public static object GetIndexer( this object obj, params object[] parameters ) { return DelegateForGetIndexer( obj.GetTypeAdjusted(), parameters.ToTypeArray() )( obj, parameters ); } /// <summary> /// Gets the value of the indexer of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be retrieved.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order).</param> /// <param name="parameters">The list of the indexer parameters.</param> /// <returns>The value returned by the indexer.</returns> public static object GetIndexer( this object obj, Type[] parameterTypes, params object[] parameters ) { return DelegateForGetIndexer( obj.GetTypeAdjusted(), parameterTypes )( obj, parameters ); } /// <summary> /// Sets the value of the indexer matching <paramref name="bindingFlags"/> of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be set.</param> /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param> /// <param name="parameters">The list of the indexer parameters plus the value to be set to the indexer. /// The parameter types are determined from these parameters, therefore no parameter can be <c>null</c>. /// If any parameter is <c>null</c> (or you can't be sure of that, i.e. receive from a variable), /// use a different overload of this method.</param> /// <returns>The object whose indexer is to be set.</returns> /// <example> /// If the indexer is of type <c>string</c> and accepts one parameter of type <c>int</c>, this /// method should be invoked as follow: /// <code> /// obj.SetIndexer(new Type[]{typeof(int), typeof(string)}, new object[]{1, "a"}); /// </code> /// </example> public static object SetIndexer( this object obj, Flags bindingFlags, params object[] parameters ) { DelegateForSetIndexer( obj.GetTypeAdjusted(), bindingFlags, parameters.ToTypeArray() )( obj, parameters ); return obj; } /// <summary> /// Sets the value of the indexer matching <paramref name="bindingFlags"/> of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be set.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order), plus /// the type of the indexer.</param> /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param> /// <param name="parameters">The list of the indexer parameters plus the value to be set to the indexer. /// This list must match with the <paramref name="parameterTypes"/> list.</param> /// <returns>The object whose indexer is to be set.</returns> /// <example> /// If the indexer is of type <c>string</c> and accepts one parameter of type <c>int</c>, this /// method should be invoked as follow: /// <code> /// obj.SetIndexer(new Type[]{typeof(int), typeof(string)}, new object[]{1, "a"}); /// </code> /// </example> public static object SetIndexer( this object obj, Type[] parameterTypes, Flags bindingFlags, params object[] parameters ) { DelegateForSetIndexer( obj.GetTypeAdjusted(), bindingFlags, parameterTypes )( obj, parameters ); return obj; } /// <summary> /// Gets the value of the indexer matching <paramref name="bindingFlags"/> of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be retrieved.</param> /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param> /// <param name="parameters">The list of the indexer parameters. /// The parameter types are determined from these parameters, therefore no parameter can be <code>null</code>. /// If any parameter is <code>null</code> (or you can't be sure of that, i.e. receive from a variable), /// use a different overload of this method.</param> /// <returns>The value returned by the indexer.</returns> public static object GetIndexer( this object obj, Flags bindingFlags, params object[] parameters ) { return DelegateForGetIndexer( obj.GetTypeAdjusted(), bindingFlags, parameters.ToTypeArray() )( obj, parameters ); } /// <summary> /// Gets the value of the indexer matching <paramref name="bindingFlags"/> of the given <paramref name="obj"/> /// </summary> /// <param name="obj">The object whose indexer is to be retrieved.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order).</param> /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param> /// <param name="parameters">The list of the indexer parameters.</param> /// <returns>The value returned by the indexer.</returns> public static object GetIndexer( this object obj, Type[] parameterTypes, Flags bindingFlags, params object[] parameters ) { return DelegateForGetIndexer( obj.GetTypeAdjusted(), bindingFlags, parameterTypes )( obj, parameters ); } /// <summary> /// Creates a delegate which can set an indexer /// </summary> /// <param name="type">The type which the indexer belongs to.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order), plus /// the type of the indexer.</param> /// <returns>A delegate which can set an indexer.</returns> /// <example> /// If the indexer is of type <c>string</c> and accepts one parameter of type <c>int</c>, this /// method should be invoked as follow: /// <code> /// MethodInvoker invoker = type.DelegateForSetIndexer(new Type[]{typeof(int), typeof(string)}); /// </code> /// </example> public static MethodInvoker DelegateForSetIndexer( this Type type, params Type[] parameterTypes ) { return DelegateForSetIndexer( type, Flags.InstanceAnyVisibility, parameterTypes ); } /// <summary> /// Creates a delegate which can get the value of an indexer. /// </summary> /// <param name="type">The type which the indexer belongs to.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order).</param> /// <returns>The delegate which can get the value of an indexer.</returns> public static MethodInvoker DelegateForGetIndexer( this Type type, params Type[] parameterTypes ) { return DelegateForGetIndexer( type, Flags.InstanceAnyVisibility, parameterTypes ); } /// <summary> /// Creates a delegate which can set an indexer matching <paramref name="bindingFlags"/>. /// </summary> /// <param name="type">The type which the indexer belongs to.</param> /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order), plus /// the type of the indexer.</param> /// <returns>A delegate which can set an indexer.</returns> /// <example> /// If the indexer is of type <c>string</c> and accepts one parameter of type <c>int</c>, this /// method should be invoked as follow: /// <code> /// MethodInvoker invoker = type.DelegateForSetIndexer(new Type[]{typeof(int), typeof(string)}); /// </code> /// </example> public static MethodInvoker DelegateForSetIndexer( this Type type, Flags bindingFlags, params Type[] parameterTypes ) { return (MethodInvoker) new MethodInvocationEmitter( type, bindingFlags, Constants.IndexerSetterName, parameterTypes ). GetDelegate(); } /// <summary> /// Creates a delegate which can get the value of an indexer matching <paramref name="bindingFlags"/>. /// </summary> /// <param name="type">The type which the indexer belongs to.</param> /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param> /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order).</param> /// <returns>The delegate which can get the value of an indexer.</returns> public static MethodInvoker DelegateForGetIndexer( this Type type, Flags bindingFlags, params Type[] parameterTypes ) { return (MethodInvoker) new MethodInvocationEmitter( type, bindingFlags, Constants.IndexerGetterName, parameterTypes ). GetDelegate(); } #endregion #region Property Lookup (Single) /// <summary> /// Gets the property identified by <paramref name="name"/> on the given <paramref name="type"/>. This method /// searches for public and non-public instance properties on both the type itself and all parent classes. /// </summary> /// <returns>A single PropertyInfo instance of the first found match or null if no match was found.</returns> public static PropertyInfo Property( this Type type, string name ) { return type.Property( name, Flags.InstanceAnyVisibility ); } /// <summary> /// Gets the property identified by <paramref name="name"/> on the given <paramref name="type"/>. /// Use the <paramref name="bindingFlags"/> parameter to define the scope of the search. /// </summary> /// <returns>A single PropertyInfo instance of the first found match or null if no match was found.</returns> public static PropertyInfo Property( this Type type, string name, Flags bindingFlags ) { // we need to check all properties to do partial name matches if( bindingFlags.IsAnySet( Flags.PartialNameMatch | Flags.TrimExplicitlyImplemented ) ) { return type.Properties( bindingFlags, name ).FirstOrDefault(); } var result = type.GetProperty( name, bindingFlags ); if( result == null && bindingFlags.IsNotSet( Flags.DeclaredOnly ) ) { if( type.BaseType != typeof(object) && type.BaseType != null ) { return type.BaseType.Property( name, bindingFlags ); } } bool hasSpecialFlags = bindingFlags.IsSet( Flags.ExcludeExplicitlyImplemented ); if( hasSpecialFlags ) { IList<PropertyInfo> properties = new List<PropertyInfo> { result }; properties = properties.Filter( bindingFlags ); return properties.Count > 0 ? properties[ 0 ] : null; } return result; } #endregion #region Property Lookup (Multiple) /// <summary> /// Gets all public and non-public instance properties on the given <paramref name="type"/>, /// including properties defined on base types. The result can optionally be filtered by specifying /// a list of property names to include using the <paramref name="names"/> parameter. /// </summary> /// <returns>A list of matching instance properties on the type.</returns> /// <param name="type">The type whose public properties are to be retrieved.</param> /// <param name="names">A list of names of properties to be retrieved. If this is <c>null</c>, /// all properties are returned.</param> /// <returns>A list of all public properties on the type filted by <paramref name="names"/>. /// This value will never be null.</returns> public static IList<PropertyInfo> Properties( this Type type, params string[] names ) { return type.Properties( Flags.InstanceAnyVisibility, names ); } /// <summary> /// Gets all properties on the given <paramref name="type"/> that match the specified <paramref name="bindingFlags"/>, /// including properties defined on base types. /// </summary> /// <returns>A list of all matching properties on the type. This value will never be null.</returns> public static IList<PropertyInfo> Properties( this Type type, Flags bindingFlags, params string[] names ) { if (type == null || type == Constants.ObjectType) { return Constants.EmptyPropertyInfoArray; } bool recurse = bindingFlags.IsNotSet( Flags.DeclaredOnly ); bool hasNames = names != null && names.Length > 0; bool hasSpecialFlags = bindingFlags.IsAnySet( Flags.ExcludeBackingMembers | Flags.ExcludeExplicitlyImplemented | Flags.ExcludeHiddenMembers ); if( ! recurse && ! hasNames && ! hasSpecialFlags ) { return type.GetProperties( bindingFlags ) ?? Constants.EmptyPropertyInfoArray; } var properties = GetProperties( type, bindingFlags ); properties = hasSpecialFlags ? properties.Filter( bindingFlags ) : properties; properties = hasNames ? properties.Filter( bindingFlags, names ) : properties; return properties; } private static IList<PropertyInfo> GetProperties( Type type, Flags bindingFlags ) { bool recurse = bindingFlags.IsNotSet( Flags.DeclaredOnly ); if( ! recurse ) { return type.GetProperties( bindingFlags ) ?? Constants.EmptyPropertyInfoArray; } bindingFlags |= Flags.DeclaredOnly; bindingFlags &= ~BindingFlags.FlattenHierarchy; var properties = new List<PropertyInfo>(); properties.AddRange( type.GetProperties( bindingFlags ) ); Type baseType = type.BaseType; while( baseType != null && baseType != typeof(object) ) { properties.AddRange( baseType.GetProperties( bindingFlags ) ); baseType = baseType.BaseType; } return properties; } #endregion #region Property Combined #region TryGetValue /// <summary> /// Gets the first (public or non-public) instance property with the given <paramref name="name"/> on the given /// <paramref name="obj"/> object. Returns the value of the property if a match was found and null otherwise. /// </summary> /// <remarks> /// When using this method it is not possible to distinguish between a missing property and a property whose value is null. /// </remarks> /// <param name="obj">The source object on which to find the property</param> /// <param name="name">The name of the property whose value should be retrieved</param> /// <returns>The value of the property or null if no property was found</returns> public static object TryGetPropertyValue( this object obj, string name ) { return TryGetPropertyValue( obj, name, Flags.InstanceAnyVisibility ); } /// <summary> /// Gets the first property with the given <paramref name="name"/> on the given <paramref name="obj"/> object. /// Returns the value of the property if a match was found and null otherwise. /// Use the <paramref name="bindingFlags"/> parameter to limit the scope of the search. /// </summary> /// <remarks> /// When using this method it is not possible to distinguish between a missing property and a property whose value is null. /// </remarks> /// <param name="obj">The source object on which to find the property</param> /// <param name="name">The name of the property whose value should be retrieved</param> /// <param name="bindingFlags">A combination of Flags that define the scope of the search</param> /// <returns>The value of the property or null if no property was found</returns> public static object TryGetPropertyValue( this object obj, string name, Flags bindingFlags ) { try { return obj.GetPropertyValue( name, bindingFlags ); } catch( MissingMemberException ) { return null; } } #endregion #region TrySetValue /// <summary> /// Sets the first (public or non-public) instance property with the given <paramref name="name"/> on the /// given <paramref name="obj"/> object to the supplied <paramref name="value"/>. Returns true /// if a value was assigned to a property and false otherwise. /// </summary> /// <param name="obj">The source object on which to find the property</param> /// <param name="name">The name of the property whose value should be retrieved</param> /// <param name="value">The value that should be assigned to the property</param> /// <returns>True if the value was assigned to a property and false otherwise</returns> public static bool TrySetPropertyValue( this object obj, string name, object value ) { return TrySetPropertyValue( obj, name, value, Flags.InstanceAnyVisibility ); } /// <summary> /// Sets the first property with the given <paramref name="name"/> on the given <paramref name="obj"/> object /// to the supplied <paramref name="value"/>. Returns true if a value was assigned to a property and false otherwise. /// Use the <paramref name="bindingFlags"/> parameter to limit the scope of the search. /// </summary> /// <param name="obj">The source object on which to find the property</param> /// <param name="name">The name of the property whose value should be retrieved</param> /// <param name="value">The value that should be assigned to the property</param> /// <param name="bindingFlags">A combination of Flags that define the scope of the search</param> /// <returns>True if the value was assigned to a property and false otherwise</returns> public static bool TrySetPropertyValue( this object obj, string name, object value, Flags bindingFlags ) { try { obj.SetPropertyValue( name, value, bindingFlags ); return true; } catch (MissingMemberException) { return false; } } #endregion #endregion } }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // 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 Yaapii.Atoms.Enumerable; using Yaapii.Atoms.Fail; namespace Yaapii.Atoms.Scalar { /// <summary> /// First element in <see cref="IEnumerable{T}"/>. /// </summary> /// <typeparam name="T"></typeparam> public sealed class FirstOf<T> : ScalarEnvelope<T> { /// <summary> /// Element from position in a <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="ex">Exception to throw if no value can be found.</param> public FirstOf(IEnumerable<T> source, Exception ex) : this( (enm) => true, source, (enm) => throw ex ) { } public FirstOf(IEnumerable<T> source) : this( (enm) => true, source, new NoSuchElementException("Cannot get first element - no match.") ) { } /// <summary> /// Element from position in a <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="condition">condition to find the desired item</param> public FirstOf(Func<T, bool> condition, IEnumerable<T> source) : this( condition, source, new NoSuchElementException("Cannot get first element - no match.") ) { } /// <summary> /// Element from position in a <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="condition">condition to find the desired item</param> /// <param name="ex">Exception to throw if no value can be found.</param> public FirstOf(Func<T, bool> condition, IEnumerable<T> source, Exception ex) : this( condition, source, (enm) => { throw ex; } ) { } /// <summary> /// First element in a <see cref="IEnumerable{T}"/> with a fallback value. /// </summary> /// <param name="source">source enum</param> /// <param name="fallback">fallback func</param> public FirstOf(IEnumerable<T> source, T fallback) : this( enm => true, source, (b) => fallback ) { } /// <summary> /// First element in a <see cref="IEnumerable{T}"/> with a fallback value. /// </summary> /// <param name="source">source enum</param> /// <param name="fallback">fallback func</param> /// <param name="condition">condition to match in order to find the desired item</param> public FirstOf(Func<T, bool> condition, IEnumerable<T> source, T fallback) : this( condition, source, (b) => fallback ) { } /// <summary> /// First Element in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="fallback">fallback func</param> public FirstOf(IEnumerable<T> source, IScalar<T> fallback) : this( enm => true, source, (enm) => fallback.Value() ) { } /// <summary> /// First element in a <see cref="IEnumerable{T}"/> fallback function <see cref="IBiFunc{X, Y, Z}"/> /// </summary> /// <param name="src">source enumerable</param> /// <param name="fallback">fallback if no match</param> public FirstOf(IEnumerable<T> src, Func<IEnumerable<T>, T> fallback) : this(item => true, src, fallback) { } /// <summary> /// First element in a <see cref="IEnumerable{T}"/> fallback function <see cref="IBiFunc{X, Y, Z}"/> /// </summary> /// <param name="src">source enumerable</param> /// <param name="fallback">fallback if no match</param> /// <param name="condition">condition to match</param> public FirstOf(Func<T, bool> condition, IEnumerable<T> src, Func<IEnumerable<T>, T> fallback) : base(() => { var filtered = new Filtered<T>(condition, src).GetEnumerator(); T result; if (filtered.MoveNext()) { result = filtered.Current; } else { result = fallback(src); } return result; }) { } } public static class FirstOf { /// <summary> /// Element from position in a <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="ex">Exception to throw if no value can be found.</param> public static IScalar<T> New<T>(IEnumerable<T> source, Exception ex) => new FirstOf<T>(source, ex); public static IScalar<T> New<T>(IEnumerable<T> source) => new FirstOf<T>(source); /// <summary> /// Element from position in a <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="condition">condition to find the desired item</param> public static IScalar<T> New<T>(Func<T, bool> condition, IEnumerable<T> source) => new FirstOf<T>(condition, source); /// <summary> /// Element from position in a <see cref="IEnumerable{T}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="condition">condition to find the desired item</param> /// <param name="ex">Exception to throw if no value can be found.</param> public static IScalar<T> New<T>(Func<T, bool> condition, IEnumerable<T> source, Exception ex) => new FirstOf<T>(condition, source, ex); /// <summary> /// First element in a <see cref="IEnumerable{T}"/> with a fallback value. /// </summary> /// <param name="source">source enum</param> /// <param name="fallback">fallback func</param> public static IScalar<T> New<T>(IEnumerable<T> source, T fallback) => new FirstOf<T>(source, fallback); /// <summary> /// First element in a <see cref="IEnumerable{T}"/> with a fallback value. /// </summary> /// <param name="source">source enum</param> /// <param name="fallback">fallback func</param> /// <param name="condition">condition to match in order to find the desired item</param> public static IScalar<T> New<T>(Func<T, bool> condition, IEnumerable<T> source, T fallback) => new FirstOf<T>(condition, source, fallback); /// <summary> /// First Element in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>. /// </summary> /// <param name="source">source enum</param> /// <param name="fallback">fallback func</param> public static IScalar<T> New<T>(IEnumerable<T> source, IScalar<T> fallback) => new FirstOf<T>(source, fallback); /// <summary> /// First element in a <see cref="IEnumerable{T}"/> fallback function <see cref="IBiFunc{X, Y, Z}"/> /// </summary> /// <param name="src">source enumerable</param> /// <param name="fallback">fallback if no match</param> public static IScalar<T> New<T>(IEnumerable<T> src, Func<IEnumerable<T>, T> fallback) => new FirstOf<T>(src, fallback); /// <summary> /// First element in a <see cref="IEnumerable{T}"/> fallback function <see cref="IBiFunc{X, Y, Z}"/> /// </summary> /// <param name="src">source enumerable</param> /// <param name="fallback">fallback if no match</param> /// <param name="condition">condition to match</param> public static IScalar<T> New<T>(Func<T, bool> condition, IEnumerable<T> src, Func<IEnumerable<T>, T> fallback) => new FirstOf<T>(condition, src, fallback); } }